diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-27 16:51:28 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-27 16:51:28 +0000 |
commit | 940b4d1848e8c70ab7642901a68594e8016caffc (patch) | |
tree | eb72f344ee6c3d9b80a7ecc079ea79e9fba8676d /svtools | |
parent | Initial commit. (diff) | |
download | libreoffice-940b4d1848e8c70ab7642901a68594e8016caffc.tar.xz libreoffice-940b4d1848e8c70ab7642901a68594e8016caffc.zip |
Adding upstream version 1:7.0.4.upstream/1%7.0.4upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'svtools')
195 files changed, 72619 insertions, 0 deletions
diff --git a/svtools/AllLangMoTarget_svt.mk b/svtools/AllLangMoTarget_svt.mk new file mode 100644 index 000000000..dc1ad301c --- /dev/null +++ b/svtools/AllLangMoTarget_svt.mk @@ -0,0 +1,13 @@ +# -*- Mode: makefile-gmake; tab-width: 4; indent-tabs-mode: t -*- +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +$(eval $(call gb_AllLangMoTarget_AllLangMoTarget,svt)) + +$(eval $(call gb_AllLangMoTarget_set_polocation,svt,svtools)) + +# vim: set noet sw=4 ts=4: diff --git a/svtools/CppunitTest_svtools_dialogs_test.mk b/svtools/CppunitTest_svtools_dialogs_test.mk new file mode 100644 index 000000000..70f8a00e4 --- /dev/null +++ b/svtools/CppunitTest_svtools_dialogs_test.mk @@ -0,0 +1,69 @@ +# -*- Mode: makefile-gmake; tab-width: 4; indent-tabs-mode: t -*- +#************************************************************************* +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# +#************************************************************************* + +$(eval $(call gb_CppunitTest_CppunitScreenShot,svtools_dialogs_test)) + +$(eval $(call gb_CppunitTest_add_exception_objects,svtools_dialogs_test, \ + svtools/qa/unit/svtools-dialogs-test \ +)) + +$(eval $(call gb_CppunitTest_use_sdk_api,svtools_dialogs_test)) + +$(eval $(call gb_CppunitTest_set_include,svtools_dialogs_test,\ + -I$(SRCDIR)/svtools/source/inc \ + -I$(SRCDIR)/svtools/inc \ + $$(INCLUDE) \ +)) + +$(eval $(call gb_CppunitTest_use_libraries,svtools_dialogs_test, \ + basegfx \ + comphelper \ + cppu \ + cppuhelper \ + drawinglayer \ + editeng \ + i18nlangtag \ + i18nutil \ + msfilter \ + oox \ + sal \ + salhelper \ + sax \ + sfx \ + sot \ + svl \ + svt \ + test \ + tl \ + tk \ + ucbhelper \ + unotest \ + utl \ + vcl \ + xo \ +)) + +$(eval $(call gb_CppunitTest_use_external,svtools_dialogs_test,boost_headers)) + +$(eval $(call gb_CppunitTest_use_sdk_api,svtools_dialogs_test)) + +$(eval $(call gb_CppunitTest_use_ure,svtools_dialogs_test)) +$(eval $(call gb_CppunitTest_use_vcl_non_headless_with_windows,svtools_dialogs_test)) + +$(eval $(call gb_CppunitTest_use_rdb,svtools_dialogs_test,services)) + +$(eval $(call gb_CppunitTest_use_configuration,svtools_dialogs_test)) + +$(eval $(call gb_CppunitTest_use_uiconfigs,svtools_dialogs_test,\ + svt \ +)) + +# vim: set noet sw=4 ts=4: diff --git a/svtools/CppunitTest_svtools_graphic.mk b/svtools/CppunitTest_svtools_graphic.mk new file mode 100644 index 000000000..04e562e16 --- /dev/null +++ b/svtools/CppunitTest_svtools_graphic.mk @@ -0,0 +1,57 @@ +# -*- Mode: makefile-gmake; tab-width: 4; indent-tabs-mode: t -*- +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# + +$(eval $(call gb_CppunitTest_CppunitTest,svtools_graphic)) + +$(eval $(call gb_CppunitTest_use_externals,svtools_graphic,\ + boost_headers \ + libxml2 \ +)) + +$(eval $(call gb_CppunitTest_use_api,svtools_graphic,\ + udkapi \ + offapi \ + oovbaapi \ +)) + +$(eval $(call gb_CppunitTest_use_ure,svtools_graphic)) + +$(eval $(call gb_CppunitTest_use_vcl,svtools_graphic)) + +$(eval $(call gb_CppunitTest_use_libraries,svtools_graphic, \ + comphelper \ + cppu \ + cppuhelper \ + tl \ + sal \ + svt \ + sw \ + test \ + unotest \ + vcl \ +)) + +$(eval $(call gb_CppunitTest_set_include,svtools_graphic,\ + -I$(SRCDIR)/sw/inc \ + $$(INCLUDE) \ +)) + +$(eval $(call gb_CppunitTest_use_custom_headers,svtools_graphic,\ + officecfg/registry \ +)) + +$(eval $(call gb_CppunitTest_use_configuration,svtools_graphic)) + +$(eval $(call gb_CppunitTest_use_rdb,svtools_graphic,services)) + +$(eval $(call gb_CppunitTest_add_exception_objects,svtools_graphic, \ + svtools/qa/unit/GraphicObjectTest \ +)) + +# vim: set noet sw=4 ts=4: diff --git a/svtools/CppunitTest_svtools_html.mk b/svtools/CppunitTest_svtools_html.mk new file mode 100644 index 000000000..6fbca2c06 --- /dev/null +++ b/svtools/CppunitTest_svtools_html.mk @@ -0,0 +1,30 @@ +# -*- Mode: makefile-gmake; tab-width: 4; indent-tabs-mode: t -*- +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# + +$(eval $(call gb_CppunitTest_CppunitTest,svtools_html)) + +$(eval $(call gb_CppunitTest_use_external,svtools_html,boost_headers)) + +$(eval $(call gb_CppunitTest_use_sdk_api,svtools_html)) + +$(eval $(call gb_CppunitTest_add_exception_objects,svtools_html, \ + svtools/qa/unit/testHtmlReader \ + svtools/qa/unit/testHtmlWriter \ +)) + +$(eval $(call gb_CppunitTest_use_libraries,svtools_html, \ + comphelper \ + cppu \ + cppuhelper \ + tl \ + sal \ + svt \ +)) + +# vim: set noet sw=4 ts=4: diff --git a/svtools/Executable_langsupport.mk b/svtools/Executable_langsupport.mk new file mode 100644 index 000000000..176a88b15 --- /dev/null +++ b/svtools/Executable_langsupport.mk @@ -0,0 +1,40 @@ +# -*- Mode: makefile-gmake; tab-width: 4; indent-tabs-mode: t -*- +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# + +$(eval $(call gb_Executable_Executable,langsupport)) + +$(eval $(call gb_Executable_set_targettype_gui,langsupport,YES)) + +$(eval $(call gb_Executable_set_include,langsupport,\ + $$(INCLUDE) \ + -I$(SRCDIR)/svtools/inc \ + -I$(SRCDIR)/svtools/source/inc \ +)) + +$(eval $(call gb_Executable_use_external,langsupport,boost_headers)) + +$(eval $(call gb_Executable_use_sdk_api,langsupport)) + +$(eval $(call gb_Executable_use_libraries,langsupport,\ + comphelper \ + cppu \ + cppuhelper \ + i18nlangtag \ + sal \ + svt \ + tl \ + ucbhelper \ + vcl \ +)) + +$(eval $(call gb_Executable_add_exception_objects,langsupport,\ + svtools/langsupport/langsupport \ +)) + +# vim: set noet sw=4 ts=4: diff --git a/svtools/IwyuFilter_svtools.yaml b/svtools/IwyuFilter_svtools.yaml new file mode 100644 index 000000000..8e4a3400d --- /dev/null +++ b/svtools/IwyuFilter_svtools.yaml @@ -0,0 +1,16 @@ +--- +assumeFilename: svtools/source/control/ruler.cxx +blacklist: + svtools/source/control/accessibleruler.hxx: + # base class has to be a complete type + - com/sun/star/accessibility/XAccessible.hpp + - com/sun/star/accessibility/XAccessibleComponent.hpp + - com/sun/star/accessibility/XAccessibleContext.hpp + - com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp + - com/sun/star/lang/XServiceInfo.hpp + svtools/source/dialogs/insdlg.cxx: + # Needed on WIN + - comphelper/classids.hxx + svtools/qa/unit/testHtmlReader.cxx: + # Needed for the CPPUNIT_TEST_FIXTURE() macro. + - unotest/bootstrapfixturebase.hxx diff --git a/svtools/JunitTest_svtools_unoapi.mk b/svtools/JunitTest_svtools_unoapi.mk new file mode 100644 index 000000000..7ba0c75e9 --- /dev/null +++ b/svtools/JunitTest_svtools_unoapi.mk @@ -0,0 +1,24 @@ +# -*- Mode: makefile-gmake; tab-width: 4; indent-tabs-mode: t -*- +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# +# This file incorporates work covered by the following license notice: +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed +# with this work for additional information regarding copyright +# ownership. The ASF licenses this file to you under the Apache +# License, Version 2.0 (the "License"); you may not use this file +# except in compliance with the License. You may obtain a copy of +# the License at http://www.apache.org/licenses/LICENSE-2.0 . +# + +$(eval $(call gb_JunitTest_JunitTest,svtools_unoapi)) + +$(eval $(call gb_JunitTest_set_unoapi_test_defaults,svtools_unoapi)) + +# vim: set noet sw=4 ts=4: diff --git a/svtools/Library_svt.mk b/svtools/Library_svt.mk new file mode 100644 index 000000000..3723fe67b --- /dev/null +++ b/svtools/Library_svt.mk @@ -0,0 +1,197 @@ +# -*- Mode: makefile-gmake; tab-width: 4; indent-tabs-mode: t -*- +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# +# This file incorporates work covered by the following license notice: +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed +# with this work for additional information regarding copyright +# ownership. The ASF licenses this file to you under the Apache +# License, Version 2.0 (the "License"); you may not use this file +# except in compliance with the License. You may obtain a copy of +# the License at http://www.apache.org/licenses/LICENSE-2.0 . +# + +$(eval $(call gb_Library_Library,svt)) + +$(eval $(call gb_Library_set_precompiled_header,svt,svtools/inc/pch/precompiled_svt)) + +$(eval $(call gb_Library_set_componentfile,svt,svtools/util/svt)) + +$(eval $(call gb_Library_use_custom_headers,svt,\ + officecfg/registry \ +)) + +$(eval $(call gb_Library_use_sdk_api,svt)) + +$(eval $(call gb_Library_set_include,svt,\ + $$(INCLUDE) \ + -I$(SRCDIR)/svtools/source/inc \ + -I$(SRCDIR)/svtools/inc \ +)) + +$(eval $(call gb_Library_add_defs,svt,\ + -DSVT_DLLIMPLEMENTATION \ +)) + +$(eval $(call gb_Library_use_libraries,svt,\ + basegfx \ + comphelper \ + cppu \ + cppuhelper \ + i18nlangtag \ + i18nutil \ + $(if $(ENABLE_JAVA), \ + jvmfwk) \ + salhelper \ + sal \ + sot \ + svl \ + tk \ + tl \ + ucbhelper \ + utl \ + vcl \ +)) + +$(eval $(call gb_Library_use_externals,svt,\ + boost_headers \ + icuuc \ + icu_headers \ +)) + +$(eval $(call gb_Library_add_exception_objects,svt,\ + svtools/source/brwbox/brwbox1 \ + svtools/source/brwbox/brwbox2 \ + svtools/source/brwbox/brwbox3 \ + svtools/source/brwbox/brwhead \ + svtools/source/brwbox/datwin \ + svtools/source/brwbox/ebbcontrols \ + svtools/source/brwbox/editbrowsebox \ + svtools/source/brwbox/editbrowsebox2 \ + svtools/source/config/accessibilityoptions \ + svtools/source/config/apearcfg \ + svtools/source/config/colorcfg \ + svtools/source/config/extcolorcfg \ + svtools/source/config/fontsubstconfig \ + svtools/source/config/helpopt \ + svtools/source/config/htmlcfg \ + svtools/source/config/itemholder2 \ + svtools/source/config/menuoptions \ + svtools/source/config/miscopt \ + svtools/source/config/slidesorterbaropt \ + svtools/source/config/optionsdrawinglayer \ + svtools/source/config/printoptions \ + svtools/source/contnr/DocumentInfoPreview \ + svtools/source/contnr/querydelete \ + svtools/source/contnr/templwin \ + svtools/source/control/accessibleruler \ + svtools/source/control/asynclink \ + svtools/source/control/calendar \ + svtools/source/control/collatorres \ + svtools/source/control/ctrlbox \ + svtools/source/control/ctrltool \ + svtools/source/control/indexentryres \ + svtools/source/control/inettbc \ + svtools/source/control/managedmenubutton \ + svtools/source/control/ruler \ + svtools/source/control/scriptedtext \ + svtools/source/control/scrwin \ + svtools/source/control/tabbar \ + svtools/source/control/toolbarmenu \ + svtools/source/control/valueacc \ + svtools/source/control/valueset \ + svtools/source/dialogs/addresstemplate \ + svtools/source/dialogs/colrdlg \ + svtools/source/dialogs/insdlg \ + svtools/source/dialogs/PlaceEditDialog \ + svtools/source/dialogs/prnsetup \ + svtools/source/dialogs/restartdialog \ + svtools/source/dialogs/ServerDetailsControls \ + svtools/source/edit/editsyntaxhighlighter \ + svtools/source/edit/svmedit \ + svtools/source/edit/svmedit2 \ + svtools/source/edit/textwindowpeer \ + svtools/source/filter/SvFilterOptionsDialog \ + svtools/source/filter/DocumentToGraphicRenderer \ + svtools/source/filter/exportdialog \ + svtools/source/graphic/renderer \ + svtools/source/hatchwindow/documentcloser \ + svtools/source/hatchwindow/hatchwindow \ + svtools/source/hatchwindow/hatchwindowfactory \ + svtools/source/hatchwindow/ipwin \ + $(if $(ENABLE_JAVA), \ + svtools/source/java/javacontext \ + svtools/source/java/javainteractionhandler) \ + svtools/source/misc/acceleratorexecute \ + svtools/source/misc/bindablecontrolhelper \ + svtools/source/misc/cliplistener \ + svtools/source/misc/dialogclosedlistener \ + svtools/source/misc/ehdl \ + svtools/source/misc/embedhlp \ + svtools/source/misc/embedtransfer \ + svtools/source/misc/filechangedchecker \ + svtools/source/misc/imagemgr \ + svtools/source/misc/imageresourceaccess \ + svtools/source/misc/langtab \ + svtools/source/misc/langhelp \ + svtools/source/misc/openfiledroptargetlistener \ + svtools/source/misc/sampletext \ + svtools/source/misc/stringtransfer \ + svtools/source/misc/svtresid \ + svtools/source/misc/templatefoldercache \ + svtools/source/misc/unitconv \ + svtools/source/svhtml/htmlkywd \ + svtools/source/svhtml/htmlout \ + svtools/source/svhtml/htmlsupp \ + svtools/source/svhtml/HtmlWriter \ + svtools/source/svhtml/parhtml \ + svtools/source/svrtf/parrtf \ + svtools/source/svrtf/rtfkeywd \ + svtools/source/svrtf/rtfout \ + svtools/source/svrtf/svparser \ + svtools/source/table/defaultinputhandler \ + svtools/source/table/gridtablerenderer \ + svtools/source/table/tablecontrol \ + svtools/source/table/tablecontrol_impl \ + svtools/source/table/tabledatawindow \ + svtools/source/table/mousefunction \ + svtools/source/table/cellvalueconversion \ + svtools/source/table/tablegeometry \ + svtools/source/uno/addrtempuno \ + svtools/source/uno/fpicker \ + svtools/source/uno/framestatuslistener \ + svtools/source/uno/generictoolboxcontroller \ + svtools/source/uno/genericunodialog \ + svtools/source/uno/miscservices \ + svtools/source/uno/popupmenucontrollerbase \ + svtools/source/uno/popupwindowcontroller \ + svtools/source/uno/statusbarcontroller \ + svtools/source/uno/svtxgridcontrol \ + svtools/source/uno/toolboxcontroller \ + svtools/source/uno/unocontroltablemodel \ + svtools/source/uno/unogridcolumnfacade \ + svtools/source/uno/unoevent \ + svtools/source/uno/unoiface \ + svtools/source/uno/unoimap \ + svtools/source/uno/wizard/unowizard \ + svtools/source/uno/wizard/wizardpagecontroller \ + svtools/source/uno/wizard/wizardshell \ +)) + +ifeq ($(OS),WNT) +$(eval $(call gb_Library_use_system_win32_libs,svt,\ + advapi32 \ + gdi32 \ + ole32 \ + oleaut32 \ + uuid \ +)) +endif + +# vim: set noet sw=4 ts=4: diff --git a/svtools/Makefile b/svtools/Makefile new file mode 100644 index 000000000..ccb1c85a0 --- /dev/null +++ b/svtools/Makefile @@ -0,0 +1,7 @@ +# -*- Mode: makefile-gmake; tab-width: 4; indent-tabs-mode: t -*- + +module_directory:=$(dir $(realpath $(firstword $(MAKEFILE_LIST)))) + +include $(module_directory)/../solenv/gbuild/partial_build.mk + +# vim: set noet sw=4 ts=4: diff --git a/svtools/Module_svtools.mk b/svtools/Module_svtools.mk new file mode 100644 index 000000000..33af7b522 --- /dev/null +++ b/svtools/Module_svtools.mk @@ -0,0 +1,61 @@ +# -*- Mode: makefile-gmake; tab-width: 4; indent-tabs-mode: t -*- +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# +# This file incorporates work covered by the following license notice: +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed +# with this work for additional information regarding copyright +# ownership. The ASF licenses this file to you under the Apache +# License, Version 2.0 (the "License"); you may not use this file +# except in compliance with the License. You may obtain a copy of +# the License at http://www.apache.org/licenses/LICENSE-2.0 . +# + +$(eval $(call gb_Module_Module,svtools)) + +$(eval $(call gb_Module_add_targets,svtools,\ + Library_svt \ + UIConfig_svt \ +)) + +$(eval $(call gb_Module_add_l10n_targets,svtools,\ + AllLangMoTarget_svt \ +)) + +$(eval $(call gb_Module_add_check_targets,svtools,\ + CppunitTest_svtools_graphic \ + CppunitTest_svtools_html \ +)) + +ifeq ($(CROSS_COMPILING)$(DISABLE_DYNLOADING),) + +ifneq ($(OS),WNT) +$(eval $(call gb_Module_add_targets,svtools,\ + Executable_langsupport \ +)) +endif + +endif + +$(eval $(call gb_Module_add_subsequentcheck_targets,svtools,\ + JunitTest_svtools_unoapi \ +)) + +# screenshots +$(eval $(call gb_Module_add_screenshot_targets,svtools,\ + CppunitTest_svtools_dialogs_test \ +)) + +#todo: javapatches +#todo: jpeg on mac in svtools/util/makefile.mk +#todo: deliver errtxt.src as ehdl.srs +#todo: nooptfiles filter, filterconfigitem, FilterConfigCache, SvFilterOptionsDialog +#todo: map file + +# vim: set noet sw=4 ts=4: diff --git a/svtools/README b/svtools/README new file mode 100644 index 000000000..dc35c3f38 --- /dev/null +++ b/svtools/README @@ -0,0 +1 @@ +Tools on top of VCL. Common dialogs, file and print dialogs, wizards, vcl filters, lots of helper code. diff --git a/svtools/UIConfig_svt.mk b/svtools/UIConfig_svt.mk new file mode 100644 index 000000000..e6c205b37 --- /dev/null +++ b/svtools/UIConfig_svt.mk @@ -0,0 +1,30 @@ +# -*- Mode: makefile-gmake; tab-width: 4; indent-tabs-mode: t -*- +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# + +$(eval $(call gb_UIConfig_UIConfig,svt)) + +$(eval $(call gb_UIConfig_add_uifiles,svt,\ + svtools/uiconfig/ui/addresstemplatedialog \ + svtools/uiconfig/ui/combocontrol \ + svtools/uiconfig/ui/datewindow \ + svtools/uiconfig/ui/editcontrol \ + svtools/uiconfig/ui/emptypage \ + svtools/uiconfig/ui/fileviewmenu \ + svtools/uiconfig/ui/graphicexport \ + svtools/uiconfig/ui/inputbox \ + svtools/uiconfig/ui/javadisableddialog \ + svtools/uiconfig/ui/listcontrol \ + svtools/uiconfig/ui/linewindow \ + svtools/uiconfig/ui/placeedit \ + svtools/uiconfig/ui/printersetupdialog \ + svtools/uiconfig/ui/querydeletedialog \ + svtools/uiconfig/ui/restartdialog \ +)) + +# vim: set noet sw=4 ts=4: diff --git a/svtools/inc/FltCallDialogParameter.hxx b/svtools/inc/FltCallDialogParameter.hxx new file mode 100644 index 000000000..0a45e65d7 --- /dev/null +++ b/svtools/inc/FltCallDialogParameter.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 <com/sun/star/uno/Sequence.hxx> +#include <com/sun/star/beans/PropertyValue.hpp> +#include <tools/fldunit.hxx> + +class FilterConfigItem; +class SvStream; +class Graphic; +namespace weld +{ +class Window; +} + +struct FltCallDialogParameter +{ + weld::Window* pWindow; + FieldUnit eFieldUnit; + OUString aFilterExt; + + // In and Out PropertySequence for all filter dialogs + css::uno::Sequence<css::beans::PropertyValue> aFilterData; + + FltCallDialogParameter(weld::Window* pW, FieldUnit eFiUni) + : pWindow(pW) + , eFieldUnit(eFiUni){}; +}; diff --git a/svtools/inc/bitmaps.hlst b/svtools/inc/bitmaps.hlst new file mode 100644 index 000000000..875564800 --- /dev/null +++ b/svtools/inc/bitmaps.hlst @@ -0,0 +1,137 @@ +/* -*- 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 + +#define BMP_IMPRESS_SC "res/sx03123.png" +#define BMP_BITMAP_SC "res/sx03125.png" +#define BMP_CALC_SC "res/sx03126.png" +#define BMP_CALCTEMPLATE_SC "res/sx03127.png" +#define BMP_DATABASE_SC "res/sx03129.png" +#define BMP_IMPRESSTEMPLATE_SC "res/sx03130.png" +#define BMP_GIF_SC "res/sx03137.png" +#define BMP_HTML_SC "res/sx03139.png" +#define BMP_JPG_SC "res/sx03140.png" +#define BMP_MATH_SC "res/sx03144.png" +#define BMP_MATHTEMPLATE_SC "res/sx03145.png" +#define BMP_FILE_SC "res/sx03150.png" +#define BMP_PCD_SC "res/sx03152.png" +#define BMP_PCT_SC "res/sx03153.png" +#define BMP_PCX_SC "res/sx03154.png" +#define BMP_SIM_SC "res/sx03155.png" +#define BMP_TEXTFILE_SC "res/sx03156.png" +#define BMP_TIFF_SC "res/sx03158.png" +#define BMP_WMF_SC "res/sx03160.png" +#define BMP_WRITER_SC "res/sx03162.png" +#define BMP_WRITERTEMPLATE_SC "res/sx03163.png" +#define BMP_FIXEDDEV_SC "res/sx03164.png" +#define BMP_REMOVABLEDEV_SC "res/sx03165.png" +#define BMP_CDROMDEV_SC "res/sx03166.png" +#define BMP_NETWORKDEV_SC "res/sx03167.png" +#define BMP_TABLE_SC "res/sx03188.png" +#define BMP_DXF_SC "res/sx03217.png" +#define BMP_MET_SC "res/sx03218.png" +#define BMP_PNG_SC "res/sx03219.png" +#define BMP_SVM_SC "res/sx03222.png" +#define BMP_GLOBAL_DOC_SC "res/sx03226.png" +#define BMP_DRAW_SC "res/sx03227.png" +#define BMP_DRAWTEMPLATE_SC "res/sx03228.png" +#define BMP_OO_DATABASE_DOC_SC "res/sx03245.png" +#define BMP_OO_DRAW_DOC_SC "res/sx03246.png" +#define BMP_OO_MATH_DOC_SC "res/sx03247.png" +#define BMP_OO_GLOBAL_DOC_SC "res/sx03248.png" +#define BMP_OO_IMPRESS_DOC_SC "res/sx03249.png" +#define BMP_OO_CALC_DOC_SC "res/sx03250.png" +#define BMP_OO_WRITER_DOC_SC "res/sx03251.png" +#define BMP_OO_DRAW_TEMPLATE_SC "res/sx03252.png" +#define BMP_OO_IMPRESS_TEMPLATE_SC "res/sx03253.png" +#define BMP_OO_CALC_TEMPLATE_SC "res/sx03254.png" +#define BMP_OO_WRITER_TEMPLATE_SC "res/sx03255.png" +#define BMP_EXTENSION_SC "res/sx03256.png" +#define BMP_IMPRESS_LC "res/lx03123.png" +#define BMP_BITMAP_LC "res/lx03125.png" +#define BMP_CALC_LC "res/lx03126.png" +#define BMP_CALCTEMPLATE_LC "res/lx03127.png" +#define BMP_DATABASE_LC "res/lx03129.png" +#define BMP_IMPRESSTEMPLATE_LC "res/lx03130.png" +#define BMP_GIF_LC "res/lx03137.png" +#define BMP_HTML_LC "res/lx03139.png" +#define BMP_JPG_LC "res/lx03140.png" +#define BMP_MATH_LC "res/lx03144.png" +#define BMP_MATHTEMPLATE_LC "res/lx03145.png" +#define BMP_FILE_LC "res/lx03150.png" +#define BMP_PCD_LC "res/lx03152.png" +#define BMP_PCT_LC "res/lx03153.png" +#define BMP_PCX_LC "res/lx03154.png" +#define BMP_SIM_LC "res/lx03155.png" +#define BMP_TEXTFILE_LC "res/lx03156.png" +#define BMP_TIFF_LC "res/lx03158.png" +#define BMP_WMF_LC "res/lx03160.png" +#define BMP_WRITER_LC "res/lx03162.png" +#define BMP_WRITERTEMPLATE_LC "res/lx03163.png" +#define BMP_FIXEDDEV_LC "res/lx03164.png" +#define BMP_REMOVABLEDEV_LC "res/lx03165.png" +#define BMP_CDROMDEV_LC "res/lx03166.png" +#define BMP_NETWORKDEV_LC "res/lx03167.png" +#define BMP_TABLE_LC "res/lx03188.png" +#define BMP_FOLDER_LC "res/lx03189.png" +#define BMP_DXF_LC "res/lx03217.png" +#define BMP_MET_LC "res/lx03218.png" +#define BMP_PNG_LC "res/lx03219.png" +#define BMP_SVM_LC "res/lx03222.png" +#define BMP_GLOBAL_DOC_LC "res/lx03226.png" +#define BMP_DRAW_LC "res/lx03227.png" +#define BMP_DRAWTEMPLATE_LC "res/lx03228.png" +#define BMP_OO_DATABASE_DOC_LC "res/lx03245.png" +#define BMP_OO_DRAW_DOC_LC "res/lx03246.png" +#define BMP_OO_MATH_DOC_LC "res/lx03247.png" +#define BMP_OO_GLOBAL_DOC_LC "res/lx03248.png" +#define BMP_OO_IMPRESS_DOC_LC "res/lx03249.png" +#define BMP_OO_CALC_DOC_LC "res/lx03250.png" +#define BMP_OO_WRITER_DOC_LC "res/lx03251.png" +#define BMP_OO_DRAW_TEMPLATE_LC "res/lx03252.png" +#define BMP_OO_IMPRESS_TEMPLATE_LC "res/lx03253.png" +#define BMP_OO_CALC_TEMPLATE_LC "res/lx03254.png" +#define BMP_OO_WRITER_TEMPLATE_LC "res/lx03255.png" +#define BMP_EXTENSION_LC "res/lx03256.png" +#define BMP_HTML_32 "res/lx03139_32.png" +#define BMP_OO_DATABASE_DOC_32 "res/lx03245_32.png" +#define BMP_OO_DRAW_DOC_32 "res/lx03246_32.png" +#define BMP_OO_MATH_DOC_32 "res/lx03247_32.png" +#define BMP_OO_GLOBAL_DOC_32 "res/lx03248_32.png" +#define BMP_OO_IMPRESS_DOC_32 "res/lx03249_32.png" +#define BMP_OO_CALC_DOC_32 "res/lx03250_32.png" +#define BMP_OO_WRITER_DOC_32 "res/lx03251_32.png" +#define BMP_OO_WRITER_TEMPLATE_32 "res/lx03255_32.png" +#define BMP_PLUGIN "res/plugin.png" +#define RID_BMP_FOLDER "svtools/res/folder.png" +#define BMP_CURRENT "svtools/res/ed01.png" +#define BMP_MODIFIED "svtools/res/ed02.png" +#define BMP_NEW "svtools/res/ed03.png" +#define BMP_DELETED "svtools/res/ed04.png" +#define BMP_CURRENTNEW "svtools/res/ed05.png" +#define BMP_PRIMARYKEY "svtools/res/ed06.png" +#define BMP_CURRENT_PRIMARYKEY "svtools/res/ed07.png" +#define BMP_FILTER "svtools/res/ed08.png" +#define BMP_HEADERFOOTER "svtools/res/ed09.png" + +#define BMP_TAB_LOCK "cmd/sc_lock.png" + +// Workaround for tdf#135369, not directly used from the code: + +#define BMP_OO_DATABASE_DOC_24 "res/odb_24_8.png" +#define BMP_OO_DRAW_DOC_24 "res/odg_24_8.png" +#define BMP_OO_MATH_DOC_24 "res/odf_24_8.png" +#define BMP_OO_GLOBAL_DOC_24 "res/odm_24_8.png" +#define BMP_OO_IMPRESS_DOC_24 "res/odp_24_8.png" +#define BMP_OO_CALC_DOC_24 "res/ods_24_8.png" +#define BMP_OO_WRITER_DOC_24 "res/odt_24_8.png" +#define BMP_OO_WRITER_TEMPLATE_24 "res/ott_24_8.png" + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/svtools/inc/borderline.hrc b/svtools/inc/borderline.hrc new file mode 100644 index 000000000..05bb3c78f --- /dev/null +++ b/svtools/inc/borderline.hrc @@ -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/. + */ +#pragma once + +#include <editeng/borderline.hxx> + +#define NC_(Context, String) reinterpret_cast<char const *>(Context "\004" u8##String) + +const std::pair<const char*, SvxBorderLineStyle> RID_SVXSTR_BORDERLINE[] = +{ + { NC_("RID_SVXSTR_BORDERLINE", "None"), SvxBorderLineStyle::NONE }, + { NC_("RID_SVXSTR_BORDERLINE", "Solid"), SvxBorderLineStyle::SOLID }, + { NC_("RID_SVXSTR_BORDERLINE", "Dotted"), SvxBorderLineStyle::DOTTED }, + { NC_("RID_SVXSTR_BORDERLINE", "Dashed"), SvxBorderLineStyle::DASHED }, + { NC_("RID_SVXSTR_BORDERLINE", "Double"), SvxBorderLineStyle::DOUBLE }, + { NC_("RID_SVXSTR_BORDERLINE", "Thin Thick, Small Gap"), SvxBorderLineStyle::THINTHICK_SMALLGAP }, + { NC_("RID_SVXSTR_BORDERLINE", "Thin Thick, Medium Gap"), SvxBorderLineStyle::THINTHICK_MEDIUMGAP }, + { NC_("RID_SVXSTR_BORDERLINE", "Thin Thick, Large Gap"), SvxBorderLineStyle::THINTHICK_LARGEGAP }, + { NC_("RID_SVXSTR_BORDERLINE", "Thick Thin, Small Gap"), SvxBorderLineStyle::THICKTHIN_SMALLGAP }, + { NC_("RID_SVXSTR_BORDERLINE", "Thick Thin, Medium Gap"), SvxBorderLineStyle::THICKTHIN_MEDIUMGAP }, + { NC_("RID_SVXSTR_BORDERLINE", "Thick Thin, Large Gap"), SvxBorderLineStyle::THICKTHIN_LARGEGAP }, + { NC_("RID_SVXSTR_BORDERLINE", "Embossed"), SvxBorderLineStyle::EMBOSSED }, + { NC_("RID_SVXSTR_BORDERLINE", "Engraved"), SvxBorderLineStyle::ENGRAVED }, + { NC_("RID_SVXSTR_BORDERLINE", "Outset"), SvxBorderLineStyle::OUTSET }, + { NC_("RID_SVXSTR_BORDERLINE", "Inset"), SvxBorderLineStyle::INSET }, + { NC_("RID_SVXSTR_BORDERLINE", "Fine Dashed"), SvxBorderLineStyle::FINE_DASHED }, + { NC_("RID_SVXSTR_BORDERLINE", "Double Thin"), SvxBorderLineStyle::DOUBLE_THIN }, + { NC_("RID_SVXSTR_BORDERLINE", "Dash Dot"), SvxBorderLineStyle::DASH_DOT }, + { NC_("RID_SVXSTR_BORDERLINE", "Dash Dot Dot"), SvxBorderLineStyle::DASH_DOT_DOT } +}; + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/inc/errtxt.hrc b/svtools/inc/errtxt.hrc new file mode 100644 index 000000000..9847148d4 --- /dev/null +++ b/svtools/inc/errtxt.hrc @@ -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 . + */ + +#pragma once + +#include <svtools/sfxecode.hxx> +#include <svtools/soerr.hxx> + +#define NC_(Context, String) reinterpret_cast<char const *>(Context "\004" u8##String) + +const ErrMsgCode RID_ERRCTX[] = +{ + { NC_("RID_ERRCTX", "Error") , ErrCode(ERRCTX_ERROR) }, + { NC_("RID_ERRCTX", "Warning") , ErrCode(ERRCTX_WARNING) }, + { NC_("RID_ERRCTX", "$(ERR) loading the template $(ARG1)") , ErrCode(ERRCTX_SFX_LOADTEMPLATE) }, + { NC_("RID_ERRCTX", "$(ERR) saving the document $(ARG1)"), ErrCode(ERRCTX_SFX_SAVEDOC) }, + { NC_("RID_ERRCTX", "$(ERR) saving the document $(ARG1)"), ErrCode(ERRCTX_SFX_SAVEASDOC) }, + { NC_("RID_ERRCTX", "$(ERR) displaying doc. information for document $(ARG1)") , ErrCode(ERRCTX_SFX_DOCINFO) }, + { NC_("RID_ERRCTX", "$(ERR) writing document $(ARG1) as template") , ErrCode(ERRCTX_SFX_DOCTEMPLATE) }, + { NC_("RID_ERRCTX", "$(ERR) copying or moving document contents") , ErrCode(ERRCTX_SFX_MOVEORCOPYCONTENTS) }, + { NC_("RID_ERRCTX", "$(ERR) starting the Document Manager") , ErrCode(ERRCTX_SFX_DOCMANAGER) }, + { NC_("RID_ERRCTX", "$(ERR) loading document $(ARG1)") , ErrCode(ERRCTX_SFX_OPENDOC) }, + { NC_("RID_ERRCTX", "$(ERR) creating a new document") , ErrCode(ERRCTX_SFX_NEWDOCDIRECT) }, + { NC_("RID_ERRCTX", "$(ERR) creating a new document") , ErrCode(ERRCTX_SFX_NEWDOC) }, + { NC_("RID_ERRCTX", "$(ERR) expanding entry") , ErrCode(ERRCTX_SFX_CREATEOBJSH) }, + { NC_("RID_ERRCTX", "$(ERR) loading BASIC of document $(ARG1)") , ErrCode(ERRCTX_SFX_LOADBASIC) }, + { NC_("RID_ERRCTX", "$(ERR) searching for an address"), ErrCode(ERRCTX_SFX_SEARCHADDRESS) }, + { nullptr, ERRCODE_NONE } +}; + +const std::pair<const char*, ErrCodeClass> RID_ERRHDL_CLASS[] = +{ + { NC_("RID_ERRHDL", "Abort") , ErrCodeClass::Abort }, + { NC_("RID_ERRHDL", "Nonexistent object") , ErrCodeClass::NotExists }, + { NC_("RID_ERRHDL", "Object already exists") , ErrCodeClass::AlreadyExists }, + { NC_("RID_ERRHDL", "Object not accessible") , ErrCodeClass::Access }, + { NC_("RID_ERRHDL", "Inadmissible path") , ErrCodeClass::Path }, + { NC_("RID_ERRHDL", "Locking problem") , ErrCodeClass::Locking }, + { NC_("RID_ERRHDL", "Wrong parameter") , ErrCodeClass::Parameter }, + { NC_("RID_ERRHDL", "Resource exhausted") , ErrCodeClass::Space }, + { NC_("RID_ERRHDL", "Action not supported") , ErrCodeClass::NotSupported }, + { NC_("RID_ERRHDL", "Read Error") , ErrCodeClass::Read }, + { NC_("RID_ERRHDL", "Write Error") , ErrCodeClass::Write }, + { NC_("RID_ERRHDL", "unknown") , ErrCodeClass::Unknown }, + { NC_("RID_ERRHDL", "Version Incompatibility") , ErrCodeClass::Version }, + { NC_("RID_ERRHDL", "General Error") , ErrCodeClass::General }, + { NC_("RID_ERRHDL", "Incorrect format") , ErrCodeClass::Format }, + { NC_("RID_ERRHDL", "Error creating object") , ErrCodeClass::Create }, + { NC_("RID_ERRHDL", "Inadmissible value or data type") , ErrCodeClass::Sbx }, + { NC_("RID_ERRHDL", "BASIC runtime error") , ErrCodeClass::Runtime }, + { NC_("RID_ERRHDL", "BASIC syntax error") , ErrCodeClass::Compiler }, + { nullptr, ErrCodeClass::NONE } +}; + +const ErrMsgCode RID_ERRHDL[] = +{ + { NC_("RID_ERRHDL", "General Error") , ErrCode(1) }, + { NC_("RID_ERRHDL", "General input/output error.") , ERRCODE_IO_GENERAL }, + { NC_("RID_ERRHDL", "Invalid file name.") , ERRCODE_IO_MISPLACEDCHAR }, + { NC_("RID_ERRHDL", "Nonexistent file.") , ERRCODE_IO_NOTEXISTS }, + { NC_("RID_ERRHDL", "File already exists.") , ERRCODE_IO_ALREADYEXISTS }, + { NC_("RID_ERRHDL", "The object is not a directory.") , ERRCODE_IO_NOTADIRECTORY }, + { NC_("RID_ERRHDL", "The object is not a file.") , ERRCODE_IO_NOTAFILE }, + { NC_("RID_ERRHDL", "The specified device is invalid.") , ERRCODE_IO_INVALIDDEVICE }, + { NC_("RID_ERRHDL", "The object cannot be accessed\ndue to insufficient user rights.") , ERRCODE_IO_ACCESSDENIED }, + { NC_("RID_ERRHDL", "Sharing violation while accessing the object.") , ERRCODE_IO_LOCKVIOLATION }, + { NC_("RID_ERRHDL", "No more space on device.") , ERRCODE_IO_OUTOFSPACE }, + { NC_("RID_ERRHDL", "This operation cannot be run on\nfiles containing wildcards.") , ERRCODE_IO_ISWILDCARD }, + { NC_("RID_ERRHDL", "This operation is not supported on this operating system.") , ERRCODE_IO_NOTSUPPORTED }, + { NC_("RID_ERRHDL", "There are too many files open.") , ERRCODE_IO_TOOMANYOPENFILES }, + { NC_("RID_ERRHDL", "Data could not be read from the file.") , ERRCODE_IO_CANTREAD }, + { NC_("RID_ERRHDL", "The file could not be written.") , ERRCODE_IO_CANTWRITE }, + { NC_("RID_ERRHDL", "The operation could not be run due to insufficient memory.") , ERRCODE_IO_OUTOFMEMORY }, + { NC_("RID_ERRHDL", "The seek operation could not be run.") , ERRCODE_IO_CANTSEEK }, + { NC_("RID_ERRHDL", "The tell operation could not be run.") , ERRCODE_IO_CANTTELL }, + { NC_("RID_ERRHDL", "Incorrect file version.") , ERRCODE_IO_WRONGVERSION }, + { NC_("RID_ERRHDL", "Incorrect file format.") , ERRCODE_IO_WRONGFORMAT }, + { NC_("RID_ERRHDL", "The file name contains invalid characters.") , ERRCODE_IO_INVALIDCHAR }, + { NC_("RID_ERRHDL", "An unknown I/O error has occurred.") , ERRCODE_IO_UNKNOWN }, + { NC_("RID_ERRHDL", "An invalid attempt was made to access the file.") , ERRCODE_IO_INVALIDACCESS }, + { NC_("RID_ERRHDL", "The file could not be created.") , ERRCODE_IO_CANTCREATE }, + { NC_("RID_ERRHDL", "The operation was started under an invalid parameter.") , ERRCODE_IO_INVALIDPARAMETER }, + { NC_("RID_ERRHDL", "The operation on the file was aborted.") , ERRCODE_IO_ABORT }, + { NC_("RID_ERRHDL", "Path to the file does not exist.") , ERRCODE_IO_NOTEXISTSPATH }, + { NC_("RID_ERRHDL", "An object cannot be copied into itself.") , ERRCODE_IO_RECURSIVE }, + { NC_("RID_ERRHDL", "The specified template could not be found.") , ERRCODE_SFX_TEMPLATENOTFOUND }, + { NC_("RID_ERRHDL", "The file cannot be used as template.") , ERRCODE_SFX_NOTATEMPLATE }, + { NC_("RID_ERRHDL", "This document has already been opened for editing.") , ERRCODE_SFX_ALREADYOPEN }, + { NC_("RID_ERRHDL", "The wrong password has been entered.") , ERRCODE_SFX_WRONGPASSWORD }, + { NC_("RID_ERRHDL", "Error reading file.") , ERRCODE_SFX_DOLOADFAILED }, + { NC_("RID_ERRHDL", "The document was opened as read-only.") , ERRCODE_SFX_DOCUMENTREADONLY }, + { NC_("RID_ERRHDL", "General OLE Error.") , ERRCODE_SFX_OLEGENERAL }, + { NC_("RID_ERRHDL", "The host name $(ARG1) could not be resolved.") , ERRCODE_INET_NAME_RESOLVE }, + { NC_("RID_ERRHDL", "Could not establish Internet connection to $(ARG1).") , ERRCODE_INET_CONNECT }, + { NC_("RID_ERRHDL", "Error reading data from the Internet.\nServer error message: $(ARG1).") , ERRCODE_INET_READ }, + { NC_("RID_ERRHDL", "Error transferring data to the Internet.\nServer error message: $(ARG1).") , ERRCODE_INET_WRITE }, + { NC_("RID_ERRHDL", "General Internet error has occurred.") , ERRCODE_INET_GENERAL }, + { NC_("RID_ERRHDL", "The requested Internet data is not available in the cache and cannot be transmitted as the Online mode has not be activated.") , ERRCODE_INET_OFFLINE }, + { NC_("RID_ERRHDL", "The contents could not be created.") , ERRCODE_SFX_CANTCREATECONTENT }, + { NC_("RID_ERRHDL", "The file name is too long for the target file system.") , ERRCODE_IO_NAMETOOLONG }, + { NC_("RID_ERRHDL", "The input syntax is invalid.") , ERRCODE_SFX_INVALIDSYNTAX }, + { NC_("RID_ERRHDL", "This document contains attributes that cannot be saved in the selected format.\nPlease save the document in a %PRODUCTNAME %PRODUCTVERSION file format."), ERRCODE_IO_NOTSTORABLEINBINARYFORMAT }, + { NC_("RID_ERRHDL", "The maximum number of documents that can be opened at the same time has been reached. You need to close one or more documents before you can open a new document."), ERRCODE_SFX_NOMOREDOCUMENTSALLOWED }, + { NC_("RID_ERRHDL", "Could not create backup copy.") , ERRCODE_SFX_CANTCREATEBACKUP }, + { NC_("RID_ERRHDL", "An attempt was made to execute a macro.\nFor security reasons, macro support is disabled."), ERRCODE_SFX_MACROS_SUPPORT_DISABLED }, + { NC_("RID_ERRHDL", "This document contains macros.\n\nMacros may contain viruses. Execution of macros is disabled due to the current macro security setting in %PRODUCTNAME - Preferences - %PRODUCTNAME - Security.\n\nTherefore, some functionality may not be available.") , ERRCODE_SFX_DOCUMENT_MACRO_DISABLED_MAC }, + { NC_("RID_ERRHDL", "This document contains macros.\n\nMacros may contain viruses. Execution of macros is disabled due to the current macro security setting in Tools - Options - %PRODUCTNAME - Security.\n\nTherefore, some functionality may not be available.") , ERRCODE_SFX_DOCUMENT_MACRO_DISABLED }, + { NC_("RID_ERRHDL", "The encrypted document contains unexpected non-encrypted streams.\n\nThis could be the result of document manipulation.\n\nWe recommend that you do not trust the content of the current document.\nExecution of macros is disabled for this document.\n ") , ERRCODE_SFX_INCOMPLETE_ENCRYPTION }, + { NC_("RID_ERRHDL", "Invalid data length.") , ERRCODE_IO_INVALIDLENGTH }, + { NC_("RID_ERRHDL", "Function not possible: path contains current directory.") , ERRCODE_IO_CURRENTDIR }, + { NC_("RID_ERRHDL", "Function not possible: device (drive) not identical.") , ERRCODE_IO_NOTSAMEDEVICE }, + { NC_("RID_ERRHDL", "Device (drive) not ready.") , ERRCODE_IO_DEVICENOTREADY }, + { NC_("RID_ERRHDL", "Wrong checksum.") , ERRCODE_IO_BADCRC }, + { NC_("RID_ERRHDL", "Function not possible: write protected.") , ERRCODE_IO_WRITEPROTECTED }, + { NC_("RID_ERRHDL", "The password of a shared spreadsheet cannot be set or changed.\nDeactivate sharing mode first."), ERRCODE_SFX_SHARED_NOPASSWORDCHANGE }, + { NC_("RID_ERRHDL", "File format error found at $(ARG1)(row,col)."), ERRCODE_SFX_FORMAT_ROWCOL }, + { NC_("RID_ERRHDL", "The filter for this file format is disabled in configuration. Please contact your systems administrator."), ERRCODE_IO_FILTERDISABLED }, + { nullptr, ERRCODE_NONE } +}; + +const ErrMsgCode RID_SO_ERROR_HANDLER[] = +{ + { NC_("RID_ERRHDL", "General OLE error."), + ERRCODE_SO_GENERALERROR }, + { NC_("RID_ERRHDL", "The action cannot be executed in the object's current state."), + ERRCODE_SO_CANNOT_DOVERB_NOW }, + { NC_("RID_ERRHDL", "The object does not support any actions."), + ERRCODE_SO_NOVERBS }, + { NC_("RID_ERRHDL", "Object does not support this action."), + ERRCODE_SO_NOTIMPL }, + { nullptr, ERRCODE_NONE } +}; + +const ErrMsgCode RID_SO_ERRCTX[] = +{ + { NC_("RID_ERRHDL", "$(ERR) activating object") , ErrCode(ERRCTX_SO_DOVERB) }, + { nullptr, ERRCODE_NONE } +}; + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/inc/langtab.hrc b/svtools/inc/langtab.hrc new file mode 100644 index 000000000..5242b7ec1 --- /dev/null +++ b/svtools/inc/langtab.hrc @@ -0,0 +1,432 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <i18nlangtag/lang.h> + +#define NC_(Context, String) reinterpret_cast<char const *>(Context "\004" u8##String) + +const std::pair<const char*, LanguageType> STR_ARR_SVT_LANGUAGE_TABLE[] = +{ + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "[None]") , LANGUAGE_NONE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Unknown") , LANGUAGE_DONTKNOW }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Default") , LANGUAGE_SYSTEM }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Default") , LANGUAGE_USER_SYSTEM_CONFIG }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Afrikaans (South Africa)") , LANGUAGE_AFRIKAANS }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Albanian") , LANGUAGE_ALBANIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Arabic") , LANGUAGE_ARABIC_PRIMARY_ONLY }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Arabic (Algeria)") , LANGUAGE_ARABIC_ALGERIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Arabic (Bahrain)") , LANGUAGE_ARABIC_BAHRAIN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Arabic (Chad)") , LANGUAGE_USER_ARABIC_CHAD }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Arabic (Comoros)") , LANGUAGE_USER_ARABIC_COMOROS }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Arabic (Djibouti)") , LANGUAGE_USER_ARABIC_DJIBOUTI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Arabic (Egypt)") , LANGUAGE_ARABIC_EGYPT }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Arabic (Eritrea)") , LANGUAGE_USER_ARABIC_ERITREA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Arabic (Iraq)") , LANGUAGE_ARABIC_IRAQ }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Arabic (Israel)") , LANGUAGE_USER_ARABIC_ISRAEL }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Arabic (Jordan)") , LANGUAGE_ARABIC_JORDAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Arabic (Kuwait)") , LANGUAGE_ARABIC_KUWAIT }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Arabic (Lebanon)") , LANGUAGE_ARABIC_LEBANON }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Arabic (Libya)") , LANGUAGE_ARABIC_LIBYA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Arabic (Mauritania)") , LANGUAGE_USER_ARABIC_MAURITANIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Arabic (Morocco)") , LANGUAGE_ARABIC_MOROCCO }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Arabic (Oman)") , LANGUAGE_ARABIC_OMAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Arabic (Palestine)") , LANGUAGE_USER_ARABIC_PALESTINE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Arabic (Qatar)") , LANGUAGE_ARABIC_QATAR }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Arabic (Saudi Arabia)") , LANGUAGE_ARABIC_SAUDI_ARABIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Arabic (Somalia)") , LANGUAGE_USER_ARABIC_SOMALIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Arabic (Sudan)") , LANGUAGE_USER_ARABIC_SUDAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Arabic (Syria)") , LANGUAGE_ARABIC_SYRIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Arabic (Tunisia)") , LANGUAGE_ARABIC_TUNISIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Arabic (UAE)") , LANGUAGE_ARABIC_UAE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Arabic (Yemen)") , LANGUAGE_ARABIC_YEMEN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Aragonese") , LANGUAGE_USER_ARAGONESE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Armenian, Eastern (Armenia)") , LANGUAGE_ARMENIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Assamese") , LANGUAGE_ASSAMESE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Azerbaijani Latin") , LANGUAGE_AZERI_LATIN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Azerbaijani Cyrillic") , LANGUAGE_AZERI_CYRILLIC }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Basque") , LANGUAGE_BASQUE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Bengali (India)") , LANGUAGE_BENGALI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Bulgarian") , LANGUAGE_BULGARIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Belarusian") , LANGUAGE_BELARUSIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Catalan") , LANGUAGE_CATALAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Catalan (Valencian)") , LANGUAGE_USER_CATALAN_VALENCIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Chinese (traditional)") , LANGUAGE_CHINESE_TRADITIONAL }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Chinese (simplified)") , LANGUAGE_CHINESE_SIMPLIFIED }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Chinese (Hong Kong)") , LANGUAGE_CHINESE_HONGKONG }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Chinese (Singapore)") , LANGUAGE_CHINESE_SINGAPORE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Chinese (Macau)") , LANGUAGE_CHINESE_MACAU }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Church Slavic") , LANGUAGE_USER_CHURCH_SLAVIC }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Croatian") , LANGUAGE_CROATIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Czech") , LANGUAGE_CZECH }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Danish") , LANGUAGE_DANISH }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Dutch (Netherlands)") , LANGUAGE_DUTCH }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Dutch (Belgium)") , LANGUAGE_DUTCH_BELGIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "English (USA)") , LANGUAGE_ENGLISH_US }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "English (UK)") , LANGUAGE_ENGLISH_UK }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "English, OED spelling (UK)") , LANGUAGE_USER_ENGLISH_UK_OXENDICT }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "English (Australia)") , LANGUAGE_ENGLISH_AUS }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "English (Canada)") , LANGUAGE_ENGLISH_CAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "English (New Zealand)") , LANGUAGE_ENGLISH_NZ }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "English (Ireland)") , LANGUAGE_ENGLISH_EIRE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "English (South Africa)") , LANGUAGE_ENGLISH_SAFRICA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "English (Jamaica)") , LANGUAGE_ENGLISH_JAMAICA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "English (Caribbean)") , LANGUAGE_ENGLISH_CARIBBEAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "English (Belize)") , LANGUAGE_ENGLISH_BELIZE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "English (Trinidad)") , LANGUAGE_ENGLISH_TRINIDAD }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "English (Zimbabwe)") , LANGUAGE_ENGLISH_ZIMBABWE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "English (Philippines)") , LANGUAGE_ENGLISH_PHILIPPINES }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "English (India)") , LANGUAGE_ENGLISH_INDIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Estonian") , LANGUAGE_ESTONIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Finnish") , LANGUAGE_FINNISH }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Faroese") , LANGUAGE_FAEROESE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Persian") , LANGUAGE_FARSI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "French (France)") , LANGUAGE_FRENCH }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "French (Belgium)") , LANGUAGE_FRENCH_BELGIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "French (Canada)") , LANGUAGE_FRENCH_CANADIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "French (Switzerland)") , LANGUAGE_FRENCH_SWISS }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "French (Luxembourg)") , LANGUAGE_FRENCH_LUXEMBOURG }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "French (Monaco)") , LANGUAGE_FRENCH_MONACO }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Gascon") , LANGUAGE_USER_GASCON }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "German (Germany)") , LANGUAGE_GERMAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "German (Switzerland)") , LANGUAGE_GERMAN_SWISS }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "German (Austria)") , LANGUAGE_GERMAN_AUSTRIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "German (Luxembourg)") , LANGUAGE_GERMAN_LUXEMBOURG }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "German (Liechtenstein)") , LANGUAGE_GERMAN_LIECHTENSTEIN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Greek") , LANGUAGE_GREEK }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Gujarati") , LANGUAGE_GUJARATI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Hebrew") , LANGUAGE_HEBREW }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Hindi") , LANGUAGE_HINDI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Hungarian") , LANGUAGE_HUNGARIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Icelandic") , LANGUAGE_ICELANDIC }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Indonesian") , LANGUAGE_INDONESIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Italian (Italy)") , LANGUAGE_ITALIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Italian (Switzerland)") , LANGUAGE_ITALIAN_SWISS }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Japanese") , LANGUAGE_JAPANESE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Kannada") , LANGUAGE_KANNADA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Kashmiri (Kashmir)") , LANGUAGE_KASHMIRI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Kashmiri (India)") , LANGUAGE_KASHMIRI_INDIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Kazakh") , LANGUAGE_KAZAKH }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Konkani") , LANGUAGE_KONKANI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Korean (RoK)") , LANGUAGE_KOREAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Latvian") , LANGUAGE_LATVIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Lithuanian") , LANGUAGE_LITHUANIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Macedonian") , LANGUAGE_MACEDONIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Malay (Malaysia)") , LANGUAGE_MALAY_MALAYSIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Malay (Brunei Darussalam)") , LANGUAGE_MALAY_BRUNEI_DARUSSALAM }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Malayalam") , LANGUAGE_MALAYALAM }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Manipuri") , LANGUAGE_MANIPURI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Marathi") , LANGUAGE_MARATHI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Nepali (Nepal)") , LANGUAGE_NEPALI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Nepali (India)") , LANGUAGE_NEPALI_INDIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Norwegian, Bokmål") , LANGUAGE_NORWEGIAN_BOKMAL }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Norwegian, Nynorsk") , LANGUAGE_NORWEGIAN_NYNORSK }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Odia") , LANGUAGE_ODIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Polish") , LANGUAGE_POLISH }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Portuguese (Angola)") , LANGUAGE_USER_PORTUGUESE_ANGOLA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Portuguese (Portugal)") , LANGUAGE_PORTUGUESE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Portuguese (Brazil)") , LANGUAGE_PORTUGUESE_BRAZILIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Punjabi") , LANGUAGE_PUNJABI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Rhaeto-Romance") , LANGUAGE_RHAETO_ROMAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Romanian (Romania)") , LANGUAGE_ROMANIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Romanian (Moldova)") , LANGUAGE_ROMANIAN_MOLDOVA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Russian") , LANGUAGE_RUSSIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Sanskrit") , LANGUAGE_SANSKRIT }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Serbian Cyrillic (Serbia and Montenegro)") , LANGUAGE_SERBIAN_CYRILLIC_SAM }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Serbian Latin (Serbia and Montenegro)") , LANGUAGE_SERBIAN_LATIN_SAM }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Serbian Cyrillic (Serbia)") , LANGUAGE_USER_SERBIAN_CYRILLIC_SERBIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Serbian Latin (Serbia)") , LANGUAGE_USER_SERBIAN_LATIN_SERBIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Serbian Cyrillic (Montenegro)") , LANGUAGE_USER_SERBIAN_CYRILLIC_MONTENEGRO }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Serbian Latin (Montenegro)") , LANGUAGE_USER_SERBIAN_LATIN_MONTENEGRO }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Serbian Latin") , LANGUAGE_SERBIAN_LATIN_LSO }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Sidama") , LANGUAGE_USER_SIDAMA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Sindhi, Devanagari") , LANGUAGE_SINDHI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Sindhi, Arabic") , LANGUAGE_SINDHI_PAKISTAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Slovak") , LANGUAGE_SLOVAK }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Slovenian") , LANGUAGE_SLOVENIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Spanish (Spain)") , LANGUAGE_SPANISH }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Spanish (Mexico)") , LANGUAGE_SPANISH_MEXICAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Spanish (Guatemala)") , LANGUAGE_SPANISH_GUATEMALA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Spanish (Costa Rica)") , LANGUAGE_SPANISH_COSTARICA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Spanish (Panama)") , LANGUAGE_SPANISH_PANAMA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Spanish (Dom. Rep.)") , LANGUAGE_SPANISH_DOMINICAN_REPUBLIC }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Spanish (Venezuela)") , LANGUAGE_SPANISH_VENEZUELA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Spanish (Colombia)") , LANGUAGE_SPANISH_COLOMBIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Spanish (Peru)") , LANGUAGE_SPANISH_PERU }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Spanish (Argentina)") , LANGUAGE_SPANISH_ARGENTINA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Spanish (Ecuador)") , LANGUAGE_SPANISH_ECUADOR }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Spanish (Chile)") , LANGUAGE_SPANISH_CHILE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Spanish (Uruguay)") , LANGUAGE_SPANISH_URUGUAY }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Spanish (Paraguay)") , LANGUAGE_SPANISH_PARAGUAY }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Spanish (Bolivia)") , LANGUAGE_SPANISH_BOLIVIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Spanish (El Salvador)") , LANGUAGE_SPANISH_EL_SALVADOR }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Spanish (Honduras)") , LANGUAGE_SPANISH_HONDURAS }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Spanish (Nicaragua)") , LANGUAGE_SPANISH_NICARAGUA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Spanish (Puerto Rico)") , LANGUAGE_SPANISH_PUERTO_RICO }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Swahili (Kenya)") , LANGUAGE_SWAHILI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Swedish (Sweden)") , LANGUAGE_SWEDISH }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Swedish (Finland)") , LANGUAGE_SWEDISH_FINLAND }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Tajik") , LANGUAGE_TAJIK }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Tamil") , LANGUAGE_TAMIL }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Tatar") , LANGUAGE_TATAR }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Telugu") , LANGUAGE_TELUGU }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Thai") , LANGUAGE_THAI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Turkish") , LANGUAGE_TURKISH }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Urdu (Pakistan)") , LANGUAGE_URDU_PAKISTAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Urdu (India)") , LANGUAGE_URDU_INDIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Ukrainian") , LANGUAGE_UKRAINIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Uzbek Latin") , LANGUAGE_UZBEK_LATIN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Uzbek Cyrillic") , LANGUAGE_UZBEK_CYRILLIC }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Welsh") , LANGUAGE_WELSH }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Latin") , LANGUAGE_USER_LATIN_VATICAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Esperanto") , LANGUAGE_USER_ESPERANTO }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Kinyarwanda (Rwanda)") , LANGUAGE_USER_KINYARWANDA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Maori") , LANGUAGE_MAORI_NEW_ZEALAND }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Galician") , LANGUAGE_GALICIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Dhivehi") , LANGUAGE_DHIVEHI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Northern Sotho") , LANGUAGE_SEPEDI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Gaelic (Scotland)") , LANGUAGE_GAELIC_SCOTLAND }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Mongolian Cyrillic") , LANGUAGE_MONGOLIAN_CYRILLIC_MONGOLIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Mongolian Mongolian") , LANGUAGE_MONGOLIAN_MONGOLIAN_MONGOLIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Interlingua") , LANGUAGE_USER_INTERLINGUA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Bosnian") , LANGUAGE_BOSNIAN_BOSNIA_HERZEGOVINA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Bengali (Bangladesh)") , LANGUAGE_BENGALI_BANGLADESH }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Occitan") , LANGUAGE_USER_OCCITAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Khmer") , LANGUAGE_KHMER }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Kurdish, Northern (Turkey)") , LANGUAGE_USER_KURDISH_TURKEY }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Kurdish, Northern (Syria)") , LANGUAGE_USER_KURDISH_SYRIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Kurdish, Central (Iraq)") , LANGUAGE_USER_KURDISH_IRAQ }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Kurdish, Central (Iran)") , LANGUAGE_USER_KURDISH_IRAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Kurdish, Southern (Iran)") , LANGUAGE_USER_KURDISH_SOUTHERN_IRAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Kurdish, Southern (Iraq)") , LANGUAGE_USER_KURDISH_SOUTHERN_IRAQ }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Sardinian") , LANGUAGE_USER_SARDINIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Dzongkha") , LANGUAGE_DZONGKHA_BHUTAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Swahili (Tanzania)") , LANGUAGE_USER_SWAHILI_TANZANIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Lao") , LANGUAGE_LAO }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Irish") , LANGUAGE_GAELIC_IRELAND }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Tibetan (PR China)") , LANGUAGE_TIBETAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Georgian") , LANGUAGE_GEORGIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Frisian") , LANGUAGE_FRISIAN_NETHERLANDS }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Tswana (South Africa)") , LANGUAGE_TSWANA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Zulu") , LANGUAGE_ZULU }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Vietnamese") , LANGUAGE_VIETNAMESE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Breton") , LANGUAGE_USER_BRETON }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Kalaallisut") , LANGUAGE_USER_KALAALLISUT }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Ndebele, South") , LANGUAGE_USER_NDEBELE_SOUTH }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Southern Sotho") , LANGUAGE_SESOTHO }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Swazi") , LANGUAGE_USER_SWAZI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Tsonga") , LANGUAGE_TSONGA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Venda") , LANGUAGE_VENDA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Tswana (Botswana)") , LANGUAGE_USER_TSWANA_BOTSWANA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Xhosa") , LANGUAGE_XHOSA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Sinhala") , LANGUAGE_SINHALESE_SRI_LANKA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Moore") , LANGUAGE_USER_MOORE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Bambara") , LANGUAGE_USER_BAMBARA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Akan") , LANGUAGE_USER_AKAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Luxembourgish") , LANGUAGE_USER_LUXEMBOURGISH }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Friulian") , LANGUAGE_USER_FRIULIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Fijian") , LANGUAGE_USER_FIJIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Afrikaans (Namibia)") , LANGUAGE_USER_AFRIKAANS_NAMIBIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "English (Namibia)") , LANGUAGE_USER_ENGLISH_NAMIBIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Walloon") , LANGUAGE_USER_WALLOON }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Coptic") , LANGUAGE_USER_COPTIC }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Tigrigna (Eritrea)") , LANGUAGE_TIGRIGNA_ERITREA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Tigrigna (Ethiopia)") , LANGUAGE_TIGRIGNA_ETHIOPIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Amharic") , LANGUAGE_AMHARIC_ETHIOPIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Kirghiz") , LANGUAGE_KIRGHIZ }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "German (Belgium)") , LANGUAGE_USER_GERMAN_BELGIUM }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Chuvash") , LANGUAGE_USER_CHUVASH }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Burmese") , LANGUAGE_BURMESE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Hausa (Nigeria)") , LANGUAGE_HAUSA_NIGERIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Hausa (Ghana)") , LANGUAGE_USER_HAUSA_GHANA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Éwé") , LANGUAGE_USER_EWE_GHANA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "English (Ghana)") , LANGUAGE_USER_ENGLISH_GHANA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Sango") , LANGUAGE_USER_SANGO }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Tagalog") , LANGUAGE_USER_TAGALOG }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Ganda") , LANGUAGE_USER_GANDA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Lingala") , LANGUAGE_USER_LINGALA_DRCONGO }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Low German") , LANGUAGE_USER_LOW_GERMAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Hiligaynon") , LANGUAGE_USER_HILIGAYNON }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Nyanja") , LANGUAGE_USER_NYANJA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Kashubian") , LANGUAGE_USER_KASHUBIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Spanish (Cuba)") , LANGUAGE_USER_SPANISH_CUBA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Tetun (Indonesia)") , LANGUAGE_USER_TETUN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Quechua (Bolivia, North)") , LANGUAGE_USER_QUECHUA_NORTH_BOLIVIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Quechua (Bolivia, South)") , LANGUAGE_USER_QUECHUA_SOUTH_BOLIVIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Somali") , LANGUAGE_SOMALI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Sami, Inari (Finland)") , LANGUAGE_SAMI_INARI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Sami, Lule (Norway)") , LANGUAGE_SAMI_LULE_NORWAY }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Sami, Lule (Sweden)") , LANGUAGE_SAMI_LULE_SWEDEN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Sami, Northern (Finland)") , LANGUAGE_SAMI_NORTHERN_FINLAND }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Sami, Northern (Norway)") , LANGUAGE_SAMI_NORTHERN_NORWAY }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Sami, Northern (Sweden)") , LANGUAGE_SAMI_NORTHERN_SWEDEN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Sami, Skolt (Finland)") , LANGUAGE_SAMI_SKOLT }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Sami, Southern (Norway)") , LANGUAGE_SAMI_SOUTHERN_NORWAY }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Sami, Southern (Sweden)") , LANGUAGE_SAMI_SOUTHERN_SWEDEN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Sami, Kildin (Russia)") , LANGUAGE_USER_SAMI_KILDIN_RUSSIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Guarani (Paraguay)") , LANGUAGE_GUARANI_PARAGUAY }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Bodo") , LANGUAGE_USER_BODO_INDIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Dogri") , LANGUAGE_USER_DOGRI_INDIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Maithili") , LANGUAGE_USER_MAITHILI_INDIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Santali") , LANGUAGE_USER_SANTALI_INDIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Tetun (Timor-Leste)") , LANGUAGE_USER_TETUN_TIMOR_LESTE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Turkmen") , LANGUAGE_TURKMEN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Maltese") , LANGUAGE_MALTESE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Tok Pisin") , LANGUAGE_USER_TOK_PISIN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Shuswap") , LANGUAGE_USER_SHUSWAP }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Oromo") , LANGUAGE_OROMO }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Greek, Ancient") , LANGUAGE_USER_ANCIENT_GREEK }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Yiddish (Israel)") , LANGUAGE_YIDDISH }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Quechua (Ecuador)") , LANGUAGE_QUECHUA_ECUADOR }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Uyghur") , LANGUAGE_UIGHUR_CHINA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Asturian") , LANGUAGE_USER_ASTURIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Sorbian, Upper") , LANGUAGE_UPPER_SORBIAN_GERMANY }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Sorbian, Lower") , LANGUAGE_LOWER_SORBIAN_GERMANY }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Latgalian") , LANGUAGE_USER_LATGALIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Maore") , LANGUAGE_USER_MAORE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Bushi") , LANGUAGE_USER_BUSHI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Tahitian") , LANGUAGE_USER_TAHITIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Malagasy, Plateau") , LANGUAGE_MALAGASY_PLATEAU }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Papiamentu (Netherlands Antilles)") , LANGUAGE_PAPIAMENTU }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Papiamento (Aruba)") , LANGUAGE_USER_PAPIAMENTU_ARUBA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Sardinian, Campidanese") , LANGUAGE_USER_SARDINIAN_CAMPIDANESE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Sardinian, Gallurese") , LANGUAGE_USER_SARDINIAN_GALLURESE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Sardinian, Logudorese") , LANGUAGE_USER_SARDINIAN_LOGUDORESE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Sardinian, Sassarese") , LANGUAGE_USER_SARDINIAN_SASSARESE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Bafia") , LANGUAGE_USER_BAFIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Gikuyu") , LANGUAGE_USER_GIKUYU }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Yoruba") , LANGUAGE_YORUBA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Rusyn (Ukraine)") , LANGUAGE_USER_RUSYN_UKRAINE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Rusyn (Slovakia)") , LANGUAGE_USER_RUSYN_SLOVAKIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Kabyle Latin") , LANGUAGE_TAMAZIGHT_LATIN_ALGERIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Yiddish (USA)") , LANGUAGE_USER_YIDDISH_US }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Hawaiian") , LANGUAGE_HAWAIIAN_UNITED_STATES }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Limbu") , LANGUAGE_USER_LIMBU }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Lojban") , LANGUAGE_USER_LOJBAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Haitian") , LANGUAGE_USER_HAITIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Beembe") , LANGUAGE_USER_BEEMBE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Bekwel") , LANGUAGE_USER_BEKWEL }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Kituba (Congo)") , LANGUAGE_USER_KITUBA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Lari") , LANGUAGE_USER_LARI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Mbochi") , LANGUAGE_USER_MBOCHI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Teke-Eboo") , LANGUAGE_USER_TEKE_EBOO }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Teke-Ibali") , LANGUAGE_USER_TEKE_IBALI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Teke-Tyee") , LANGUAGE_USER_TEKE_TYEE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Vili") , LANGUAGE_USER_VILI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "KeyID") , LANGUAGE_USER_KEYID }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Pali Latin") , LANGUAGE_USER_PALI_LATIN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Kyrgyz (China)") , LANGUAGE_USER_KYRGYZ_CHINA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Komi-Zyrian") , LANGUAGE_USER_KOMI_ZYRIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Komi-Permyak") , LANGUAGE_USER_KOMI_PERMYAK }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Pitjantjatjara") , LANGUAGE_USER_PITJANTJATJARA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "English (Malawi)") , LANGUAGE_USER_ENGLISH_MALAWI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Erzya") , LANGUAGE_USER_ERZYA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Mari, Meadow") , LANGUAGE_USER_MARI_MEADOW }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Papiamento (Curaçao)") , LANGUAGE_USER_PAPIAMENTU_CURACAO }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Papiamento (Bonaire)") , LANGUAGE_USER_PAPIAMENTU_BONAIRE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Khanty") , LANGUAGE_USER_KHANTY }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Livonian") , LANGUAGE_USER_LIVONIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Moksha") , LANGUAGE_USER_MOKSHA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Mari, Hill") , LANGUAGE_USER_MARI_HILL }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Nganasan") , LANGUAGE_USER_NGANASAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Olonets") , LANGUAGE_USER_OLONETS }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Veps") , LANGUAGE_USER_VEPS }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Võro") , LANGUAGE_USER_VORO }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Nenets") , LANGUAGE_USER_NENETS }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Aka (Central African Republic)") , LANGUAGE_USER_AKA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Aka (Congo)") , LANGUAGE_USER_AKA_CONGO }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Dibole") , LANGUAGE_USER_DIBOLE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Doondo") , LANGUAGE_USER_DOONDO }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Kaamba") , LANGUAGE_USER_KAAMBA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Koongo (Congo)") , LANGUAGE_USER_KOONGO_CONGO }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Kunyi") , LANGUAGE_USER_KUNYI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Ngungwel") , LANGUAGE_USER_NGUNGWEL }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Njyem (Congo)") , LANGUAGE_USER_NJYEM_CONGO }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Punu") , LANGUAGE_USER_PUNU_CONGO }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Suundi") , LANGUAGE_USER_SUUNDI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Teke-Kukuya") , LANGUAGE_USER_TEKE_KUKUYA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Tsaangi") , LANGUAGE_USER_TSAANGI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Yaka (Congo)") , LANGUAGE_USER_YAKA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Yaka (Democratic Republic of the Congo)") , LANGUAGE_USER_YAKA_DRCONGO }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Yombe (Congo)") , LANGUAGE_USER_YOMBE_CONGO }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "N'ko") , LANGUAGE_USER_NKO }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Udmurt") , LANGUAGE_USER_UDMURT }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Tibetan (India)") , LANGUAGE_USER_TIBETAN_INDIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Cornish") , LANGUAGE_USER_CORNISH }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Sami, Pite (Sweden)") , LANGUAGE_USER_SAMI_PITE_SWEDEN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Ngäbere") , LANGUAGE_USER_NGAEBERE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Kumyk") , LANGUAGE_USER_KUMYK }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Nogai") , LANGUAGE_USER_NOGAI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Karakalpak Latin") , LANGUAGE_USER_KARAKALPAK_LATIN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Ladin") , LANGUAGE_USER_LADIN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "French (Burkina Faso)") , LANGUAGE_USER_FRENCH_BURKINA_FASO }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Puinave") , LANGUAGE_USER_PUINAVE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Maninkakan, Eastern, Latin") , LANGUAGE_USER_MANINKAKAN_EASTERN_LATIN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Avar") , LANGUAGE_USER_AVAR }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Cree, Plains, Latin") , LANGUAGE_USER_CREE_PLAINS_LATIN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Cree, Plains, Syllabics") , LANGUAGE_USER_CREE_PLAINS_SYLLABICS }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Lengo") , LANGUAGE_USER_LENGO }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "French (Côte d'Ivoire)") , LANGUAGE_FRENCH_COTE_D_IVOIRE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "French (Mali)") , LANGUAGE_FRENCH_MALI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "French (Senegal)") , LANGUAGE_FRENCH_SENEGAL }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "French (Benin)") , LANGUAGE_USER_FRENCH_BENIN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "French (Niger)") , LANGUAGE_USER_FRENCH_NIGER }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "French (Togo)") , LANGUAGE_USER_FRENCH_TOGO }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Kven Finnish") , LANGUAGE_USER_KVEN_FINNISH }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Venetian") , LANGUAGE_USER_VENETIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "English (Gambia)") , LANGUAGE_USER_ENGLISH_GAMBIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Aranese") , LANGUAGE_USER_OCCITAN_ARANESE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Arpitan (France)") , LANGUAGE_USER_ARPITAN_FRANCE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Arpitan (Italy)") , LANGUAGE_USER_ARPITAN_ITALY }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Arpitan (Switzerland)") , LANGUAGE_USER_ARPITAN_SWITZERLAND }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "English (Botswana)") , LANGUAGE_USER_ENGLISH_BOTSWANA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Interlingue Occidental") , LANGUAGE_USER_INTERLINGUE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Apatani") , LANGUAGE_USER_APATANI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "English (Mauritius)") , LANGUAGE_USER_ENGLISH_MAURITIUS }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "French (Mauritius)") , LANGUAGE_USER_FRENCH_MAURITIUS }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Silesian") , LANGUAGE_USER_SILESIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Hungarian (Szekely-Hungarian Rovas)") , LANGUAGE_USER_HUNGARIAN_ROVAS }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "English (Malaysia)") , LANGUAGE_ENGLISH_MALAYSIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Manchu") , LANGUAGE_USER_MANCHU }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Xibe") , LANGUAGE_USER_XIBE }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Kituba (Democratic Republic of the Congo)"), LANGUAGE_USER_KITUBA_DRCONGO }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Fon"), LANGUAGE_USER_FON }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Plautdietsch"), LANGUAGE_USER_PLAUTDIETSCH }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Armenian, Eastern (Russia)") , LANGUAGE_USER_ARMENIAN_RUSSIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Armenian, Eastern (Iran)") , LANGUAGE_USER_ARMENIAN_IRAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Armenian, Western (Armenia)") , LANGUAGE_USER_ARMENIAN_WESTERN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Armenian, Classical (Armenia)") , LANGUAGE_USER_ARMENIAN_CLASSICAL }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Malay Arabic (Malaysia)") , LANGUAGE_USER_MALAY_ARABIC_MALAYSIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Malay Arabic (Brunei Darussalam)") , LANGUAGE_USER_MALAY_ARABIC_BRUNEI }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Juǀ’hoan") , LANGUAGE_USER_JUHOAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Naro") , LANGUAGE_USER_NARO }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Iloko") , LANGUAGE_USER_ILOKO }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "English (Zambia)") , LANGUAGE_USER_ENGLISH_ZAMBIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "English (Sri Lanka)") , LANGUAGE_USER_ENGLISH_SRI_LANKA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "English (Nigeria)") , LANGUAGE_USER_ENGLISH_NIGERIA }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Kabardian") , LANGUAGE_USER_KABARDIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Guadeloupean Creole French") , LANGUAGE_USER_GUADELOUPEAN_CREOLE_FRENCH }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Ligurian") , LANGUAGE_USER_LIGURIAN }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Minangkabau") , LANGUAGE_USER_MINANGKABAU }, + { NC_("STR_ARR_SVT_LANGUAGE_TABLE", "Sundanese") , LANGUAGE_USER_SUNDANESE } +}; + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/inc/pch/precompiled_svt.cxx b/svtools/inc/pch/precompiled_svt.cxx new file mode 100644 index 000000000..56e1a70fe --- /dev/null +++ b/svtools/inc/pch/precompiled_svt.cxx @@ -0,0 +1,12 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.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 "precompiled_svt.hxx" + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/inc/pch/precompiled_svt.hxx b/svtools/inc/pch/precompiled_svt.hxx new file mode 100644 index 000000000..71d8eefd4 --- /dev/null +++ b/svtools/inc/pch/precompiled_svt.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 has been autogenerated by update_pch.sh. It is possible to edit it + manually (such as when an include file has been moved/renamed/removed). All such + manual changes will be rewritten by the next run of update_pch.sh (which presumably + also fixes all possible problems, so it's usually better to use it). + + Generated on 2020-04-25 20:55:31 using: + ./bin/update_pch svtools svt --cutoff=4 --exclude:system --include:module --exclude:local + + If after updating build fails, use the following command to locate conflicting headers: + ./bin/update_pch_bisect ./svtools/inc/pch/precompiled_svt.hxx "make svtools.build" --find-conflicts +*/ + +#if PCH_LEVEL >= 1 +#include <algorithm> +#include <cassert> +#include <cmath> +#include <cstddef> +#include <cstring> +#include <deque> +#include <float.h> +#include <functional> +#include <initializer_list> +#include <iomanip> +#include <limits.h> +#include <limits> +#include <list> +#include <map> +#include <math.h> +#include <memory> +#include <new> +#include <optional> +#include <ostream> +#include <set> +#include <stddef.h> +#include <string.h> +#include <string> +#include <string_view> +#include <type_traits> +#include <typeinfo> +#include <unordered_map> +#include <utility> +#include <vector> +#include <boost/property_tree/ptree.hpp> +#include <boost/property_tree/ptree_fwd.hpp> +#endif // PCH_LEVEL >= 1 +#if PCH_LEVEL >= 2 +#include <osl/diagnose.h> +#include <osl/endian.h> +#include <osl/file.hxx> +#include <osl/interlck.h> +#include <osl/mutex.hxx> +#include <osl/thread.h> +#include <osl/time.h> +#include <rtl/alloc.h> +#include <rtl/bootstrap.hxx> +#include <rtl/character.hxx> +#include <rtl/instance.hxx> +#include <rtl/math.h> +#include <rtl/math.hxx> +#include <rtl/ref.hxx> +#include <rtl/strbuf.h> +#include <rtl/strbuf.hxx> +#include <rtl/string.h> +#include <rtl/string.hxx> +#include <rtl/stringconcat.hxx> +#include <rtl/stringutils.hxx> +#include <rtl/tencinfo.h> +#include <rtl/textcvt.h> +#include <rtl/textenc.h> +#include <rtl/unload.h> +#include <rtl/uri.hxx> +#include <rtl/ustrbuf.h> +#include <rtl/ustrbuf.hxx> +#include <rtl/ustring.h> +#include <rtl/ustring.hxx> +#include <rtl/uuid.h> +#include <sal/config.h> +#include <sal/log.hxx> +#include <sal/macros.h> +#include <sal/saldllapi.h> +#include <sal/types.h> +#include <sal/typesizes.h> +#include <vcl/EnumContext.hxx> +#include <vcl/GraphicExternalLink.hxx> +#include <vcl/NotebookBarAddonsMerger.hxx> +#include <vcl/Scanline.hxx> +#include <vcl/accessiblefactory.hxx> +#include <vcl/alpha.hxx> +#include <vcl/animate/Animation.hxx> +#include <vcl/animate/AnimationBitmap.hxx> +#include <vcl/bitmap.hxx> +#include <vcl/bitmapex.hxx> +#include <vcl/builder.hxx> +#include <vcl/button.hxx> +#include <vcl/checksum.hxx> +#include <vcl/commandevent.hxx> +#include <vcl/ctrl.hxx> +#include <vcl/dllapi.h> +#include <vcl/dndhelp.hxx> +#include <vcl/dockwin.hxx> +#include <vcl/edit.hxx> +#include <vcl/errcode.hxx> +#include <vcl/event.hxx> +#include <vcl/floatwin.hxx> +#include <vcl/fntstyle.hxx> +#include <vcl/font.hxx> +#include <vcl/gfxlink.hxx> +#include <vcl/graph.hxx> +#include <vcl/graphicfilter.hxx> +#include <vcl/help.hxx> +#include <vcl/idle.hxx> +#include <vcl/image.hxx> +#include <vcl/imapobj.hxx> +#include <vcl/keycod.hxx> +#include <vcl/keycodes.hxx> +#include <vcl/mapmod.hxx> +#include <vcl/menu.hxx> +#include <vcl/outdev.hxx> +#include <vcl/ptrstyle.hxx> +#include <vcl/region.hxx> +#include <vcl/scopedbitmapaccess.hxx> +#include <vcl/scrbar.hxx> +#include <vcl/settings.hxx> +#include <vcl/spinfld.hxx> +#include <vcl/svapp.hxx> +#include <vcl/syswin.hxx> +#include <vcl/task.hxx> +#include <vcl/textfilter.hxx> +#include <vcl/textview.hxx> +#include <vcl/timer.hxx> +#include <vcl/transfer.hxx> +#include <vcl/vclenum.hxx> +#include <vcl/vclevent.hxx> +#include <vcl/vclptr.hxx> +#include <vcl/vclreferencebase.hxx> +#include <vcl/vectorgraphicdata.hxx> +#include <vcl/virdev.hxx> +#include <vcl/weld.hxx> +#include <vcl/window.hxx> +#include <vcl/windowstate.hxx> +#endif // PCH_LEVEL >= 2 +#if PCH_LEVEL >= 3 +#include <basegfx/basegfxdllapi.h> +#include <basegfx/color/bcolor.hxx> +#include <basegfx/numeric/ftools.hxx> +#include <basegfx/point/b2dpoint.hxx> +#include <basegfx/point/b2ipoint.hxx> +#include <basegfx/polygon/b2dpolygon.hxx> +#include <basegfx/polygon/b2dpolypolygon.hxx> +#include <basegfx/range/b2drange.hxx> +#include <basegfx/range/basicrange.hxx> +#include <basegfx/tuple/b2dtuple.hxx> +#include <basegfx/tuple/b2ituple.hxx> +#include <basegfx/tuple/b3dtuple.hxx> +#include <basegfx/utils/common.hxx> +#include <basegfx/vector/b2dsize.hxx> +#include <basegfx/vector/b2dvector.hxx> +#include <basegfx/vector/b2enums.hxx> +#include <basegfx/vector/b2ivector.hxx> +#include <com/sun/star/accessibility/AccessibleEventId.hpp> +#include <com/sun/star/accessibility/AccessibleStateType.hpp> +#include <com/sun/star/accessibility/XAccessible.hpp> +#include <com/sun/star/awt/Key.hpp> +#include <com/sun/star/awt/KeyGroup.hpp> +#include <com/sun/star/awt/XActionListener.hpp> +#include <com/sun/star/awt/XAdjustmentListener.hpp> +#include <com/sun/star/awt/XDevice.hpp> +#include <com/sun/star/awt/XDockableWindow.hpp> +#include <com/sun/star/awt/XFocusListener.hpp> +#include <com/sun/star/awt/XItemListener.hpp> +#include <com/sun/star/awt/XKeyListener.hpp> +#include <com/sun/star/awt/XLayoutConstrains.hpp> +#include <com/sun/star/awt/XMenuListener.hpp> +#include <com/sun/star/awt/XMouseListener.hpp> +#include <com/sun/star/awt/XMouseMotionListener.hpp> +#include <com/sun/star/awt/XPaintListener.hpp> +#include <com/sun/star/awt/XSpinListener.hpp> +#include <com/sun/star/awt/XStyleSettingsSupplier.hpp> +#include <com/sun/star/awt/XSystemDependentWindowPeer.hpp> +#include <com/sun/star/awt/XTabListener.hpp> +#include <com/sun/star/awt/XTextListener.hpp> +#include <com/sun/star/awt/XTopWindow2.hpp> +#include <com/sun/star/awt/XTopWindowListener.hpp> +#include <com/sun/star/awt/XUnitConversion.hpp> +#include <com/sun/star/awt/XVclContainer.hpp> +#include <com/sun/star/awt/XVclContainerListener.hpp> +#include <com/sun/star/awt/XVclContainerPeer.hpp> +#include <com/sun/star/awt/XVclWindowPeer.hpp> +#include <com/sun/star/awt/XView.hpp> +#include <com/sun/star/awt/XWindow.hpp> +#include <com/sun/star/awt/XWindow2.hpp> +#include <com/sun/star/awt/XWindowListener.hpp> +#include <com/sun/star/awt/grid/XGridSelectionListener.hpp> +#include <com/sun/star/awt/tab/XTabPageContainerListener.hpp> +#include <com/sun/star/awt/tree/XTreeEditListener.hpp> +#include <com/sun/star/awt/tree/XTreeExpansionListener.hpp> +#include <com/sun/star/beans/Property.hpp> +#include <com/sun/star/beans/PropertyAttribute.hpp> +#include <com/sun/star/beans/PropertyState.hpp> +#include <com/sun/star/beans/PropertyValue.hpp> +#include <com/sun/star/beans/XFastPropertySet.hpp> +#include <com/sun/star/beans/XMultiPropertySet.hpp> +#include <com/sun/star/beans/XPropertiesChangeListener.hpp> +#include <com/sun/star/beans/XPropertySet.hpp> +#include <com/sun/star/beans/XPropertySetInfo.hpp> +#include <com/sun/star/beans/XPropertySetOption.hpp> +#include <com/sun/star/beans/XPropertyState.hpp> +#include <com/sun/star/beans/XVetoableChangeListener.hpp> +#include <com/sun/star/container/XContainerListener.hpp> +#include <com/sun/star/container/XNameAccess.hpp> +#include <com/sun/star/container/XNameReplace.hpp> +#include <com/sun/star/datatransfer/DataFlavor.hpp> +#include <com/sun/star/datatransfer/XTransferable2.hpp> +#include <com/sun/star/datatransfer/clipboard/XClipboard.hpp> +#include <com/sun/star/datatransfer/clipboard/XClipboardOwner.hpp> +#include <com/sun/star/datatransfer/dnd/DNDConstants.hpp> +#include <com/sun/star/datatransfer/dnd/DropTargetDragEvent.hpp> +#include <com/sun/star/datatransfer/dnd/DropTargetDropEvent.hpp> +#include <com/sun/star/datatransfer/dnd/XDragGestureListener.hpp> +#include <com/sun/star/datatransfer/dnd/XDragSourceListener.hpp> +#include <com/sun/star/datatransfer/dnd/XDropTargetListener.hpp> +#include <com/sun/star/embed/Aspects.hpp> +#include <com/sun/star/frame/XDispatchProvider.hpp> +#include <com/sun/star/frame/XFrame.hpp> +#include <com/sun/star/frame/XStatusListener.hpp> +#include <com/sun/star/frame/XTerminateListener.hpp> +#include <com/sun/star/frame/XToolbarController.hpp> +#include <com/sun/star/i18n/Calendar2.hpp> +#include <com/sun/star/i18n/ForbiddenCharacters.hpp> +#include <com/sun/star/i18n/LanguageCountryInfo.hpp> +#include <com/sun/star/i18n/LocaleDataItem2.hpp> +#include <com/sun/star/i18n/LocaleItem.hpp> +#include <com/sun/star/i18n/NativeNumberXmlAttributes.hpp> +#include <com/sun/star/i18n/TransliterationModules.hpp> +#include <com/sun/star/i18n/TransliterationModulesExtra.hpp> +#include <com/sun/star/i18n/reservedWords.hpp> +#include <com/sun/star/lang/DisposedException.hpp> +#include <com/sun/star/lang/EventObject.hpp> +#include <com/sun/star/lang/Locale.hpp> +#include <com/sun/star/lang/XComponent.hpp> +#include <com/sun/star/lang/XEventListener.hpp> +#include <com/sun/star/lang/XInitialization.hpp> +#include <com/sun/star/lang/XMultiServiceFactory.hpp> +#include <com/sun/star/lang/XServiceInfo.hpp> +#include <com/sun/star/lang/XTypeProvider.hpp> +#include <com/sun/star/lang/XUnoTunnel.hpp> +#include <com/sun/star/uno/Any.h> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Exception.hpp> +#include <com/sun/star/uno/Reference.h> +#include <com/sun/star/uno/Reference.hxx> +#include <com/sun/star/uno/RuntimeException.hpp> +#include <com/sun/star/uno/Sequence.h> +#include <com/sun/star/uno/Sequence.hxx> +#include <com/sun/star/uno/Type.h> +#include <com/sun/star/uno/Type.hxx> +#include <com/sun/star/uno/TypeClass.hdl> +#include <com/sun/star/uno/XAggregation.hpp> +#include <com/sun/star/uno/XComponentContext.hpp> +#include <com/sun/star/uno/XInterface.hpp> +#include <com/sun/star/uno/XWeak.hpp> +#include <com/sun/star/uno/genfunc.h> +#include <com/sun/star/util/Date.hpp> +#include <com/sun/star/util/DateTime.hpp> +#include <com/sun/star/util/Time.hpp> +#include <com/sun/star/util/URLTransformer.hpp> +#include <com/sun/star/util/XNumberFormatsSupplier.hpp> +#include <com/sun/star/util/XUpdatable.hpp> +#include <com/sun/star/view/PrintableState.hpp> +#include <com/sun/star/view/XSelectionChangeListener.hpp> +#include <comphelper/broadcasthelper.hxx> +#include <comphelper/comphelperdllapi.h> +#include <comphelper/interfacecontainer2.hxx> +#include <comphelper/processfactory.hxx> +#include <comphelper/propagg.hxx> +#include <comphelper/proparrhlp.hxx> +#include <comphelper/propertycontainer.hxx> +#include <comphelper/propertycontainerhelper.hxx> +#include <comphelper/propstate.hxx> +#include <comphelper/sequence.hxx> +#include <comphelper/servicehelper.hxx> +#include <comphelper/string.hxx> +#include <comphelper/uno3.hxx> +#include <cppu/cppudllapi.h> +#include <cppu/unotype.hxx> +#include <cppuhelper/basemutex.hxx> +#include <cppuhelper/compbase_ex.hxx> +#include <cppuhelper/cppuhelperdllapi.h> +#include <cppuhelper/implbase.hxx> +#include <cppuhelper/implbase2.hxx> +#include <cppuhelper/implbase_ex.hxx> +#include <cppuhelper/implbase_ex_post.hxx> +#include <cppuhelper/implbase_ex_pre.hxx> +#include <cppuhelper/interfacecontainer.h> +#include <cppuhelper/interfacecontainer.hxx> +#include <cppuhelper/propshlp.hxx> +#include <cppuhelper/queryinterface.hxx> +#include <cppuhelper/supportsservice.hxx> +#include <cppuhelper/weak.hxx> +#include <cppuhelper/weakagg.hxx> +#include <cppuhelper/weakref.hxx> +#include <i18nlangtag/lang.h> +#include <i18nlangtag/languagetag.hxx> +#include <i18nutil/i18nutildllapi.h> +#include <i18nutil/transliteration.hxx> +#include <o3tl/cow_wrapper.hxx> +#include <o3tl/deleter.hxx> +#include <o3tl/safeint.hxx> +#include <o3tl/strong_int.hxx> +#include <o3tl/typed_flags_set.hxx> +#include <o3tl/underlyingenumvalue.hxx> +#include <salhelper/thread.hxx> +#include <sot/exchange.hxx> +#include <sot/formats.hxx> +#include <sot/sotdllapi.h> +#include <svl/SfxBroadcaster.hxx> +#include <svl/hint.hxx> +#include <svl/macitem.hxx> +#include <svl/poolitem.hxx> +#include <svl/svldllapi.h> +#include <svl/typedwhich.hxx> +#include <toolkit/awt/vclxcontainer.hxx> +#include <toolkit/awt/vclxdevice.hxx> +#include <toolkit/awt/vclxwindow.hxx> +#include <toolkit/dllapi.h> +#include <toolkit/helper/listenermultiplexer.hxx> +#include <toolkit/helper/macros.hxx> +#include <toolkit/helper/mutexhelper.hxx> +#include <toolkit/helper/vclunohelper.hxx> +#include <tools/color.hxx> +#include <tools/date.hxx> +#include <tools/datetime.hxx> +#include <tools/debug.hxx> +#include <tools/diagnose_ex.h> +#include <tools/fldunit.hxx> +#include <tools/fontenum.hxx> +#include <tools/fract.hxx> +#include <tools/gen.hxx> +#include <tools/globname.hxx> +#include <tools/lineend.hxx> +#include <tools/link.hxx> +#include <tools/mapunit.hxx> +#include <tools/ref.hxx> +#include <tools/solar.h> +#include <tools/stream.hxx> +#include <tools/time.hxx> +#include <tools/toolsdllapi.h> +#include <tools/urlobj.hxx> +#include <tools/wintypes.hxx> +#include <typelib/typeclass.h> +#include <typelib/typedescription.h> +#include <typelib/uik.h> +#include <ucbhelper/content.hxx> +#include <uno/any2.h> +#include <uno/data.h> +#include <uno/sequence2.h> +#include <unotools/accessiblestatesethelper.hxx> +#include <unotools/calendarwrapper.hxx> +#include <unotools/configitem.hxx> +#include <unotools/configmgr.hxx> +#include <unotools/localedatawrapper.hxx> +#include <unotools/nativenumberwrapper.hxx> +#include <unotools/options.hxx> +#include <unotools/readwritemutexguard.hxx> +#include <unotools/resmgr.hxx> +#include <unotools/streamwrap.hxx> +#include <unotools/syslocale.hxx> +#include <unotools/transliterationwrapper.hxx> +#include <unotools/unotoolsdllapi.h> +#endif // PCH_LEVEL >= 3 +#if PCH_LEVEL >= 4 +#include <svtools/brwbox.hxx> +#include <svtools/colorcfg.hxx> +#include <svtools/htmlkywd.hxx> +#include <svtools/htmltokn.h> +#include <svtools/svtdllapi.h> +#include <svtools/svtresid.hxx> +#include <svtools/valueset.hxx> +#endif // PCH_LEVEL >= 4 + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/inc/strings.hxx b/svtools/inc/strings.hxx new file mode 100644 index 000000000..5e7199c4a --- /dev/null +++ b/svtools/inc/strings.hxx @@ -0,0 +1,25 @@ +/* -*- 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 + +// no need to translate this +// the items in this string have to be in the same order as the STR_FIELD_* strings are added to the +// field label list of the dialog +#define STR_LOGICAL_FIELD_NAMES "FirstName;LastName;Company;Department;Street;Zip;City;State;Country;PhonePriv;PhoneComp;PhoneOffice;PhoneCell;PhoneOther;Pager;Fax;EMail;URL;Title;Position;Code;AddrForm;AddrFormMail;Id;CalendarURL;InviteParticipant;Note;Altfield1;Altfield2;Altfield3;Altfield4" + +#define STR_DESCRIPTION_SMATH_DOC "StarMath 2.0 - 5.0" +#define STR_DESCRIPTION_SCHART_DOC "StarChart 3.0 - 5.0" +#define STR_DESCRIPTION_SDRAW_DOC "StarDraw 3.0 / 5.0 (StarImpress)" +#define STR_DESCRIPTION_SCALC_DOC "StarCalc 3.0 - 5.0" +#define STR_DESCRIPTION_SIMPRESS_DOC "StarImpress 4.0 / 5.0" +#define STR_DESCRIPTION_SWRITER_DOC "StarWriter 3.0 - 5.0" + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/svtools/inc/svmedit.hxx b/svtools/inc/svmedit.hxx new file mode 100644 index 000000000..bafa79ea1 --- /dev/null +++ b/svtools/inc/svmedit.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_SVTOOLS_SVMEDIT_HXX +#define INCLUDED_SVTOOLS_SVMEDIT_HXX + +#include <vcl/vclmedit.hxx> + +class MultiLineEdit : public VclMultiLineEdit +{ +public: + MultiLineEdit( vcl::Window* pParent, WinBits nWinStyle ); + + virtual css::uno::Reference< css::awt::XWindowPeer > GetComponentInterface(bool bCreate = true) override; +}; + +#endif // INCLUDED_SVTOOLS_SVMEDIT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/inc/svmedit2.hxx b/svtools/inc/svmedit2.hxx new file mode 100644 index 000000000..7d4570034 --- /dev/null +++ b/svtools/inc/svmedit2.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_SVTOOLS_SVMEDIT2_HXX +#define INCLUDED_SVTOOLS_SVMEDIT2_HXX + +#include "svmedit.hxx" + +class TextAttrib; + +class ExtMultiLineEdit final : public MultiLineEdit +{ +public: + ExtMultiLineEdit( vcl::Window* pParent, WinBits nWinStyle ); + + // methods of TextView + void InsertText( const OUString& rNew ); + void SetAutoScroll( bool bAutoScroll ); + + // methods of TextEngine + void SetAttrib( const TextAttrib& rAttr, sal_uInt32 nPara, sal_Int32 nStart, sal_Int32 nEnd ); + void SetLeftMargin( sal_uInt16 nLeftMargin ); + sal_uInt32 GetParagraphCount() const; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/inc/table/defaultinputhandler.hxx b/svtools/inc/table/defaultinputhandler.hxx new file mode 100644 index 000000000..c09328c50 --- /dev/null +++ b/svtools/inc/table/defaultinputhandler.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 <table/tableinputhandler.hxx> + +#include <memory> + + +namespace svt::table +{ + + + struct DefaultInputHandler_Impl; + + + //= DefaultInputHandler + + class DefaultInputHandler final : public ITableInputHandler + { + private: + ::std::unique_ptr< DefaultInputHandler_Impl > m_pImpl; + + public: + DefaultInputHandler(); + virtual ~DefaultInputHandler() override; + + virtual bool MouseMove ( ITableControl& _rControl, const MouseEvent& rMEvt ) override; + virtual bool MouseButtonDown ( ITableControl& _rControl, const MouseEvent& rMEvt ) override; + virtual bool MouseButtonUp ( ITableControl& _rControl, const MouseEvent& rMEvt ) override; + virtual bool KeyInput ( ITableControl& _rControl, const KeyEvent& rKEvt ) override; + virtual bool GetFocus ( ITableControl& _rControl ) override; + virtual bool LoseFocus ( ITableControl& _rControl ) override; + }; + + +} // namespace svt::table + + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/inc/table/gridtablerenderer.hxx b/svtools/inc/table/gridtablerenderer.hxx new file mode 100644 index 000000000..e372de324 --- /dev/null +++ b/svtools/inc/table/gridtablerenderer.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 . + */ + +#pragma once + +#include <table/tablemodel.hxx> +#include <vcl/image.hxx> + +#include <memory> + + +namespace svt::table +{ + + + struct GridTableRenderer_Impl; + + + //= GridTableRenderer + + /** a default implementation for the ->ITableRenderer interface + + This class is able to paint a table grid, table headers, and cell + backgrounds according to the selected/active state of cells. + */ + class GridTableRenderer final : public ITableRenderer + { + private: + ::std::unique_ptr< GridTableRenderer_Impl > m_pImpl; + + public: + /** creates a table renderer associated with the given model + + @param _rModel + the model which should be rendered. The caller is responsible + for lifetime control, that is, the model instance must live + at least as long as the renderer instance lives + */ + GridTableRenderer( ITableModel& _rModel ); + virtual ~GridTableRenderer() override; + + /** determines whether or not to paint grid lines + */ + bool useGridLines() const; + + /** controls whether or not to paint grid lines + */ + void useGridLines( bool const i_use ); + + public: + // ITableRenderer overridables + virtual void PaintHeaderArea( + vcl::RenderContext& _rDevice, const tools::Rectangle& _rArea, + bool _bIsColHeaderArea, bool _bIsRowHeaderArea, + const StyleSettings& _rStyle ) override; + virtual void PaintColumnHeader( ColPos _nCol, + vcl::RenderContext& _rDevice, const tools::Rectangle& _rArea, + const StyleSettings& _rStyle ) override; + virtual void PrepareRow( RowPos _nRow, bool i_hasControlFocus, bool _bSelected, + vcl::RenderContext& _rDevice, const tools::Rectangle& _rRowArea, + const StyleSettings& _rStyle ) override; + virtual void PaintRowHeader( + vcl::RenderContext& _rDevice, const tools::Rectangle& _rArea, + const StyleSettings& _rStyle ) override; + virtual void PaintCell( ColPos const i_col, + bool i_hasControlFocus, bool _bSelected, + vcl::RenderContext& _rDevice, const tools::Rectangle& _rArea, + const StyleSettings& _rStyle ) override; + virtual void ShowCellCursor( vcl::Window& _rView, const tools::Rectangle& _rCursorRect) override; + virtual void HideCellCursor( vcl::Window& _rView ) override; + virtual bool FitsIntoCell( + css::uno::Any const & i_cellContent, + OutputDevice& i_targetDevice, tools::Rectangle const & i_targetArea + ) const override; + virtual bool GetFormattedCellString( + css::uno::Any const & i_cellValue, + OUString & o_cellString + ) const override; + + private: + struct CellRenderContext; + + void impl_paintCellContent( + CellRenderContext const & i_context + ); + void impl_paintCellImage( + CellRenderContext const & i_context, + Image const & i_image + ); + void impl_paintCellText( + CellRenderContext const & i_context, + OUString const & i_text + ); + }; + +} // namespace svt::table + + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/inc/table/tablecontrol.hxx b/svtools/inc/table/tablecontrol.hxx new file mode 100644 index 000000000..fb6868f3d --- /dev/null +++ b/svtools/inc/table/tablecontrol.hxx @@ -0,0 +1,174 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <svtools/svtdllapi.h> +#include <table/tablemodel.hxx> +#include <vcl/accessibletable.hxx> + +#include <vcl/ctrl.hxx> +#include <vcl/seleng.hxx> + +#include <memory> + +namespace svt::table +{ + class TableControl_Impl; + + + //= TableControl + + /** a basic control which manages table-like data, i.e. a number of cells + organized in <code>m</code> rows and <code>n</code> columns. + + The control itself does not do any assumptions about the concrete data + it displays, this is encapsulated in an instance supporting the + ->ITableModel interface. + + Also, the control does not do any assumptions about how the model's + content is rendered. This is the responsibility of a component + supporting the ->ITableRenderer interface (the renderer is obtained from + the model). + + The control supports the concept of a <em>current</em> (or <em>active</em> + cell). + The control supports accessibility, this is encapsulated in IAccessibleTable + */ + class TableControl final : public Control, public vcl::table::IAccessibleTable + { + private: + std::shared_ptr<TableControl_Impl> m_pImpl; + + + public: + TableControl( vcl::Window* _pParent, WinBits _nStyle ); + virtual ~TableControl() override; + virtual void dispose() override; + + /// sets a new table model + void SetModel( const PTableModel& _pModel ); + /// retrieves the current table model + PTableModel GetModel() const; + + /** retrieves the current row + + The current row is the one which contains the active cell. + + @return + the row index of the active cell, or ->ROW_INVALID + if there is no active cell, e.g. because the table does + not contain any rows or columns. + */ + sal_Int32 GetCurrentRow() const override; + + ITableControl& + getTableControlInterface(); + + /** retrieves the current column + + The current col is the one which contains the active cell. + + @return + the column index of the active cell, or ->COL_INVALID + if there is no active cell, e.g. because the table does + not contain any rows or columns. + */ + sal_Int32 GetCurrentColumn() const override; + + /** activates the cell at the given position + */ + void GoTo( ColPos _nColumnPos, RowPos _nRow); + + virtual void Resize() override; + void Select(); + + /**after removing a row, updates the vector which contains the selected rows + if the row, which should be removed, is selected, it will be erased from the vector + */ + SelectionEngine* getSelEngine(); + vcl::Window& getDataWindow(); + + // Window overridables + virtual void GetFocus() override; + virtual void LoseFocus() override; + virtual void KeyInput( const KeyEvent& rKEvt ) override; + virtual void StateChanged( StateChangedType i_nStateChange ) override; + + /** Creates and returns the accessible object of the whole GridControl. */ + virtual css::uno::Reference< css::accessibility::XAccessible > CreateAccessible() override; + virtual css::uno::Reference< css::accessibility::XAccessible > CreateAccessibleControl( sal_Int32 _nIndex ) override; + virtual OUString GetAccessibleObjectName(vcl::table::AccessibleTableControlObjType eObjType, sal_Int32 _nRow, sal_Int32 _nCol) const override; + virtual void GoToCell( sal_Int32 _nColumnPos, sal_Int32 _nRow ) override; + virtual OUString GetAccessibleObjectDescription(vcl::table::AccessibleTableControlObjType eObjType) const override; + virtual void FillAccessibleStateSet( ::utl::AccessibleStateSetHelper& rStateSet, vcl::table::AccessibleTableControlObjType eObjType ) const override; + + // temporary methods + // Those do not really belong into the public API - they're intended for firing A11Y-related events. However, + // firing those events should be an implementation internal to the TableControl resp. TableControl_Impl, + // instead of something triggered externally. + void commitCellEventIfAccessibleAlive( sal_Int16 const i_eventID, const css::uno::Any& i_newValue, const css::uno::Any& i_oldValue ); + void commitTableEventIfAccessibleAlive( sal_Int16 const i_eventID, const css::uno::Any& i_newValue, const css::uno::Any& i_oldValue ); + + + // IAccessibleTable + virtual tools::Rectangle GetWindowExtentsRelative( 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; + virtual sal_Int32 GetAccessibleControlCount() const override; + virtual bool ConvertPointToControlIndex( sal_Int32& _rnIndex, const Point& _rPoint ) override; + virtual long GetRowCount() const override; + virtual long GetColumnCount() const override; + virtual bool ConvertPointToCellAddress( sal_Int32& _rnRow, sal_Int32& _rnColPos, const Point& _rPoint ) override; + virtual tools::Rectangle calcHeaderRect( bool _bIsColumnBar ) override; + virtual tools::Rectangle calcHeaderCellRect( bool _bIsColumnBar, sal_Int32 nPos) override; + virtual tools::Rectangle calcTableRect() override; + virtual tools::Rectangle calcCellRect( sal_Int32 _nRowPos, sal_Int32 _nColPos ) 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 void FillAccessibleStateSetForCell( ::utl::AccessibleStateSetHelper& _rStateSet, sal_Int32 _nRow, sal_uInt16 _nColumnPos ) const override; + virtual OUString GetRowName(sal_Int32 _nIndex) const override; + virtual OUString GetColumnName( sal_Int32 _nIndex ) const override; + virtual bool HasRowHeader() override; + virtual bool HasColHeader() override; + virtual OUString GetAccessibleCellText(sal_Int32 _nRowPos, sal_Int32 _nColPos) const override; + + virtual sal_Int32 GetSelectedRowCount() const override; + virtual sal_Int32 GetSelectedRowIndex( sal_Int32 const i_selectionIndex ) const override; + virtual bool IsRowSelected( sal_Int32 const i_rowIndex ) const override; + virtual void SelectRow( sal_Int32 const i_rowIndex, bool const i_select ) override; + virtual void SelectAllRows( bool const i_select ) override; + + + private: + DECL_LINK( ImplSelectHdl, LinkParamNone*, void ); + + private: + TableControl( const TableControl& ) = delete; + TableControl& operator=( const TableControl& ) = delete; + }; + + +} // namespace svt::table + + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/inc/table/tablecontrolinterface.hxx b/svtools/inc/table/tablecontrolinterface.hxx new file mode 100644 index 000000000..69670d2bd --- /dev/null +++ b/svtools/inc/table/tablecontrolinterface.hxx @@ -0,0 +1,243 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <sal/types.h> +#include <vcl/seleng.hxx> + +#include <table/tabletypes.hxx> +#include <table/tablemodel.hxx> + + +namespace svt::table +{ + + + //= TableControlAction + + enum TableControlAction + { + /// moves the cursor in the table control one row up, if possible, by keeping the current column + cursorUp, + /// moves the cursor in the table control one row down, if possible, by keeping the current column + cursorDown, + /// moves the cursor in the table control one column to the left, if possible, by keeping the current row + cursorLeft, + /// moves the cursor in the table control one column to the right, if possible, by keeping the current row + cursorRight, + /// moves the cursor to the beginning of the current line + cursorToLineStart, + /// moves the cursor to the end of the current line + cursorToLineEnd, + /// moves the cursor to the first row, keeping the current column + cursorToFirstLine, + /// moves the cursor to the last row, keeping the current column + cursorToLastLine, + /// moves the cursor one page up, keeping the current column + cursorPageUp, + /// moves the cursor one page down, keeping the current column + cursorPageDown, + /// moves the cursor to the top-most, left-most cell + cursorTopLeft, + /// moves the cursor to the bottom-most, right-most cell + cursorBottomRight, + /// selects the row, where the actual cursor is + cursorSelectRow, + /// selects the rows, above the actual cursor is + cursorSelectRowUp, + /// selects the row, beneath the actual cursor is + cursorSelectRowDown, + /// selects the row, from the actual cursor till top + cursorSelectRowAreaTop, + /// selects the row, from the actual cursor till bottom + cursorSelectRowAreaBottom, + + /// invalid and final enumeration value, not to be actually used + invalidTableControlAction + }; + + + //= TableCellArea + + enum TableCellArea + { + CellContent, + ColumnDivider + }; + + + //= TableCell + + struct TableCell + { + ColPos nColumn; + RowPos nRow; + TableCellArea eArea; + + TableCell( ColPos const i_column, RowPos const i_row ) + :nColumn( i_column ) + ,nRow( i_row ) + ,eArea( CellContent ) + { + } + }; + + + //= ColumnMetrics + + struct ColumnMetrics + { + /** the start of the column, in pixels. Might be negative, in case the column is scrolled out of the visible + area. Note: see below. + */ + long nStartPixel; + + /** the end of the column, in pixels, plus 1. Effectively, this is the accumulated width of all columns + up to the current one. + + Huh? Earlier you said that the nStartPixel of columns + scrolled out (to the left) of the visible area is + negative. Also, where is the promise that there is no gap + between columns? The above claim would be true only if the + first column always started at zero, and there is never a + gap. So these doc comments are inconsistent. How + surprising. + */ + long nEndPixel; + + ColumnMetrics() + :nStartPixel(0) + ,nEndPixel(0) + { + } + + ColumnMetrics( long const i_start, long const i_end ) + :nStartPixel( i_start ) + ,nEndPixel( i_end ) + { + } + }; + + + //= TableArea + + enum class TableArea + { + ColumnHeaders, + RowHeaders, + All + }; + + + //= ITableControl + + /** defines a callback interface to be implemented by a concrete table control + */ + class SAL_NO_VTABLE ITableControl + { + public: + /** hides the cell cursor + + The method cares for successive calls, that is, for every call to + ->hideCursor(), you need one call to ->showCursor. Only if the number + of both calls matches, the cursor is really shown. + + @see showCursor + */ + virtual void hideCursor() = 0; + + /** shows the cell cursor + + @see hideCursor + */ + virtual void showCursor() = 0; + + /** dispatches an action to the table control + + @return + <TRUE/> if the action could be dispatched successfully, <FALSE/> otherwise. Usual + failure conditions include some other instance vetoing the action, or impossibility + to execute the action at all (for instance moving up one row when already positioned + on the very first row). + + @see TableControlAction + */ + virtual bool dispatchAction( TableControlAction _eAction ) = 0; + + /** returns selection engine*/ + virtual SelectionEngine* getSelEngine() = 0; + + /** returns the table model + + The returned model is guaranteed to not be <NULL/>. + */ + virtual PTableModel getModel() const = 0; + + /// returns the index of the currently active column + virtual ColPos getCurrentColumn() const = 0; + + /// returns the index of the currently active row + virtual RowPos getCurrentRow() const = 0; + + /// activates the given cell + virtual void activateCell( ColPos const i_col, RowPos const i_row ) = 0; + + /// retrieves the size of the table window, in pixels + virtual ::Size getTableSizePixel() const = 0; + + /// sets a new mouse pointer for the table window + virtual void setPointer( PointerStyle i_pointer ) = 0; + + /// captures the mouse to the table window + virtual void captureMouse() = 0; + + /// releases the mouse, after it had previously been captured + virtual void releaseMouse() = 0; + + /// invalidates the table window + virtual void invalidate( TableArea const i_what ) = 0; + + /// calculates a width, given in pixels, into an AppFont-based width + virtual long pixelWidthToAppFont( long const i_pixels ) const = 0; + + /// shows a tracking rectangle + virtual void showTracking( tools::Rectangle const & i_location, ShowTrackFlags const i_flags ) = 0; + + /// hides a previously shown tracking rectangle + virtual void hideTracking() = 0; + + /// does a hit test for the given pixel coordinates + virtual TableCell hitTest( const Point& rPoint ) const = 0; + + /// retrieves the metrics for a given column + virtual ColumnMetrics getColumnMetrics( ColPos const i_column ) const = 0; + + /// determines whether a given row is selected + virtual bool isRowSelected( RowPos _nRow ) const = 0; + + virtual ~ITableControl() {}; + }; + + +} // namespace svt::table + + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/inc/table/tableinputhandler.hxx b/svtools/inc/table/tableinputhandler.hxx new file mode 100644 index 000000000..9d11df38d --- /dev/null +++ b/svtools/inc/table/tableinputhandler.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 <memory> + +class MouseEvent; +class KeyEvent; + + +namespace svt::table +{ + + + class ITableControl; + + + //= ITableInputHandler + + /** interface for components handling input in a ->TableControl + */ + class ITableInputHandler + { + public: + // all those methods have the same semantics as the equal-named methods of ->Window, + // with the additional option to return a boolean value indicating whether + // the event should be further processed by the ->Window implementations (<FALSE/>), + // or whether it has been sufficiently handled by the ->ITableInputHandler instance + // (<FALSE/>). + + virtual bool MouseMove ( ITableControl& _rControl, const MouseEvent& rMEvt ) = 0; + virtual bool MouseButtonDown ( ITableControl& _rControl, const MouseEvent& rMEvt ) = 0; + virtual bool MouseButtonUp ( ITableControl& _rControl, const MouseEvent& rMEvt ) = 0; + virtual bool KeyInput ( ITableControl& _rControl, const KeyEvent& rKEvt ) = 0; + virtual bool GetFocus ( ITableControl& _rControl ) = 0; + virtual bool LoseFocus ( ITableControl& _rControl ) = 0; + + virtual ~ITableInputHandler() { } + }; + typedef std::shared_ptr< ITableInputHandler > PTableInputHandler; + + +} // namespace svt::table + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/inc/table/tablemodel.hxx b/svtools/inc/table/tablemodel.hxx new file mode 100644 index 000000000..b3bcc36e9 --- /dev/null +++ b/svtools/inc/table/tablemodel.hxx @@ -0,0 +1,454 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <svtools/svtdllapi.h> +#include <table/tabletypes.hxx> +#include <table/tablerenderer.hxx> +#include <table/tableinputhandler.hxx> + +#include <com/sun/star/style/VerticalAlignment.hpp> +#include <com/sun/star/style/HorizontalAlignment.hpp> + +#include <sal/types.h> + +#include <optional> +#include <memory> +#include <vector> +#include <o3tl/typed_flags_set.hxx> + +namespace svt::table { class ITableDataSort; } + +class Color; + +enum class ColumnAttributeGroup +{ + NONE = 0x00, + /// denotes column attributes related to the width of the column + WIDTH = 0x01, + /// denotes column attributes related to the appearance of the column, i.e. those relevant for rendering + APPEARANCE = 0x02, + /// denotes the entirety of column attributes + ALL = 0x03, +}; +namespace o3tl +{ + template<> struct typed_flags<ColumnAttributeGroup> : is_typed_flags<ColumnAttributeGroup, 0x03> {}; +} + + +namespace svt::table +{ + //= ScrollbarVisibility + enum ScrollbarVisibility + { + /** enumeration value denoting that a scrollbar should never be visible, even + if needed normally + */ + ScrollbarShowNever, + /** enumeration value denoting that a scrollbar should be visible when needed only + */ + ScrollbarShowSmart, + /** enumeration value denoting that a scrollbar should always be visible, even + if not needed normally + */ + ScrollbarShowAlways + }; + + + //= ITableModelListener + + /** declares an interface to be implemented by components interested in + changes in an ->ITableModel + */ + class SAL_NO_VTABLE ITableModelListener : public std::enable_shared_from_this< ITableModelListener > + { + public: + /** notifies the listener that one or more rows have been inserted into + the table + + @param first + the index of the first newly inserted row + @param last + the index of the last newly inserted row. Must not be smaller + than ->first + */ + virtual void rowsInserted( RowPos first, RowPos last ) = 0; + + /** notifies the listener that one or more rows have been removed from + the table + + @param first + the old index of the first removed row. If this is <code>-1</code>, then all + rows have been removed from the model. + @param last + the old index of the last removed row. Must not be smaller + than ->first + */ + virtual void rowsRemoved( RowPos first, RowPos last ) = 0; + + /** notifies the listener that one or more columns have been inserted into + the table + */ + virtual void columnInserted() = 0; + + /** notifies the listener that one or more columns have been removed from + the table + */ + virtual void columnRemoved() = 0; + + /** notifies the listener that all columns have been removed from the model + */ + virtual void allColumnsRemoved() = 0; + + /** notifies the listener that a rectangular cell range in the table + has been updated + + Listeners are required to discard any possibly cached information + they have about the cells in question, in particular any possibly + cached cell values. + */ + virtual void cellsUpdated( RowPos const i_firstRow, RowPos const i_lastRow ) = 0; + + /** notifies the listener that attributes of a given column changed + + @param i_column + the position of the column whose attributes changed + @param i_attributeGroup + a combination of one or more <code>COL_ATTRS_*</code> flags, denoting the attribute group(s) + in which changes occurred. + */ + virtual void columnChanged( ColPos const i_column, ColumnAttributeGroup const i_attributeGroup ) = 0; + + /** notifies the listener that the metrics of the table changed. + + Metrics here include the column header height, the row header width, the row height, and the presence + of both the row and column header. + */ + virtual void tableMetricsChanged() = 0; + + /// deletes the listener instance + virtual ~ITableModelListener(){}; + }; + typedef std::shared_ptr< ITableModelListener > PTableModelListener; + + + //= IColumnModel + + /** interface to be implemented by table column models + */ + class SAL_NO_VTABLE IColumnModel + { + public: + /** returns the name of the column + + Column names should be human-readable, but not necessarily unique + within a given table. + + @see setName + */ + virtual OUString getName() const = 0; + + /** retrieves the help text to be displayed for the column. + */ + virtual OUString getHelpText() const = 0; + + /** determines whether the column can be interactively resized + + @see getMinWidth + @see getMaxWidth + @see getWidth + */ + virtual bool isResizable() const = 0; + + /** denotes the relative flexibility of the column + + This flexibility is taken into account when a table control auto-resizes its columns, because the available + space changed. In this case, the columns grow or shrink according to their flexibility. + + A value of 0 means the column is not auto-resized at all. + */ + virtual sal_Int32 getFlexibility() const = 0; + + /** returns the width of the column, in app-font units + + The returned value must be a positive ->TableMetrics value. + + @see setWidth + @see getMinWidth + @see getMaxWidth + */ + virtual TableMetrics getWidth() const = 0; + + /** sets a new width for the column + + @param _nWidth + the new width, app-font units + + @see getWidth + */ + virtual void setWidth( TableMetrics _nWidth ) = 0; + + /** returns the minimum width of the column, in app-font units, or 0 if the column + does not have a minimal width + + @see setMinWidth + @see getMaxWidth + @see getWidth + */ + virtual TableMetrics getMinWidth() const = 0; + + /** returns the maximum width of the column, in app-font units, or 0 if the column + does not have a minimal width + + @see setMaxWidth + @see getMinWidth + @see getWidth + */ + virtual TableMetrics getMaxWidth() const = 0; + + /** retrieves the horizontal alignment to be used for content in this cell + */ + virtual css::style::HorizontalAlignment getHorizontalAlign() = 0; + + /// deletes the column model instance + virtual ~IColumnModel() { } + }; + typedef std::shared_ptr< IColumnModel > PColumnModel; + + + //= ITableModel + + /** declares the interface to implement by an abstract table model + */ + class SAL_NO_VTABLE SVT_DLLPUBLIC ITableModel + { + public: + /** returns the number of columns in the table + */ + virtual TableSize getColumnCount() const = 0; + + /** returns the number of rows in the table + */ + virtual TableSize getRowCount() const = 0; + + /** determines whether the table has column headers + + If this method returns <TRUE/>, the renderer returned by + ->getRenderer must be able to render column headers. + + @see IColumnRenderer + */ + virtual bool hasColumnHeaders() const = 0; + + /** determines whether the table has row headers + + If this method returns <TRUE/>, the renderer returned by + ->getRenderer must be able to render row headers. + + @see IColumnRenderer + */ + virtual bool hasRowHeaders() const = 0; + + /** returns a model for a certain column + + @param column + the index of the column in question. Must be greater than or + equal 0, and smaller than the return value of ->getColumnCount() + + @return + the model of the column in question. Must not be <NULL/> + */ + virtual PColumnModel getColumnModel( ColPos column ) = 0; + + /** returns a renderer which is able to paint the table represented + by this table model + + @return the renderer to use. Must not be <NULL/> + */ + virtual PTableRenderer getRenderer() const = 0; + + /** returns the component handling input in a view associated with the model + */ + virtual PTableInputHandler getInputHandler() const = 0; + + /** determines the height of rows in the table. + + @return + the logical height of rows in the table, in app-font units. The height must be + greater 0. + */ + virtual TableMetrics getRowHeight() const = 0; + + /** determines the height of the column header row + + This method is not to be called if ->hasColumnHeaders() + returned <FALSE/>. + + @return + the logical height of the column header row, in app-font units. + Must be greater than 0. + */ + virtual TableMetrics getColumnHeaderHeight() const = 0; + + /** determines the width of the row header column + + This method is not to be called if ->hasRowHeaders() + returned <FALSE/>. + + @return + the logical width of the row header column, in app-font units. + Must be greater than 0. + */ + virtual TableMetrics getRowHeaderWidth() const = 0; + + /** returns the visibility mode of the vertical scrollbar + */ + virtual ScrollbarVisibility getVerticalScrollbarVisibility() const = 0; + + /** returns the visibility mode of the horizontal scrollbar + */ + virtual ScrollbarVisibility getHorizontalScrollbarVisibility() const = 0; + + /** adds a listener to be notified of changes in the table model + */ + virtual void addTableModelListener( const PTableModelListener& i_listener ) = 0; + + /** remove a listener to be notified of changes in the table model + */ + virtual void removeTableModelListener( const PTableModelListener& i_listener ) = 0; + + /** retrieves the content of the given cell + */ + virtual void getCellContent( ColPos const i_col, RowPos const i_row, css::uno::Any& o_cellContent ) = 0; + + /** returns an object which should be displayed as tooltip for the given cell + + At the moment, only string-convertible values are supported here. In the future, one might imagine displaying + scaled-down versions of a graphic in a cell, and a larger version of that very graphic as tooltip. + + If no tooltip object is provided, then the cell content is used, and displayed as tooltip for the cell + if and only if it doesn't fit into the cell's space itself. + + @param i_col + The column index of the cell in question. COL_ROW_HEADERS is a valid argument here. + @param i_row + The row index of the cell in question. + @param o_cellToolTip + takes the tooltip object upon return. + */ + virtual void getCellToolTip( ColPos const i_col, RowPos const i_row, css::uno::Any & o_cellToolTip ) = 0; + + /** retrieves title of a given row + */ + virtual css::uno::Any getRowHeading( RowPos const i_rowPos ) const = 0; + + /** returns the color to be used for rendering the grid lines. + + If this value is not set, a default color from the style settings will be used. + */ + virtual ::std::optional< ::Color > getLineColor() const = 0; + + /** returns the color to be used for rendering the header background. + + If this value is not set, a default color from the style settings will be used. + */ + virtual ::std::optional< ::Color > getHeaderBackgroundColor() const = 0; + + /** returns the color to be used for rendering the header text. + + If this value is not set, a default color from the style settings will be used. + */ + virtual ::std::optional< ::Color > getHeaderTextColor() const = 0; + + /** returns the color to be used for the background of selected cells, when the control has the focus + + If this value is not set, a default color from the style settings will be used. + */ + virtual ::std::optional< ::Color > getActiveSelectionBackColor() const = 0; + + /** returns the color to be used for the background of selected cells, when the control does not have the focus + + If this value is not set, a default color from the style settings will be used. + */ + virtual ::std::optional< ::Color > getInactiveSelectionBackColor() const = 0; + + /** returns the color to be used for the text of selected cells, when the control has the focus + + If this value is not set, a default color from the style settings will be used. + */ + virtual ::std::optional< ::Color > getActiveSelectionTextColor() const = 0; + + /** returns the color to be used for the text of selected cells, when the control does not have the focus + + If this value is not set, a default color from the style settings will be used. + */ + virtual ::std::optional< ::Color > getInactiveSelectionTextColor() const = 0; + + /** returns the color to be used for rendering cell texts. + + If this value is not set, a default color from the style settings will be used. + */ + virtual ::std::optional< ::Color > getTextColor() const = 0; + + /** returns the color to be used for text lines (underline, strikethrough) when rendering cell text. + + If this value is not set, a default color from the style settings will be used. + */ + virtual ::std::optional< ::Color > getTextLineColor() const = 0; + + /** returns the colors to be used for the row backgrounds. + + If this value is not set, every second row will have a background color derived from the style settings's + selection color, the other rows will not have a special background at all. + + If this value is an empty sequence, the rows will not have a special background at all, instead the + normal background of the complete control will be used. + + If value is a non-empty sequence, then rows will have the background colors as specified in the sequence, + in alternating order. + */ + virtual ::std::optional< ::std::vector< ::Color > > + getRowBackgroundColors() const = 0; + + /** determines the vertical alignment of content within a cell + */ + virtual css::style::VerticalAlignment getVerticalAlign() const = 0; + + /** returns an adapter to the sorting functionality of the model + + It is legitimate to return <NULL/> here, in this case, the table model does not support sorting. + */ + virtual ITableDataSort* getSortAdapter() = 0; + + /** returns enabled state. + */ + virtual bool isEnabled() const = 0; + + /// destroys the table model instance + virtual ~ITableModel() { } + }; + typedef std::shared_ptr< ITableModel > PTableModel; + + +} // namespace svt::table + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/inc/table/tablerenderer.hxx b/svtools/inc/table/tablerenderer.hxx new file mode 100644 index 000000000..c43bac818 --- /dev/null +++ b/svtools/inc/table/tablerenderer.hxx @@ -0,0 +1,249 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <table/tabletypes.hxx> + +#include <rtl/ustring.hxx> + +#include <memory> + +namespace com :: sun :: star :: uno { class Any; } +namespace tools { class Rectangle; } +namespace vcl { class Window; } + +class OutputDevice; +class StyleSettings; +namespace vcl { + typedef OutputDevice RenderContext; +}; + + +namespace svt::table +{ + + + //= ITableRenderer + + /** interface to implement by components rendering a ->TableControl + */ + class SAL_NO_VTABLE ITableRenderer + { + public: + + /** paints a (part of) header area + + There are two header areas in a table control: + <ul><li>The row containing all column headers, i.e. <em>above</em> all rows containing the data</li> + <li>The column containing all row headers. i.e. <em>left of</em> all columns containing the data</li> + </ul> + + A header area is more than the union of the single column/row headers. + + First, there might be less columns than fit into the view - in this case, right + beside the right-most column, there's still room which belongs to the column header + area, but is not occupied by any particular column header.<br/> + An equivalent statement holds for the row header area, if there are fewer rows than + fit into the view. + + Second, if the table control has both a row header and a column header, + the intersection between those both belongs to both the column header area and the + row header area, but not to any particular column or row header. + + There are two flags specifying whether the to-be-painted area is part of the column + and/or row header area. + <ul><li>If both are <TRUE/>, the intersection of both areas is to be painted.</li> + <li>If ->_bIsColHeaderArea is <TRUE/> and ->_bIsRowHeaderArea is <FALSE/>, + then ->_rArea denotes the column header area <em>excluding</em> the + intersection between row and column header area.</li> + <li>Equivalently for ->_bIsColHeaderArea being <FALSE/> and ->_bIsRowHeaderArea + being <TRUE/></li> + </ul> + Note that it's not possible for both ->_bIsColHeaderArea and ->_bIsRowHeaderArea + to be <FALSE/> at the same time. + + @param _rDevice + the device to paint onto + @param _rArea + the area to paint into + @param _bIsColHeaderArea + <TRUE/> if and only if ->_rArea is part of the column header area. + @param _bIsRowHeaderArea + <TRUE/> if and only if ->_rArea is part of the row header area. + @param _rStyle + the style to be used for drawing + */ + virtual void PaintHeaderArea( + vcl::RenderContext& _rDevice, const tools::Rectangle& _rArea, + bool _bIsColHeaderArea, bool _bIsRowHeaderArea, + const StyleSettings& _rStyle ) = 0; + + /** paints the header for a given column + + @param _nCol + the index of the column to paint + @param _rDevice + denotes the device to paint onto + @param _rArea + the are into which the column header should be painted + @param _rStyle + the style to be used for drawing + */ + virtual void PaintColumnHeader( ColPos _nCol, + vcl::RenderContext& _rDevice, const tools::Rectangle& _rArea, + const StyleSettings& _rStyle ) = 0; + + /** prepares a row for painting + + Painting a table means painting rows as necessary, in an increasing + order. The assumption is that retrieving data for two different rows + is (potentially) more expensive than retrieving data for two different + columns. Thus, the renderer will get the chance to "seek" to a certain + row, and then has to render all cells in this row, before another + row is going to be painted. + + @param _nRow + the row which is going to be painted. The renderer should + at least remember this row, since subsequent calls to + ->PaintRowHeader(), ->PaintCell(), and ->FinishRow() will + not pass this parameter again. + + However, the renderer is also allowed to render any + cell-independent content of this row. + + @param i_hasControlFocus + <TRUE/> if and only if the table control currently has the focus + @param _bSelected + <TRUE/> if and only if the row to be prepared is + selected currently. + @param _rDevice + denotes the device to paint onto + @param _rRowArea + the are into which the row should be painted. This excludes + the row header area, if applicable. + @param _rStyle + the style to be used for drawing + */ + virtual void PrepareRow( RowPos _nRow, bool i_hasControlFocus, bool _bSelected, + vcl::RenderContext& _rDevice, const tools::Rectangle& _rRowArea, + const StyleSettings& _rStyle ) = 0; + + /** paints the header of a row + + The row to be painted is denoted by the most recent call to + ->PrepareRow. + + @param _rDevice + denotes the device to paint onto + @param _rArea + the are into which the row header should be painted + @param _rStyle + the style to be used for drawing + */ + virtual void PaintRowHeader( + vcl::RenderContext& _rDevice, tools::Rectangle const & _rArea, + StyleSettings const & _rStyle ) = 0; + + /** paints a certain cell + + The row to be painted is denoted by the most recent call to + ->PrepareRow. + + @param _bSelected + <TRUE/> if and only if the cell to be painted is + selected currently. This is the case if either + the row or the column of the cell is currently selected. + <br/> + Note that this flag is equal to the respective flag in the + previous ->PrepareRow call, it's passed here for convenience + only. + @param i_hasControlFocus + <TRUE/> if and only if the table control currently has the focus + <br/> + Note that this flag is equal to the respective flag in the + previous ->PrepareRow call, it's passed here for convenience + only. + @param _rDevice + denotes the device to paint onto + @param _rArea + the are into which the cell should be painted + @param _rStyle + the style to be used for drawing + */ + virtual void PaintCell( ColPos const i_col, + bool i_hasControlFocus, bool _bSelected, + vcl::RenderContext& _rDevice, const tools::Rectangle& _rArea, + const StyleSettings& _rStyle ) = 0; + + /** draws a cell cursor in the given rectangle + + The cell cursor is used to indicate the active/current cell + of a table control. + */ + virtual void ShowCellCursor( vcl::Window& _rView, const tools::Rectangle& _rCursorRect) = 0; + + /** hides the cell cursor previously drawn into the given rectangle + + The cell cursor is used to indicate the active/current cell + of a table control. + */ + virtual void HideCellCursor( vcl::Window& _rView ) = 0; + + /** checks whether a given cell content fits into a given target area on a given device. + + @param i_targetDevice + denotes the target device for the assumed rendering operation + + @param i_targetArea + denotes the area within the target device for the assumed rendering operation. + + @return + <TRUE/> if and only if the given cell content could be rendered into the given device and the + given area. + */ + virtual bool FitsIntoCell( + css::uno::Any const & i_cellContent, + OutputDevice& i_targetDevice, tools::Rectangle const & i_targetArea + ) const = 0; + + /** attempts to format the content of the given cell as string + + @param i_cellValue + the value for which an attempt for a string conversion should be made + @param o_cellString + the cell content, formatted as string + @return + <TRUE/> if and only if the content could be formatted as string + */ + virtual bool GetFormattedCellString( + css::uno::Any const & i_cellValue, + OUString & o_cellString + ) const = 0; + + /// deletes the renderer instance + virtual ~ITableRenderer() { } + }; + typedef std::shared_ptr< ITableRenderer > PTableRenderer; + + +} // namespace svt::table + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/inc/table/tablesort.hxx b/svtools/inc/table/tablesort.hxx new file mode 100644 index 000000000..699086352 --- /dev/null +++ b/svtools/inc/table/tablesort.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 <table/tabletypes.hxx> + + +namespace svt::table +{ + + + //= ColumnSortDirection + + enum ColumnSortDirection + { + ColumnSortAscending, + ColumnSortDescending + }; + + + //= ColumnSort + + struct ColumnSort + { + ColPos nColumnPos; + ColumnSortDirection eSortDirection; + + ColumnSort() + :nColumnPos( COL_INVALID ) + ,eSortDirection( ColumnSortAscending ) + { + } + + }; + + + //= ITableDataSort + + /** provides sorting functionality for the data underlying an ITableModel + */ + class SAL_NO_VTABLE ITableDataSort + { + public: + /** sorts the rows in the model by the given column's data, in the given direction. + */ + virtual void sortByColumn( ColPos const i_column, ColumnSortDirection const i_sortDirection ) = 0; + + /** retrieves the current sort order of the data + + If the <code>nColumnIndex</code> member of the returned structure is <code>COL_INVALID</code>, then + the data is currently not sorted. + */ + virtual ColumnSort getCurrentSortOrder() const = 0; + + protected: + ~ITableDataSort() {} + }; + + +} // namespace svt::table + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/inc/table/tabletypes.hxx b/svtools/inc/table/tabletypes.hxx new file mode 100644 index 000000000..8fdb18a83 --- /dev/null +++ b/svtools/inc/table/tabletypes.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 <sal/types.h> + + +namespace svt::table +{ + + /// a value denoting the size of a table + typedef sal_Int32 TableSize; + + /// a value denoting a column position within a table + typedef sal_Int32 ColPos; + /// a value denoting a row position within a table + typedef sal_Int32 RowPos; + + typedef sal_Int32 TableMetrics; + +/// denotes the column containing the row headers +#define COL_ROW_HEADERS (::svt::table::ColPos(-1)) +/// denotes the row containing the column headers +#define ROW_COL_HEADERS (::svt::table::RowPos(-1)) + +/// denotes an invalid column index +#define COL_INVALID (::svt::table::ColPos(-2)) +/// denotes an invalid row index +#define ROW_INVALID (::svt::table::RowPos(-2)) + + +} // namespace svt::table + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/inc/templwin.hrc b/svtools/inc/templwin.hrc new file mode 100644 index 000000000..0147a694f --- /dev/null +++ b/svtools/inc/templwin.hrc @@ -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 <utility> + +#define NC_(Context, String) reinterpret_cast<char const *>(Context "\004" u8##String) + +#define DI_TITLE 1 +#define DI_FROM 2 +#define DI_DATE 3 +#define DI_KEYWORDS 4 +#define DI_DESCRIPTION 5 +#define DI_MIMETYPE 6 +#define DI_MODIFIEDDATE 7 +#define DI_MODIFIEDBY 8 +#define DI_PRINTDATE 9 +#define DI_PRINTBY 10 +#define DI_THEME 11 +#define DI_SIZE 12 + +const std::pair<const char*, int> STRARY_SVT_DOCINFO[] = +{ + { NC_("STRARY_SVT_DOCINFO", "Title") , DI_TITLE }, + { NC_("STRARY_SVT_DOCINFO", "By") , DI_FROM }, + { NC_("STRARY_SVT_DOCINFO", "Date") , DI_DATE }, + { NC_("STRARY_SVT_DOCINFO", "Keywords") , DI_KEYWORDS }, + { NC_("STRARY_SVT_DOCINFO", "Description") , DI_DESCRIPTION }, + { NC_("STRARY_SVT_DOCINFO", "Type") , DI_MIMETYPE }, + { NC_("STRARY_SVT_DOCINFO", "Modified on") , DI_MODIFIEDDATE }, + { NC_("STRARY_SVT_DOCINFO", "Modified by") , DI_MODIFIEDBY }, + { NC_("STRARY_SVT_DOCINFO", "Printed on") , DI_PRINTDATE }, + { NC_("STRARY_SVT_DOCINFO", "Printed by") , DI_PRINTBY }, + { NC_("STRARY_SVT_DOCINFO", "Subject") , DI_THEME }, + { NC_("STRARY_SVT_DOCINFO", "Size") , DI_SIZE } +}; + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/langsupport/langsupport.cxx b/svtools/langsupport/langsupport.cxx new file mode 100644 index 000000000..7c25d8382 --- /dev/null +++ b/svtools/langsupport/langsupport.cxx @@ -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/. + */ + +#include <com/sun/star/lang/XComponent.hpp> +#include <com/sun/star/lang/XMultiServiceFactory.hpp> +#include <com/sun/star/uno/XComponentContext.hpp> +#include <comphelper/processfactory.hxx> +#include <cppuhelper/bootstrap.hxx> +#include <i18nlangtag/languagetag.hxx> +#include <sal/main.h> +#include <svtools/langtab.hxx> +#include <tools/diagnose_ex.h> +#include <tools/extendapplicationenvironment.hxx> +#include <vcl/svapp.hxx> +#include <iostream> +#include <sal/log.hxx> + +using namespace com::sun::star; + +SAL_IMPLEMENT_MAIN() +{ + try + { + tools::extendApplicationEnvironment(); + + uno::Reference<uno::XComponentContext> xContext = + cppu::defaultBootstrap_InitialComponentContext(); + + uno::Reference<lang::XMultiComponentFactory> xFactory = + xContext->getServiceManager(); + + uno::Reference<lang::XMultiServiceFactory> xSFactory(xFactory, + uno::UNO_QUERY_THROW); + + comphelper::setProcessServiceFactory(xSFactory); + + InitVCL(); + + { + sal_uInt32 nCount = SvtLanguageTable::GetLanguageEntryCount(); + for (sal_uInt32 i = 0; i < nCount; ++i) + { + LanguageType eLang = SvtLanguageTable::GetLanguageTypeAtIndex(i); + + if (eLang == LANGUAGE_DONTKNOW || + eLang == LANGUAGE_NONE || + eLang == LANGUAGE_HID_HUMAN_INTERFACE_DEVICE || + eLang == LANGUAGE_SYSTEM) + { + continue; + } + + OUString sTag( LanguageTag::convertToBcp47( eLang)); + + std::cout << sTag << std::endl; + } + } + + DeInitVCL(); + + uno::Reference< lang::XComponent >(xContext, uno::UNO_QUERY_THROW)->dispose(); + } + catch (const uno::Exception&) + { + TOOLS_WARN_EXCEPTION("vcl.app", "Fatal"); + return 1; + } + catch (const std::exception &e) + { + SAL_WARN("vcl.app", "Fatal: " << e.what()); + return 1; + } + + return 0; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/qa/unit/GraphicObjectTest.cxx b/svtools/qa/unit/GraphicObjectTest.cxx new file mode 100644 index 000000000..bb09612f7 --- /dev/null +++ b/svtools/qa/unit/GraphicObjectTest.cxx @@ -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/. + * + */ + +#include <cppunit/extensions/HelperMacros.h> +#include <cppunit/plugin/TestPlugIn.h> + +#include <test/bootstrapfixture.hxx> + +#include <com/sun/star/frame/Desktop.hpp> +#include <unotest/macros_test.hxx> +#include <comphelper/processfactory.hxx> + +using namespace css; + +namespace +{ + +class GraphicObjectTest: public test::BootstrapFixture, public unotest::MacrosTest +{ + +public: + void testTdf88836(); + + virtual void setUp() override + { + test::BootstrapFixture::setUp(); + + mxDesktop.set(css::frame::Desktop::create(comphelper::getComponentContext(getMultiServiceFactory()))); + } + +private: + CPPUNIT_TEST_SUITE(GraphicObjectTest); + CPPUNIT_TEST(testTdf88836); + CPPUNIT_TEST_SUITE_END(); +}; + + +void GraphicObjectTest::testTdf88836() +{ + // Construction with empty bitmap -> type should be GraphicType::NONE + Graphic aGraphic = Bitmap(); + CPPUNIT_ASSERT_EQUAL(int(GraphicType::NONE), int(aGraphic.GetType())); + aGraphic = Graphic(BitmapEx()); + CPPUNIT_ASSERT_EQUAL(int(GraphicType::NONE), int(aGraphic.GetType())); +} + +CPPUNIT_TEST_SUITE_REGISTRATION(GraphicObjectTest); + +} + +CPPUNIT_PLUGIN_IMPLEMENT(); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/qa/unit/data/svtools-dialogs-test.txt b/svtools/qa/unit/data/svtools-dialogs-test.txt new file mode 100644 index 000000000..2ed259ee5 --- /dev/null +++ b/svtools/qa/unit/data/svtools-dialogs-test.txt @@ -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 contains all dialogs that the unit tests in the module +# will work on if it is in script mode. It will read one-by-one, +# try to open it and create a screenshot that will be saved in +# workdir/screenshots using the pattern of the ui-file name. +# +# Syntax: +# - empty lines are allowed +# - lines starting with '#' are treated as comment +# - all other lines should contain a *.ui filename in the same +# notation as in the dialog constructors (see code) + +# +# The 'known' dialogs which have a hard-coded representation +# in registerKnownDialogsByID/createDialogByID +# + +# No known dialogs in svtools for now + +# +# Dialogs without a hard-coded representation. These will +# be visualized using a fallback based on VclBuilder +# + +# currently deactivated, leads to problems and the test to not work +# This is typically a hint that these should be hard-coded in the +# test case since they need some document and model data to work + +svt/ui/addresstemplatedialog.ui +svt/ui/placeedit.ui +svt/ui/printersetupdialog.ui +svt/ui/restartdialog.ui +svt/ui/graphicexport.ui +svt/ui/querydeletedialog.ui +svt/ui/javadisableddialog.ui diff --git a/svtools/qa/unit/svtools-dialogs-test.cxx b/svtools/qa/unit/svtools-dialogs-test.cxx new file mode 100644 index 000000000..be79168bb --- /dev/null +++ b/svtools/qa/unit/svtools-dialogs-test.cxx @@ -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/. + */ + +#include <sal/config.h> +#include <test/screenshot_test.hxx> +#include <vcl/abstdlg.hxx> +#include <vcl/scheduler.hxx> +#include <vcl/wrkwin.hxx> +#include <svtools/valueset.hxx> + +using namespace ::com::sun::star; + +/// Test opening a dialog in svtools +class SvtoolsDialogsTest : public ScreenshotTest +{ +private: + /// helper method to populate KnownDialogs, called in setUp(). Needs to be + /// written and has to add entries to KnownDialogs + virtual void registerKnownDialogsByID(mapType& rKnownDialogs) override; + + /// dialog creation for known dialogs by ID. Has to be implemented for + /// each registered known dialog + virtual VclPtr<VclAbstractDialog> createDialogByID(sal_uInt32 nID) override; + +public: + SvtoolsDialogsTest(); + + // try to open a dialog + void openAnyDialog(); + + CPPUNIT_TEST_SUITE(SvtoolsDialogsTest); + CPPUNIT_TEST(openAnyDialog); + CPPUNIT_TEST_SUITE_END(); +}; + +SvtoolsDialogsTest::SvtoolsDialogsTest() +{ +} + +void SvtoolsDialogsTest::registerKnownDialogsByID(mapType& /*rKnownDialogs*/) +{ + // fill map of known dialogs +} + +VclPtr<VclAbstractDialog> SvtoolsDialogsTest::createDialogByID(sal_uInt32 /*nID*/) +{ + return nullptr; +} + +void SvtoolsDialogsTest::openAnyDialog() +{ + /// process input file containing the UXMLDescriptions of the dialogs to dump + processDialogBatchFile("svtools/qa/unit/data/svtools-dialogs-test.txt"); +} + +CPPUNIT_TEST_SUITE_REGISTRATION(SvtoolsDialogsTest); + +CPPUNIT_PLUGIN_IMPLEMENT(); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/qa/unit/testHtmlReader.cxx b/svtools/qa/unit/testHtmlReader.cxx new file mode 100644 index 000000000..4e5638cc5 --- /dev/null +++ b/svtools/qa/unit/testHtmlReader.cxx @@ -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/. + * + */ + +#include <cppunit/TestFixture.h> +#include <unotest/bootstrapfixturebase.hxx> +#include <svtools/parhtml.hxx> +#include <tools/ref.hxx> +#include <tools/stream.hxx> + +namespace +{ +/// Subclass of HTMLParser that can sense the import result. +class TestHTMLParser : public HTMLParser +{ +public: + TestHTMLParser(SvStream& rStream); + virtual void NextToken(HtmlTokenId nToken) override; + /// Make this public for test purposes. + using HTMLParser::SetNamespace; + + OUString m_aDocument; + int m_nLineBreakCount = 0; +}; + +TestHTMLParser::TestHTMLParser(SvStream& rStream) + : HTMLParser(rStream) +{ +} + +void TestHTMLParser::NextToken(HtmlTokenId nToken) +{ + if (nToken == HtmlTokenId::TEXTTOKEN) + m_aDocument += aToken; + else if (nToken == HtmlTokenId::LINEBREAK) + ++m_nLineBreakCount; +} + +/// Tests HTMLParser. +class Test : public CppUnit::TestFixture +{ +}; + +CPPUNIT_TEST_FIXTURE(Test, testTdf114428) +{ + SvMemoryStream aStream; + OString aDocument("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<html>hello</html>"); + aStream.WriteBytes(aDocument.getStr(), aDocument.getLength()); + aStream.Seek(0); + + tools::SvRef<TestHTMLParser> xParser = new TestHTMLParser(aStream); + xParser->CallParser(); + + // This was '<?xml version="1.0" encoding="utf-8"?> hello', XML declaration + // was not ignored. + CPPUNIT_ASSERT_EQUAL(OUString("hello"), xParser->m_aDocument.trim()); +} + +CPPUNIT_TEST_FIXTURE(Test, testLineBreak) +{ + SvMemoryStream aStream; + OString aDocument("aaa<br></br>bbb"); + aStream.WriteBytes(aDocument.getStr(), aDocument.getLength()); + aStream.Seek(0); + + tools::SvRef<TestHTMLParser> xParser = new TestHTMLParser(aStream); + xParser->SetNamespace("reqif-xhtml"); + xParser->CallParser(); + + // This was 2, <br></br> was interpreted as 2 line breaks in XHTML mode. + CPPUNIT_ASSERT_EQUAL(1, xParser->m_nLineBreakCount); +} +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/qa/unit/testHtmlWriter.cxx b/svtools/qa/unit/testHtmlWriter.cxx new file mode 100644 index 000000000..773da64c4 --- /dev/null +++ b/svtools/qa/unit/testHtmlWriter.cxx @@ -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/. + * + */ + +#include <cppunit/TestFixture.h> +#include <cppunit/plugin/TestPlugIn.h> + +#include <unotest/bootstrapfixturebase.hxx> +#include <tools/stream.hxx> +#include <svtools/HtmlWriter.hxx> + +namespace +{ + +OString extractFromStream(SvMemoryStream& rStream) +{ + rStream.WriteChar('\0'); + rStream.Flush(); + rStream.Seek(STREAM_SEEK_TO_BEGIN); + return static_cast<const char*>(rStream.GetData()); +} + +} + +class Test: public CppUnit::TestFixture +{ +}; + +CPPUNIT_TEST_FIXTURE(Test, testSingleElement) +{ + { + SvMemoryStream aStream; + + HtmlWriter aHtml(aStream); + aHtml.prettyPrint(false); + aHtml.start("abc"); + aHtml.end(); + + OString aString = extractFromStream(aStream); + CPPUNIT_ASSERT_EQUAL(OString("<abc/>"), aString); + } + + { + SvMemoryStream aStream; + + HtmlWriter aHtml(aStream); + aHtml.prettyPrint(false); + aHtml.single("abc"); + + OString aString = extractFromStream(aStream); + + CPPUNIT_ASSERT_EQUAL(OString("<abc/>"), aString); + } +} + +CPPUNIT_TEST_FIXTURE(Test, testSingleElementWithAttributes) +{ + { + SvMemoryStream aStream; + + HtmlWriter aHtml(aStream); + aHtml.prettyPrint(false); + aHtml.start("abc"); + aHtml.attribute("x", "y"); + aHtml.end(); + + OString aString = extractFromStream(aStream); + + CPPUNIT_ASSERT_EQUAL(OString("<abc x=\"y\"/>"), aString); + } + + { + SvMemoryStream aStream; + + HtmlWriter aHtml(aStream); + aHtml.prettyPrint(false); + aHtml.start("abc"); + aHtml.attribute("x", "y"); + aHtml.attribute("q", "w"); + aHtml.end(); + + OString aString = extractFromStream(aStream); + + CPPUNIT_ASSERT_EQUAL(OString("<abc x=\"y\" q=\"w\"/>"), aString); + } +} + +CPPUNIT_TEST_FIXTURE(Test, testSingleElementWithContent) +{ + SvMemoryStream aStream; + + HtmlWriter aHtml(aStream); + aHtml.prettyPrint(false); + aHtml.start("abc"); + aHtml.end(); + + OString aString = extractFromStream(aStream); + + CPPUNIT_ASSERT_EQUAL(OString("<abc/>"), aString); +} + +CPPUNIT_TEST_FIXTURE(Test, testSingleElementWithContentAndAttributes) +{ + SvMemoryStream aStream; + + HtmlWriter aHtml(aStream); + aHtml.prettyPrint(false); + aHtml.start("abc"); + aHtml.attribute("x", "y"); + aHtml.attribute("q", "w"); + aHtml.end(); + + OString aString = extractFromStream(aStream); + + CPPUNIT_ASSERT_EQUAL(OString("<abc x=\"y\" q=\"w\"/>"), aString); +} + +CPPUNIT_TEST_FIXTURE(Test, testNested) +{ + SvMemoryStream aStream; + + HtmlWriter aHtml(aStream); + aHtml.prettyPrint(false); + aHtml.start("abc"); + aHtml.start("xyz"); + aHtml.end(); + aHtml.end(); + + OString aString = extractFromStream(aStream); + + CPPUNIT_ASSERT_EQUAL(OString("<abc><xyz/></abc>"), aString); +} + +CPPUNIT_TEST_FIXTURE(Test, testNamespace) +{ + SvMemoryStream aStream; + + HtmlWriter aHtml(aStream, "reqif-xhtml"); + aHtml.prettyPrint(false); + aHtml.single("br"); + + OString aString = extractFromStream(aStream); + + // This was <br/>, namespace request was ignored. + CPPUNIT_ASSERT_EQUAL(OString("<reqif-xhtml:br/>"), aString); +} + +CPPUNIT_TEST_FIXTURE(Test, testAttributeValues) +{ + SvMemoryStream aStream; + + HtmlWriter aHtml(aStream); + aHtml.prettyPrint(false); + aHtml.start("abc"); + aHtml.attribute("one", OString("one")); + aHtml.attribute("two", OUString("two")); + aHtml.attribute("three", sal_Int32(12)); + aHtml.end(); + + OString aString = extractFromStream(aStream); + + CPPUNIT_ASSERT_EQUAL(OString("<abc one=\"one\" two=\"two\" three=\"12\"/>"), aString); +} + +CPPUNIT_TEST_FIXTURE(Test, testCharacters) +{ + SvMemoryStream aStream; + + HtmlWriter aHtml(aStream); + aHtml.prettyPrint(false); + aHtml.start("abc"); + aHtml.characters("hello"); + aHtml.end(); + + OString aString = extractFromStream(aStream); + + CPPUNIT_ASSERT_EQUAL(OString("<abc>hello</abc>"), aString); +} + +CPPUNIT_PLUGIN_IMPLEMENT(); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/qa/unoapi/knownissues.xcl b/svtools/qa/unoapi/knownissues.xcl new file mode 100644 index 000000000..f8c79ca13 --- /dev/null +++ b/svtools/qa/unoapi/knownissues.xcl @@ -0,0 +1,53 @@ +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# +# This file incorporates work covered by the following license notice: +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed +# with this work for additional information regarding copyright +# ownership. The ASF licenses this file to you under the Apache +# License, Version 2.0 (the "License"); you may not use this file +# except in compliance with the License. You may obtain a copy of +# the License at http://www.apache.org/licenses/LICENSE-2.0 . +# + +### i85237 ### +svtools.AccessibleBrowseBox::com::sun::star::accessibility::XAccessibleEventBroadcaster + +### i85238 ### +svtools.AccessibleBrowseBox::com::sun::star::accessibility::XAccessibleContext + +### i85239 ### +svtools.AccessibleBrowseBoxHeaderBar::com::sun::star::accessibility::XAccessibleEventBroadcaster + +### i85240 ### +svtools.AccessibleTabBar::com::sun::star::accessibility::XAccessibleEventBroadcaster + +### i85244 ### +svtools.AccessibleTabBarPage::com::sun::star::accessibility::XAccessibleEventBroadcaster + +### i85245 ### +svtools.AccessibleBrowseBoxTableCell +# -> test is disabled in svtools.sce + +### i85246 ### +svtools.AccessibleTabBarPageList +# -> test is disabled in svtools.sce + +### i88276 ### +svtools.AccessibleIconChoiceCtrlEntry +# -> test is disabled in svtools.sce + +### i88296 ### +svtools.AccessibleTreeListBox::com::sun::star::accessibility::XAccessibleEventBroadcaster + +### i88300 ### +svtools.AccessibleTreeListBoxEntry::com::sun::star::accessibility::XAccessibleText + +### i88647 ### +svtools.AccessibleTabBarPage diff --git a/svtools/qa/unoapi/svtools.sce b/svtools/qa/unoapi/svtools.sce new file mode 100644 index 000000000..a5ab4ebfa --- /dev/null +++ b/svtools/qa/unoapi/svtools.sce @@ -0,0 +1,30 @@ +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# +# This file incorporates work covered by the following license notice: +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed +# with this work for additional information regarding copyright +# ownership. The ASF licenses this file to you under the Apache +# License, Version 2.0 (the "License"); you may not use this file +# except in compliance with the License. You may obtain a copy of +# the License at http://www.apache.org/licenses/LICENSE-2.0 . +# + +#i88276 -o svtools.AccessibleIconChoiceCtrlEntry +#i88647 -o svtools.AccessibleTabBarPage +#i110988 -o svtools.AccessibleBrowseBox +#i110988 -o svtools.AccessibleBrowseBoxHeaderBar +#i110988 -o svtools.AccessibleBrowseBoxHeaderCell +#i110988 -o svtools.AccessibleBrowseBoxTable +#i85245 -o svtools.AccessibleBrowseBoxTableCell +#i88276 -o svtools.AccessibleIconChoiceCtrl +-o svtools.AccessibleTabBar +#i85246 -o svtools.AccessibleTabBarPageList +#i110988 -o svtools.AccessibleTreeListBox +#i110988 -o svtools.AccessibleTreeListBoxEntry diff --git a/svtools/source/brwbox/brwbox1.cxx b/svtools/source/brwbox/brwbox1.cxx new file mode 100644 index 000000000..ee3922582 --- /dev/null +++ b/svtools/source/brwbox/brwbox1.cxx @@ -0,0 +1,2347 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <svtools/brwbox.hxx> +#include <svtools/brwhead.hxx> +#include <o3tl/numeric.hxx> +#include <o3tl/safeint.hxx> +#include "datwin.hxx" +#include <tools/debug.hxx> +#include <tools/fract.hxx> +#include <sal/log.hxx> +#include <vcl/scrbar.hxx> +#include <vcl/status.hxx> + +#include <algorithm> +#include <com/sun/star/accessibility/AccessibleTableModelChange.hpp> +#include <com/sun/star/accessibility/AccessibleTableModelChangeType.hpp> +#include <com/sun/star/accessibility/AccessibleEventId.hpp> +#include <tools/multisel.hxx> +#include "brwimpl.hxx" + + +#define SCROLL_FLAGS (ScrollFlags::Clip | ScrollFlags::NoChildren) + +using namespace com::sun::star::accessibility::AccessibleEventId; +using namespace com::sun::star::accessibility::AccessibleTableModelChangeType; +using com::sun::star::accessibility::AccessibleTableModelChange; +using namespace ::com::sun::star::uno; +using namespace svt; + +namespace +{ + void disposeAndClearHeaderCell(::svt::BrowseBoxImpl::THeaderCellMap& _rHeaderCell) + { + ::std::for_each( + _rHeaderCell.begin(), + _rHeaderCell.end(), + ::svt::BrowseBoxImpl::THeaderCellMapFunctorDispose() + ); + _rHeaderCell.clear(); + } +} + +void BrowseBox::ConstructImpl( BrowserMode nMode ) +{ + SAL_INFO("svtools", "BrowseBox:ConstructImpl " << this ); + bMultiSelection = false; + pColSel = nullptr; + pVScroll = nullptr; + pDataWin = VclPtr<BrowserDataWin>::Create( this ).get(); + m_pImpl.reset( new ::svt::BrowseBoxImpl() ); + + InitSettings_Impl( this ); + InitSettings_Impl( pDataWin ); + + bBootstrapped = false; + nDataRowHeight = 0; + nTitleLines = 1; + nFirstCol = 0; + nTopRow = 0; + nCurRow = BROWSER_ENDOFSELECTION; + nCurColId = 0; + bResizing = false; + bSelect = false; + bSelecting = false; + bScrolling = false; + bSelectionIsVisible = false; + bNotToggleSel = false; + bRowDividerDrag = false; + bHit = false; + mbInteractiveRowHeight = false; + bHideSelect = false; + bHideCursor = TRISTATE_FALSE; + nRowCount = 0; + m_bFocusOnlyCursor = true; + m_aCursorColor = COL_TRANSPARENT; + m_nCurrentMode = BrowserMode::NONE; + nControlAreaWidth = USHRT_MAX; + uRow.nSel = BROWSER_ENDOFSELECTION; + + aHScroll->SetLineSize(1); + aHScroll->SetScrollHdl( LINK( this, BrowseBox, ScrollHdl ) ); + pDataWin->Show(); + + SetMode( nMode ); + bSelectionIsVisible = bKeepHighlight; + bHasFocus = HasChildPathFocus(); + pDataWin->nCursorHidden = + ( bHasFocus ? 0 : 1 ) + ( GetUpdateMode() ? 0 : 1 ); +} + +BrowseBox::BrowseBox( vcl::Window* pParent, WinBits nBits, BrowserMode nMode ) + :Control( pParent, nBits | WB_3DLOOK ) + ,DragSourceHelper( this ) + ,DropTargetHelper( this ) + ,aHScroll( VclPtr<ScrollBar>::Create(this, WB_HSCROLL) ) + ,aStatusBar( VclPtr<StatusBar>::Create(this) ) +{ + ConstructImpl( nMode ); +} + +BrowseBox::~BrowseBox() +{ + disposeOnce(); +} + +void BrowseBox::dispose() +{ + SAL_INFO("svtools", "BrowseBox:dispose " << this ); + + if ( m_pImpl->m_pAccessible ) + { + disposeAndClearHeaderCell(m_pImpl->m_aColHeaderCellMap); + disposeAndClearHeaderCell(m_pImpl->m_aRowHeaderCellMap); + m_pImpl->m_pAccessible->dispose(); + } + + Hide(); + pDataWin->pHeaderBar.disposeAndClear(); + pDataWin->pCornerWin.disposeAndClear(); + pDataWin.disposeAndClear(); + pVScroll.disposeAndClear(); + aHScroll.disposeAndClear(); + aStatusBar.disposeAndClear(); + + // free columns-space + mvCols.clear(); + pColSel.reset(); + if ( bMultiSelection ) + delete uRow.pSel; + DragSourceHelper::dispose(); + DropTargetHelper::dispose(); + Control::dispose(); +} + + +short BrowseBox::GetCursorHideCount() const +{ + return pDataWin->nCursorHidden; +} + + +void BrowseBox::DoShowCursor( const char * ) +{ + if (!pDataWin) + return; + short nHiddenCount = --pDataWin->nCursorHidden; + if (PaintCursorIfHiddenOnce()) + { + if (1 == nHiddenCount) + DrawCursor(); + } + else + { + if (0 == nHiddenCount) + DrawCursor(); + } +} + + +void BrowseBox::DoHideCursor( const char * ) +{ + short nHiddenCount = ++pDataWin->nCursorHidden; + if (PaintCursorIfHiddenOnce()) + { + if (2 == nHiddenCount) + DrawCursor(); + } + else + { + if (1 == nHiddenCount) + DrawCursor(); + } +} + + +void BrowseBox::SetRealRowCount( const OUString &rRealRowCount ) +{ + pDataWin->aRealRowCount = rRealRowCount; +} + + +void BrowseBox::SetFont( const vcl::Font& rNewFont ) +{ + pDataWin->SetFont( rNewFont ); + ImpGetDataRowHeight(); +} + +const vcl::Font& BrowseBox::GetFont() const +{ + return pDataWin->GetFont(); +} + +sal_uLong BrowseBox::GetDefaultColumnWidth( const OUString& _rText ) const +{ + return pDataWin->GetTextWidth( _rText ) + pDataWin->GetTextWidth(OUString('0')) * 4; +} + + +void BrowseBox::InsertHandleColumn( sal_uLong nWidth ) +{ + +#if OSL_DEBUG_LEVEL > 0 + OSL_ENSURE( ColCount() == 0 || mvCols[0]->GetId() != HandleColumnId , "BrowseBox::InsertHandleColumn: there is already a handle column" ); + { + for (auto const & col : mvCols) + OSL_ENSURE( col->GetId() != HandleColumnId, "BrowseBox::InsertHandleColumn: there is a non-Handle column with handle ID" ); + } +#endif + + mvCols.insert( mvCols.begin(), std::unique_ptr<BrowserColumn>(new BrowserColumn( 0, OUString(), nWidth, GetZoom() )) ); + FreezeColumn( 0 ); + + // adjust headerbar + if ( pDataWin->pHeaderBar ) + { + pDataWin->pHeaderBar->SetPosSizePixel( + Point(nWidth, 0), + Size( GetOutputSizePixel().Width() - nWidth, GetTitleHeight() ) + ); + } + + ColumnInserted( 0 ); +} + + +void BrowseBox::InsertDataColumn( sal_uInt16 nItemId, const OUString& rText, + long nWidth, HeaderBarItemBits nBits, sal_uInt16 nPos ) +{ + + OSL_ENSURE( nItemId != HandleColumnId, "BrowseBox::InsertDataColumn: nItemId is HandleColumnId" ); + OSL_ENSURE( nItemId != BROWSER_INVALIDID, "BrowseBox::InsertDataColumn: nItemId is reserved value BROWSER_INVALIDID" ); + +#if OSL_DEBUG_LEVEL > 0 + { + for (auto const& col : mvCols) + OSL_ENSURE( col->GetId() != nItemId, "BrowseBox::InsertDataColumn: duplicate column Id" ); + } +#endif + + if ( nPos < mvCols.size() ) + { + mvCols.emplace( mvCols.begin() + nPos, new BrowserColumn( nItemId, rText, nWidth, GetZoom() ) ); + } + else + { + mvCols.emplace_back( new BrowserColumn( nItemId, rText, nWidth, GetZoom() ) ); + } + if ( nCurColId == 0 ) + nCurColId = nItemId; + + if ( pDataWin->pHeaderBar ) + { + // Handle column not in the header bar + sal_uInt16 nHeaderPos = nPos; + if (nHeaderPos != HEADERBAR_APPEND && GetColumnId(0) == HandleColumnId ) + nHeaderPos--; + pDataWin->pHeaderBar->InsertItem( + nItemId, rText, nWidth, nBits, nHeaderPos ); + } + ColumnInserted( nPos ); +} + +sal_uInt16 BrowseBox::ToggleSelectedColumn() +{ + sal_uInt16 nSelectedColId = BROWSER_INVALIDID; + if ( pColSel && pColSel->GetSelectCount() ) + { + DoHideCursor( "ToggleSelectedColumn" ); + ToggleSelection(); + long nSelected = pColSel->FirstSelected(); + if (nSelected != static_cast<long>(SFX_ENDOFSELECTION)) + nSelectedColId = mvCols[nSelected]->GetId(); + pColSel->SelectAll(false); + } + return nSelectedColId; +} + +void BrowseBox::SetToggledSelectedColumn(sal_uInt16 _nSelectedColumnId) +{ + if ( pColSel && _nSelectedColumnId != BROWSER_INVALIDID ) + { + pColSel->Select( GetColumnPos( _nSelectedColumnId ) ); + ToggleSelection(); + SAL_INFO("svtools", "BrowseBox::SetToggledSelectedColumn " << this ); + DoShowCursor( "SetToggledSelectedColumn" ); + } +} + +void BrowseBox::FreezeColumn( sal_uInt16 nItemId ) +{ + // get the position in the current array + size_t nItemPos = GetColumnPos( nItemId ); + if ( nItemPos >= mvCols.size() ) + // not available! + return; + + // doesn't the state change? + if ( mvCols[ nItemPos ]->IsFrozen() ) + return; + + // remark the column selection + sal_uInt16 nSelectedColId = ToggleSelectedColumn(); + + // to be moved? + if ( nItemPos != 0 && !mvCols[ nItemPos-1 ]->IsFrozen() ) + { + // move to the right of the last frozen column + sal_uInt16 nFirstScrollable = FrozenColCount(); + std::unique_ptr<BrowserColumn> pColumn = std::move(mvCols[ nItemPos ]); + mvCols.erase( mvCols.begin() + nItemPos ); + nItemPos = nFirstScrollable; + mvCols.insert( mvCols.begin() + nItemPos, std::move(pColumn) ); + } + + // adjust the number of the first scrollable and visible column + if ( nFirstCol <= nItemPos ) + nFirstCol = nItemPos + 1; + + // toggle the freeze-state of the column + mvCols[ nItemPos ]->Freeze(); + + // align the scrollbar-range + UpdateScrollbars(); + + // repaint + Control::Invalidate(); + pDataWin->Invalidate(); + + // remember the column selection + SetToggledSelectedColumn(nSelectedColId); +} + + +void BrowseBox::SetColumnPos( sal_uInt16 nColumnId, sal_uInt16 nPos ) +{ + // never set pos of the handle column + if ( nColumnId == HandleColumnId ) + return; + + // get the position in the current array + sal_uInt16 nOldPos = GetColumnPos( nColumnId ); + if ( nOldPos >= mvCols.size() ) + // not available! + return; + + // does the state change? + if (nOldPos == nPos) + return; + + // remark the column selection + sal_uInt16 nSelectedColId = ToggleSelectedColumn(); + + // determine old column area + Size aDataWinSize( pDataWin->GetSizePixel() ); + if ( pDataWin->pHeaderBar ) + aDataWinSize.AdjustHeight(pDataWin->pHeaderBar->GetSizePixel().Height() ); + + tools::Rectangle aFromRect( GetFieldRect( nColumnId) ); + aFromRect.AdjustRight(2*MIN_COLUMNWIDTH ); + + sal_uInt16 nNextPos = nOldPos + 1; + if ( nOldPos > nPos ) + nNextPos = nOldPos - 1; + + BrowserColumn *pNextCol = mvCols[ nNextPos ].get(); + tools::Rectangle aNextRect(GetFieldRect( pNextCol->GetId() )); + + // move column internally + { + std::unique_ptr<BrowserColumn> pTemp = std::move(mvCols[nOldPos]); + mvCols.erase( mvCols.begin() + nOldPos ); + mvCols.insert( mvCols.begin() + nPos, std::move(pTemp) ); + } + + // determine new column area + tools::Rectangle aToRect( GetFieldRect( nColumnId ) ); + aToRect.AdjustRight(2*MIN_COLUMNWIDTH ); + + // do scroll, let redraw + if( pDataWin->GetBackground().IsScrollable() ) + { + long nScroll = -aFromRect.GetWidth(); + tools::Rectangle aScrollArea; + if ( nOldPos > nPos ) + { + long nFrozenWidth = GetFrozenWidth(); + if ( aToRect.Left() < nFrozenWidth ) + aToRect.SetLeft( nFrozenWidth ); + aScrollArea = tools::Rectangle(Point(aToRect.Left(),0), + Point(aNextRect.Right(),aDataWinSize.Height())); + nScroll *= -1; // reverse direction + } + else + aScrollArea = tools::Rectangle(Point(aNextRect.Left(),0), + Point(aToRect.Right(),aDataWinSize.Height())); + + pDataWin->Scroll( nScroll, 0, aScrollArea ); + aToRect.SetTop( 0 ); + aToRect.SetBottom( aScrollArea.Bottom() ); + Invalidate( aToRect ); + } + else + pDataWin->Window::Invalidate( InvalidateFlags::NoChildren ); + + // adjust header bar positions + if ( pDataWin->pHeaderBar ) + { + sal_uInt16 nNewPos = nPos; + if ( GetColumnId(0) == HandleColumnId ) + --nNewPos; + pDataWin->pHeaderBar->MoveItem(nColumnId,nNewPos); + } + // remember the column selection + SetToggledSelectedColumn(nSelectedColId); + + if ( !isAccessibleAlive() ) + return; + + commitTableEvent( + TABLE_MODEL_CHANGED, + makeAny( AccessibleTableModelChange( + DELETE, + 0, + GetRowCount(), + nOldPos, + nOldPos + ) + ), + Any() + ); + + commitTableEvent( + TABLE_MODEL_CHANGED, + makeAny( AccessibleTableModelChange( + INSERT, + 0, + GetRowCount(), + nPos, + nPos + ) + ), + Any() + ); + +} + + +void BrowseBox::SetColumnTitle( sal_uInt16 nItemId, const OUString& rTitle ) +{ + + // never set title of the handle-column + if ( nItemId == HandleColumnId ) + return; + + // get the position in the current array + sal_uInt16 nItemPos = GetColumnPos( nItemId ); + if ( nItemPos >= mvCols.size() ) + // not available! + return; + + // does the state change? + BrowserColumn *pCol = mvCols[ nItemPos ].get(); + if ( pCol->Title() == rTitle ) + return; + + OUString sOld(pCol->Title()); + + pCol->Title() = rTitle; + + // adjust headerbar column + if ( pDataWin->pHeaderBar ) + pDataWin->pHeaderBar->SetItemText( nItemId, rTitle ); + else + { + // redraw visible columns + if ( GetUpdateMode() && ( pCol->IsFrozen() || nItemPos > nFirstCol ) ) + Invalidate( tools::Rectangle( Point(0,0), + Size( GetOutputSizePixel().Width(), GetTitleHeight() ) ) ); + } + + if ( isAccessibleAlive() ) + { + commitTableEvent( TABLE_COLUMN_DESCRIPTION_CHANGED, + makeAny( rTitle ), + makeAny( sOld ) + ); + } +} + + +void BrowseBox::SetColumnWidth( sal_uInt16 nItemId, sal_uLong nWidth ) +{ + + // get the position in the current array + size_t nItemPos = GetColumnPos( nItemId ); + if ( nItemPos >= mvCols.size() ) + return; + + // does the state change? + if ( !(nWidth >= LONG_MAX || mvCols[ nItemPos ]->Width() != nWidth) ) + return; + + long nOldWidth = mvCols[ nItemPos ]->Width(); + + // adjust last column, if necessary + if ( IsVisible() && nItemPos == mvCols.size() - 1 ) + { + long nMaxWidth = pDataWin->GetSizePixel().Width(); + nMaxWidth -= pDataWin->bAutoSizeLastCol + ? GetFieldRect(nItemId).Left() + : GetFrozenWidth(); + if ( pDataWin->bAutoSizeLastCol || nWidth > o3tl::make_unsigned(nMaxWidth) ) + { + nWidth = nMaxWidth > 16 ? nMaxWidth : nOldWidth; + } + } + + // OV + // In AutoSizeLastColumn(), we call SetColumnWidth with nWidth==0xffff. + // Thus, check here, if the width has actually changed. + if( static_cast<sal_uLong>(nOldWidth) == nWidth ) + return; + + // do we want to display the change immediately? + bool bUpdate = GetUpdateMode() && + ( mvCols[ nItemPos ]->IsFrozen() || nItemPos >= nFirstCol ); + + if ( bUpdate ) + { + // Selection hidden + DoHideCursor( "SetColumnWidth" ); + ToggleSelection(); + //!pDataWin->Update(); + //!Control::Update(); + } + + // set width + mvCols[ nItemPos ]->SetWidth(nWidth, GetZoom()); + + // scroll and invalidate + if ( bUpdate ) + { + // get X-Pos of the column changed + long nX = 0; + for ( size_t nCol = 0; nCol < nItemPos; ++nCol ) + { + BrowserColumn *pCol = mvCols[ nCol ].get(); + if ( pCol->IsFrozen() || nCol >= nFirstCol ) + nX += pCol->Width(); + } + + // actually scroll+invalidate + pDataWin->SetClipRegion(); + bool bSelVis = bSelectionIsVisible; + bSelectionIsVisible = false; + if( GetBackground().IsScrollable() ) + { + + tools::Rectangle aScrRect( nX + std::min( static_cast<sal_uLong>(nOldWidth), nWidth ), 0, + GetSizePixel().Width() , // the header is longer than the datawin + pDataWin->GetPosPixel().Y() - 1 ); + Control::Scroll( nWidth-nOldWidth, 0, aScrRect, SCROLL_FLAGS ); + aScrRect.SetBottom( pDataWin->GetSizePixel().Height() ); + pDataWin->Scroll( nWidth-nOldWidth, 0, aScrRect, SCROLL_FLAGS ); + tools::Rectangle aInvRect( nX, 0, nX + std::max( nWidth, static_cast<sal_uLong>(nOldWidth) ), USHRT_MAX ); + Control::Invalidate( aInvRect, InvalidateFlags::NoChildren ); + pDataWin->Invalidate( aInvRect ); + } + else + { + Control::Invalidate( InvalidateFlags::NoChildren ); + pDataWin->Window::Invalidate( InvalidateFlags::NoChildren ); + } + + + //!pDataWin->Update(); + //!Control::Update(); + bSelectionIsVisible = bSelVis; + ToggleSelection(); + DoShowCursor( "SetColumnWidth" ); + } + UpdateScrollbars(); + + // adjust headerbar column + if ( pDataWin->pHeaderBar ) + pDataWin->pHeaderBar->SetItemSize( + nItemId ? nItemId : USHRT_MAX - 1, nWidth ); + + // adjust last column + if ( nItemPos != mvCols.size() - 1 ) + AutoSizeLastColumn(); +} + + +void BrowseBox::AutoSizeLastColumn() +{ + if ( pDataWin->bAutoSizeLastCol && + pDataWin->GetUpdateMode() ) + { + sal_uInt16 nId = GetColumnId( static_cast<sal_uInt16>(mvCols.size()) - 1 ); + SetColumnWidth( nId, LONG_MAX ); + ColumnResized( nId ); + } +} + + +void BrowseBox::RemoveColumn( sal_uInt16 nItemId ) +{ + + // get column position + sal_uInt16 nPos = GetColumnPos(nItemId); + if ( nPos >= ColCount() ) + // not available + return; + + // correct column selection + if ( pColSel ) + pColSel->Remove( nPos ); + + // correct column cursor + if ( nCurColId == nItemId ) + nCurColId = 0; + + // delete column + mvCols.erase( mvCols.begin() + nPos ); + if ( nFirstCol >= nPos && nFirstCol > FrozenColCount() ) + { + OSL_ENSURE(nFirstCol > 0,"FirstCol must be greater zero!"); + --nFirstCol; + } + + // handlecolumn not in headerbar + if (nItemId) + { + if ( pDataWin->pHeaderBar ) + pDataWin->pHeaderBar->RemoveItem( nItemId ); + } + else + { + // adjust headerbar + if ( pDataWin->pHeaderBar ) + { + pDataWin->pHeaderBar->SetPosSizePixel( + Point(0, 0), + Size( GetOutputSizePixel().Width(), GetTitleHeight() ) + ); + } + } + + // correct vertical scrollbar + UpdateScrollbars(); + + // trigger repaint, if necessary + if ( GetUpdateMode() ) + { + pDataWin->Invalidate(); + Control::Invalidate(); + if ( pDataWin->bAutoSizeLastCol && nPos ==ColCount() ) + SetColumnWidth( GetColumnId( nPos - 1 ), LONG_MAX ); + } + + if ( !isAccessibleAlive() ) + return; + + commitTableEvent( + TABLE_MODEL_CHANGED, + makeAny( AccessibleTableModelChange( DELETE, + 0, + GetRowCount(), + nPos, + nPos + ) + ), + Any() + ); + + commitHeaderBarEvent( + CHILD, + Any(), + makeAny( CreateAccessibleColumnHeader( nPos ) ), + true + ); +} + + +void BrowseBox::RemoveColumns() +{ + size_t nOldCount = mvCols.size(); + + // remove all columns + mvCols.clear(); + + // correct column selection + if ( pColSel ) + { + pColSel->SelectAll(false); + pColSel->SetTotalRange( Range( 0, 0 ) ); + } + + // correct column cursor + nCurColId = 0; + nFirstCol = 0; + + if ( pDataWin->pHeaderBar ) + pDataWin->pHeaderBar->Clear( ); + + // correct vertical scrollbar + UpdateScrollbars(); + + // trigger repaint if necessary + if ( GetUpdateMode() ) + { + pDataWin->Invalidate(); + Control::Invalidate(); + } + + if ( !isAccessibleAlive() ) + return; + + if ( mvCols.size() == nOldCount ) + return; + + // all columns should be removed, so we remove the column header bar and append it again + // to avoid to notify every column remove + commitBrowseBoxEvent( + CHILD, + Any(), + makeAny(m_pImpl->getAccessibleHeaderBar(vcl::BBTYPE_COLUMNHEADERBAR)) + ); + + // and now append it again + commitBrowseBoxEvent( + CHILD, + makeAny(m_pImpl->getAccessibleHeaderBar(vcl::BBTYPE_COLUMNHEADERBAR)), + Any() + ); + + // notify a table model change + commitTableEvent( + TABLE_MODEL_CHANGED, + makeAny ( AccessibleTableModelChange( DELETE, + 0, + GetRowCount(), + 0, + nOldCount + ) + ), + Any() + ); +} + + +OUString BrowseBox::GetColumnTitle( sal_uInt16 nId ) const +{ + + sal_uInt16 nItemPos = GetColumnPos( nId ); + if ( nItemPos >= mvCols.size() ) + return OUString(); + return mvCols[ nItemPos ]->Title(); +} + + +long BrowseBox::GetRowCount() const +{ + return nRowCount; +} + + +sal_uInt16 BrowseBox::ColCount() const +{ + + return static_cast<sal_uInt16>(mvCols.size()); +} + + +long BrowseBox::ImpGetDataRowHeight() const +{ + + BrowseBox *pThis = const_cast<BrowseBox*>(this); + pThis->nDataRowHeight = pThis->CalcReverseZoom(pDataWin->GetTextHeight() + 2); + pThis->Resize(); + pDataWin->Invalidate(); + return nDataRowHeight; +} + + +void BrowseBox::SetDataRowHeight( long nPixel ) +{ + + nDataRowHeight = CalcReverseZoom(nPixel); + Resize(); + pDataWin->Invalidate(); +} + + +void BrowseBox::SetTitleLines( sal_uInt16 nLines ) +{ + + nTitleLines = nLines; +} + + +long BrowseBox::ScrollColumns( long nCols ) +{ + + if ( nFirstCol + nCols < 0 || + nFirstCol + nCols >= static_cast<long>(mvCols.size()) ) + return 0; + + // implicitly hides cursor while scrolling + StartScroll(); + bScrolling = true; + bool bScrollable = pDataWin->GetBackground().IsScrollable(); + bool bInvalidateView = false; + + // scrolling one column to the right? + if ( nCols == 1 ) + { + // update internal value and scrollbar + ++nFirstCol; + aHScroll->SetThumbPos( nFirstCol - FrozenColCount() ); + + if ( !bScrollable ) + { + bInvalidateView = true; + } + else + { + long nDelta = mvCols[ nFirstCol-1 ]->Width(); + long nFrozenWidth = GetFrozenWidth(); + + tools::Rectangle aScrollRect( Point( nFrozenWidth + nDelta, 0 ), + Size ( GetOutputSizePixel().Width() - nFrozenWidth - nDelta, + GetTitleHeight() - 1 + ) ); + + // scroll the header bar area (if there is no dedicated HeaderBar control) + if ( !pDataWin->pHeaderBar && nTitleLines ) + { + // actually scroll + Scroll( -nDelta, 0, aScrollRect, SCROLL_FLAGS ); + + // invalidate the area of the column which was scrolled out to the left hand side + tools::Rectangle aInvalidateRect( aScrollRect ); + aInvalidateRect.SetLeft( nFrozenWidth ); + aInvalidateRect.SetRight( nFrozenWidth + nDelta - 1 ); + Invalidate( aInvalidateRect ); + } + + // scroll the data-area + aScrollRect.SetBottom( pDataWin->GetOutputSizePixel().Height() ); + + // actually scroll + pDataWin->Scroll( -nDelta, 0, aScrollRect, SCROLL_FLAGS ); + + // invalidate the area of the column which was scrolled out to the left hand side + aScrollRect.SetLeft( nFrozenWidth ); + aScrollRect.SetRight( nFrozenWidth + nDelta - 1 ); + pDataWin->Invalidate( aScrollRect ); + } + } + + // scrolling one column to the left? + else if ( nCols == -1 ) + { + --nFirstCol; + aHScroll->SetThumbPos( nFirstCol - FrozenColCount() ); + + if ( !bScrollable ) + { + bInvalidateView = true; + } + else + { + long nDelta = mvCols[ nFirstCol ]->Width(); + long nFrozenWidth = GetFrozenWidth(); + + tools::Rectangle aScrollRect( Point( nFrozenWidth, 0 ), + Size ( GetOutputSizePixel().Width() - nFrozenWidth, + GetTitleHeight() - 1 + ) ); + + // scroll the header bar area (if there is no dedicated HeaderBar control) + if ( !pDataWin->pHeaderBar && nTitleLines ) + { + Scroll( nDelta, 0, aScrollRect, SCROLL_FLAGS ); + } + + // scroll the data-area + aScrollRect.SetBottom( pDataWin->GetOutputSizePixel().Height() ); + pDataWin->Scroll( nDelta, 0, aScrollRect, SCROLL_FLAGS ); + } + } + else + { + if ( GetUpdateMode() ) + { + Invalidate( tools::Rectangle( + Point( GetFrozenWidth(), 0 ), + Size( GetOutputSizePixel().Width(), GetTitleHeight() ) ) ); + pDataWin->Invalidate( tools::Rectangle( + Point( GetFrozenWidth(), 0 ), + pDataWin->GetSizePixel() ) ); + } + + nFirstCol = nFirstCol + static_cast<sal_uInt16>(nCols); + aHScroll->SetThumbPos( nFirstCol - FrozenColCount() ); + } + + // adjust external headerbar, if necessary + if ( pDataWin->pHeaderBar ) + { + long nWidth = 0; + for ( size_t nCol = 0; + nCol < mvCols.size() && nCol < nFirstCol; + ++nCol ) + { + // not the handle column + if ( mvCols[ nCol ]->GetId() ) + nWidth += mvCols[ nCol ]->Width(); + } + + pDataWin->pHeaderBar->SetOffset( nWidth ); + } + + if( bInvalidateView ) + { + Control::Invalidate( InvalidateFlags::NoChildren ); + pDataWin->Window::Invalidate( InvalidateFlags::NoChildren ); + } + + // implicitly show cursor after scrolling + if ( nCols ) + { + pDataWin->Update(); + PaintImmediately(); + } + bScrolling = false; + EndScroll(); + + return nCols; +} + + +long BrowseBox::ScrollRows( long nRows ) +{ + // compute new top row + long nTmpMin = std::min( static_cast<long>(nTopRow + nRows), static_cast<long>(nRowCount - 1) ); + + long nNewTopRow = std::max<long>( nTmpMin, 0 ); + + if ( nNewTopRow == nTopRow ) + return 0; + + sal_uInt16 nVisibleRows = + static_cast<sal_uInt16>(pDataWin->GetOutputSizePixel().Height() / GetDataRowHeight() + 1); + + VisibleRowsChanged(nNewTopRow, nVisibleRows); + + // compute new top row again (nTopRow might have changed!) + nTmpMin = std::min( static_cast<long>(nTopRow + nRows), static_cast<long>(nRowCount - 1) ); + + nNewTopRow = std::max<long>( nTmpMin, 0 ); + + StartScroll(); + + // scroll area on screen and/or repaint + long nDeltaY = GetDataRowHeight() * ( nNewTopRow - nTopRow ); + long nOldTopRow = nTopRow; + nTopRow = nNewTopRow; + + if ( GetUpdateMode() ) + { + pVScroll->SetRange( Range( 0L, nRowCount ) ); + pVScroll->SetThumbPos( nTopRow ); + + if( pDataWin->GetBackground().IsScrollable() && + std::abs( nDeltaY ) > 0 && + std::abs( nDeltaY ) < pDataWin->GetSizePixel().Height() ) + { + pDataWin->Scroll( 0, static_cast<short>(-nDeltaY), SCROLL_FLAGS ); + } + else + pDataWin->Invalidate(); + + if ( nTopRow - nOldTopRow ) + pDataWin->Update(); + } + + EndScroll(); + + return nTopRow - nOldTopRow; +} + + +void BrowseBox::RowModified( long nRow, sal_uInt16 nColId ) +{ + + if ( !GetUpdateMode() ) + return; + + tools::Rectangle aRect; + if ( nColId == BROWSER_INVALIDID ) + // invalidate the whole row + aRect = tools::Rectangle( Point( 0, (nRow-nTopRow) * GetDataRowHeight() ), + Size( pDataWin->GetSizePixel().Width(), GetDataRowHeight() ) ); + else + { + // invalidate the specific field + aRect = GetFieldRectPixel( nRow, nColId, false ); + } + pDataWin->Invalidate( aRect ); +} + + +void BrowseBox::Clear() +{ + + // adjust the total number of rows + DoHideCursor( "Clear" ); + long nOldRowCount = nRowCount; + nRowCount = 0; + if(bMultiSelection) + { + assert(uRow.pSel); + uRow.pSel->Reset(); + } + else + uRow.nSel = BROWSER_ENDOFSELECTION; + nCurRow = BROWSER_ENDOFSELECTION; + nTopRow = 0; + nCurColId = 0; + + // nFirstCol may not be reset, else the scrolling code will become confused. + // nFirstCol may only be changed when adding or deleting columns + // nFirstCol = 0; -> wrong! + aHScroll->SetThumbPos( 0 ); + pVScroll->SetThumbPos( 0 ); + + Invalidate(); + UpdateScrollbars(); + SetNoSelection(); + DoShowCursor( "Clear" ); + CursorMoved(); + + if ( !isAccessibleAlive() ) + return; + + // all rows should be removed, so we remove the row header bar and append it again + // to avoid to notify every row remove + if ( nOldRowCount == nRowCount ) + return; + + commitBrowseBoxEvent( + CHILD, + Any(), + makeAny( m_pImpl->getAccessibleHeaderBar( vcl::BBTYPE_ROWHEADERBAR ) ) + ); + + // and now append it again + commitBrowseBoxEvent( + CHILD, + makeAny( m_pImpl->getAccessibleHeaderBar( vcl::BBTYPE_ROWHEADERBAR ) ), + Any() + ); + + // notify a table model change + commitTableEvent( + TABLE_MODEL_CHANGED, + makeAny( AccessibleTableModelChange( DELETE, + 0, + nOldRowCount, + 0, + GetColumnCount()) + ), + Any() + ); +} + +void BrowseBox::RowInserted( long nRow, long nNumRows, bool bDoPaint, bool bKeepSelection ) +{ + + if (nRow < 0) + nRow = 0; + else if (nRow > nRowCount) // maximal = nRowCount + nRow = nRowCount; + + if ( nNumRows <= 0 ) + return; + + // adjust total row count + bool bLastRow = nRow >= nRowCount; + nRowCount += nNumRows; + + DoHideCursor( "RowInserted" ); + + // must we paint the new rows? + long nOldCurRow = nCurRow; + Size aSz = pDataWin->GetOutputSizePixel(); + if ( bDoPaint && nRow >= nTopRow && + nRow <= nTopRow + aSz.Height() / GetDataRowHeight() ) + { + long nY = (nRow-nTopRow) * GetDataRowHeight(); + if ( !bLastRow ) + { + // scroll down the rows behind the new row + pDataWin->SetClipRegion(); + if( pDataWin->GetBackground().IsScrollable() ) + { + pDataWin->Scroll( 0, GetDataRowHeight() * nNumRows, + tools::Rectangle( Point( 0, nY ), + Size( aSz.Width(), aSz.Height() - nY ) ), + SCROLL_FLAGS ); + } + else + pDataWin->Window::Invalidate( InvalidateFlags::NoChildren ); + } + else + // scroll would cause a repaint, so we must explicitly invalidate + pDataWin->Invalidate( tools::Rectangle( Point( 0, nY ), + Size( aSz.Width(), nNumRows * GetDataRowHeight() ) ) ); + } + + // correct top row if necessary + if ( nRow < nTopRow ) + nTopRow += nNumRows; + + // adjust the selection + if ( bMultiSelection ) + uRow.pSel->Insert( nRow, nNumRows ); + else if ( uRow.nSel != BROWSER_ENDOFSELECTION && nRow <= uRow.nSel ) + uRow.nSel += nNumRows; + + // adjust the cursor + if ( nCurRow == BROWSER_ENDOFSELECTION ) + GoToRow( 0, false, bKeepSelection ); + else if ( nRow <= nCurRow ) + { + nCurRow += nNumRows; + GoToRow( nCurRow, false, bKeepSelection ); + } + + // adjust the vertical scrollbar + if ( bDoPaint ) + { + UpdateScrollbars(); + AutoSizeLastColumn(); + } + + DoShowCursor( "RowInserted" ); + // notify accessible that rows were inserted + if ( isAccessibleAlive() ) + { + commitTableEvent( + TABLE_MODEL_CHANGED, + makeAny( AccessibleTableModelChange( + INSERT, + nRow, + nRow + nNumRows, + 0, + GetColumnCount() + ) + ), + Any() + ); + + for (long i = nRow+1 ; i <= nRowCount ; ++i) + { + commitHeaderBarEvent( + CHILD, + makeAny( CreateAccessibleRowHeader( i ) ), + Any(), + false + ); + } + } + + if ( nCurRow != nOldCurRow ) + CursorMoved(); + + DBG_ASSERT(nRowCount > 0,"BrowseBox: nRowCount <= 0"); + DBG_ASSERT(nCurRow >= 0,"BrowseBox: nCurRow < 0"); + DBG_ASSERT(nCurRow < nRowCount,"nCurRow >= nRowCount"); +} + + +void BrowseBox::RowRemoved( long nRow, long nNumRows, bool bDoPaint ) +{ + + if ( nRow < 0 ) + nRow = 0; + else if ( nRow >= nRowCount ) + nRow = nRowCount - 1; + + if ( nNumRows <= 0 ) + return; + + if ( nRowCount <= 0 ) + return; + + if ( bDoPaint ) + { + // hide cursor and selection + SAL_INFO("svtools", "BrowseBox::HideCursor " << this ); + ToggleSelection(); + DoHideCursor( "RowRemoved" ); + } + + // adjust total row count + nRowCount -= nNumRows; + if (nRowCount < 0) nRowCount = 0; + long nOldCurRow = nCurRow; + + // adjust the selection + if ( bMultiSelection ) + // uRow.pSel->Remove( nRow, nNumRows ); + for ( long i = 0; i < nNumRows; i++ ) + uRow.pSel->Remove( nRow ); + else if ( nRow < uRow.nSel && uRow.nSel >= nNumRows ) + uRow.nSel -= nNumRows; + else if ( nRow <= uRow.nSel ) + uRow.nSel = BROWSER_ENDOFSELECTION; + + // adjust the cursor + if ( nRowCount == 0 ) // don't compare nRowCount with nNumRows as nNumRows already was subtracted from nRowCount + nCurRow = BROWSER_ENDOFSELECTION; + else if ( nRow < nCurRow ) + { + nCurRow -= std::min( nCurRow - nRow, nNumRows ); + // with the above nCurRow points a) to the first row after the removed block or b) to the same line + // as before, but moved up nNumRows + // case a) needs an additional correction if the last n lines were deleted, as 'the first row after the + // removed block' is an invalid position then + // FS - 09/28/99 - 68429 + if (nCurRow == nRowCount) + --nCurRow; + } + else if( nRow == nCurRow && nCurRow == nRowCount ) + nCurRow = nRowCount-1; + + // is the deleted row visible? + Size aSz = pDataWin->GetOutputSizePixel(); + if ( nRow >= nTopRow && + nRow <= nTopRow + aSz.Height() / GetDataRowHeight() ) + { + if ( bDoPaint ) + { + // scroll up the rows behind the deleted row + // if there are Rows behind + if (nRow < nRowCount) + { + long nY = (nRow-nTopRow) * GetDataRowHeight(); + pDataWin->SetClipRegion(); + if( pDataWin->GetBackground().IsScrollable() ) + { + pDataWin->Scroll( 0, - static_cast<short>(GetDataRowHeight()) * nNumRows, + tools::Rectangle( Point( 0, nY ), Size( aSz.Width(), + aSz.Height() - nY + nNumRows*GetDataRowHeight() ) ), + SCROLL_FLAGS ); + } + else + pDataWin->Window::Invalidate( InvalidateFlags::NoChildren ); + } + else + { + // Repaint the Rect of the deleted row + tools::Rectangle aRect( + Point( 0, (nRow-nTopRow)*GetDataRowHeight() ), + Size( pDataWin->GetSizePixel().Width(), + nNumRows * GetDataRowHeight() ) ); + pDataWin->Invalidate( aRect ); + } + } + } + // is the deleted row above of the visible area? + else if ( nRow < nTopRow ) + nTopRow = nTopRow >= nNumRows ? nTopRow-nNumRows : 0; + + if ( bDoPaint ) + { + // reshow cursor and selection + ToggleSelection(); + SAL_INFO("svtools", "BrowseBox::ShowCursor " << this ); + DoShowCursor( "RowRemoved" ); + + // adjust the vertical scrollbar + UpdateScrollbars(); + AutoSizeLastColumn(); + } + + if ( isAccessibleAlive() ) + { + if ( nRowCount == 0 ) + { + // all columns should be removed, so we remove the column header bar and append it again + // to avoid to notify every column remove + commitBrowseBoxEvent( + CHILD, + Any(), + makeAny( m_pImpl->getAccessibleHeaderBar( vcl::BBTYPE_ROWHEADERBAR ) ) + ); + + // and now append it again + commitBrowseBoxEvent( + CHILD, + makeAny(m_pImpl->getAccessibleHeaderBar(vcl::BBTYPE_ROWHEADERBAR)), + Any() + ); + commitBrowseBoxEvent( + CHILD, + Any(), + makeAny( m_pImpl->getAccessibleTable() ) + ); + + // and now append it again + commitBrowseBoxEvent( + CHILD, + makeAny( m_pImpl->getAccessibleTable() ), + Any() + ); + } + else + { + commitTableEvent( + TABLE_MODEL_CHANGED, + makeAny( AccessibleTableModelChange( + DELETE, + nRow, + nRow + nNumRows, + 0, + GetColumnCount() + ) + ), + Any() + ); + + for (long i = nRow+1 ; i <= (nRow+nNumRows) ; ++i) + { + commitHeaderBarEvent( + CHILD, + Any(), + makeAny( CreateAccessibleRowHeader( i ) ), + false + ); + } + } + } + + if ( nOldCurRow != nCurRow ) + CursorMoved(); + + DBG_ASSERT(nRowCount >= 0,"BrowseBox: nRowCount < 0"); + DBG_ASSERT(nCurRow >= 0 || nRowCount == 0,"BrowseBox: nCurRow < 0 && nRowCount != 0"); + DBG_ASSERT(nCurRow < nRowCount,"nCurRow >= nRowCount"); +} + + +bool BrowseBox::GoToRow( long nRow) +{ + return GoToRow(nRow, false); +} + + +bool BrowseBox::GoToRow( long nRow, bool bRowColMove, bool bKeepSelection ) +{ + + long nOldCurRow = nCurRow; + + // nothing to do? + if ( nRow == nCurRow && ( bMultiSelection || uRow.nSel == nRow ) ) + return true; + + // out of range? + if ( nRow < 0 || nRow >= nRowCount ) + return false; + + // not allowed? + if ( !bRowColMove && !IsCursorMoveAllowed( nRow, nCurColId ) ) + return false; + + // compute the last visible row + Size aSz( pDataWin->GetSizePixel() ); + sal_uInt16 nVisibleRows = sal_uInt16( aSz.Height() / GetDataRowHeight() - 1 ); + long nLastRow = nTopRow + nVisibleRows; + + // suspend Updates + pDataWin->EnterUpdateLock(); + + // remove old highlight, if necessary + if ( !bMultiSelection && !bKeepSelection ) + ToggleSelection(); + DoHideCursor( "GoToRow" ); + + // must we scroll? + bool bWasVisible = bSelectionIsVisible; + if (! bMultiSelection) + { + if( !bKeepSelection ) + bSelectionIsVisible = false; + } + if ( nRow < nTopRow ) + ScrollRows( nRow - nTopRow ); + else if ( nRow > nLastRow ) + ScrollRows( nRow - nLastRow ); + bSelectionIsVisible = bWasVisible; + + // adjust cursor (selection) and thumb + if ( GetUpdateMode() ) + pVScroll->SetThumbPos( nTopRow ); + + // relative positioning (because nCurRow might have changed in the meantime)! + if (nCurRow != BROWSER_ENDOFSELECTION ) + nCurRow = nCurRow + (nRow - nOldCurRow); + + // make sure that the current position is valid + if (nCurRow == BROWSER_ENDOFSELECTION && nRowCount > 0) + nCurRow = 0; + else if ( nCurRow >= nRowCount ) + nCurRow = nRowCount - 1; + aSelRange = Range( nCurRow, nCurRow ); + + // display new highlight if necessary + if ( !bMultiSelection && !bKeepSelection ) + uRow.nSel = nRow; + + // resume Updates + pDataWin->LeaveUpdateLock(); + + // Cursor+Highlight + if ( !bMultiSelection && !bKeepSelection) + ToggleSelection(); + DoShowCursor( "GoToRow" ); + if ( !bRowColMove && nOldCurRow != nCurRow ) + CursorMoved(); + + if ( !bMultiSelection && !bKeepSelection ) + { + if ( !bSelecting ) + Select(); + else + bSelect = true; + } + return true; +} + + +bool BrowseBox::GoToColumnId( sal_uInt16 nColId) +{ + return GoToColumnId(nColId, true); +} + + +bool BrowseBox::GoToColumnId( sal_uInt16 nColId, bool bMakeVisible, bool bRowColMove) +{ + if (!bColumnCursor) + return false; + + // allowed? + if (!bRowColMove && !IsCursorMoveAllowed( nCurRow, nColId ) ) + return false; + + if ( nColId != nCurColId || (bMakeVisible && !IsFieldVisible(nCurRow, nColId, true))) + { + sal_uInt16 nNewPos = GetColumnPos(nColId); + BrowserColumn* pColumn = (nNewPos < mvCols.size()) ? mvCols[ nNewPos ].get() : nullptr; + DBG_ASSERT( pColumn, "no column object - invalid id?" ); + if ( !pColumn ) + return false; + + DoHideCursor( "GoToColumnId" ); + nCurColId = nColId; + + bool bScrolled = false; + + sal_uInt16 nFirstPos = nFirstCol; + sal_uInt16 nWidth = static_cast<sal_uInt16>(pColumn->Width()); + sal_uInt16 nLastPos = GetColumnAtXPosPixel( + pDataWin->GetSizePixel().Width()-nWidth ); + sal_uInt16 nFrozen = FrozenColCount(); + if ( bMakeVisible && nLastPos && + nNewPos >= nFrozen && ( nNewPos < nFirstPos || nNewPos > nLastPos ) ) + { + if ( nNewPos < nFirstPos ) + ScrollColumns( nNewPos-nFirstPos ); + else if ( nNewPos > nLastPos ) + ScrollColumns( nNewPos-nLastPos ); + bScrolled = true; + } + + DoShowCursor( "GoToColumnId" ); + if (!bRowColMove) + { + //try to move to nCurRow, nColId + CursorMoveAttempt aAttempt(nCurRow, nColId, bScrolled); + //Detect if we are already in a call to BrowseBox::GoToColumnId + //but the attempt is impossible and we are simply recursing + //into BrowseBox::GoToColumnId with the same impossible to + //fulfill conditions + if (m_aGotoStack.empty() || aAttempt != m_aGotoStack.top()) + { + m_aGotoStack.push(aAttempt); + CursorMoved(); + m_aGotoStack.pop(); + } + } + return true; + } + return true; +} + + +bool BrowseBox::GoToRowColumnId( long nRow, sal_uInt16 nColId ) +{ + + // out of range? + if ( nRow < 0 || nRow >= nRowCount ) + return false; + + if (!bColumnCursor) + return false; + + // nothing to do ? + if ( nRow == nCurRow && ( bMultiSelection || uRow.nSel == nRow ) && + nColId == nCurColId && IsFieldVisible(nCurRow, nColId, true)) + return true; + + // allowed? + if (!IsCursorMoveAllowed(nRow, nColId)) + return false; + + DoHideCursor( "GoToRowColumnId" ); + bool bMoved = GoToRow(nRow, true) && GoToColumnId(nColId, true, true); + DoShowCursor( "GoToRowColumnId" ); + + if (bMoved) + CursorMoved(); + + return bMoved; +} + + +void BrowseBox::SetNoSelection() +{ + + // is there no selection + if ( ( !pColSel || !pColSel->GetSelectCount() ) && + ( ( !bMultiSelection && uRow.nSel == BROWSER_ENDOFSELECTION ) || + ( bMultiSelection && !uRow.pSel->GetSelectCount() ) ) ) + // nothing to do + return; + + SAL_INFO("svtools", "BrowseBox::HideCursor " << this ); + ToggleSelection(); + + // unselect all + if ( bMultiSelection ) + uRow.pSel->SelectAll(false); + else + uRow.nSel = BROWSER_ENDOFSELECTION; + if ( pColSel ) + pColSel->SelectAll(false); + if ( !bSelecting ) + Select(); + else + bSelect = true; + + // restore screen + SAL_INFO("svtools", "BrowseBox::ShowCursor " << this ); + + if ( isAccessibleAlive() ) + { + commitTableEvent( + SELECTION_CHANGED, + Any(), + Any() + ); + } +} + + +void BrowseBox::SelectAll() +{ + + if ( !bMultiSelection ) + return; + + SAL_INFO("svtools", "BrowseBox::HideCursor " << this ); + ToggleSelection(); + + // select all rows + if ( pColSel ) + pColSel->SelectAll(false); + uRow.pSel->SelectAll(); + + // don't highlight handle column + BrowserColumn *pFirstCol = mvCols[ 0 ].get(); + long nOfsX = pFirstCol->GetId() ? 0 : pFirstCol->Width(); + + // highlight the row selection + if ( !bHideSelect ) + { + tools::Rectangle aHighlightRect; + sal_uInt16 nVisibleRows = + static_cast<sal_uInt16>(pDataWin->GetOutputSizePixel().Height() / GetDataRowHeight() + 1); + for ( long nRow = std::max<long>( nTopRow, uRow.pSel->FirstSelected() ); + nRow != BROWSER_ENDOFSELECTION && nRow < nTopRow + nVisibleRows; + nRow = uRow.pSel->NextSelected() ) + aHighlightRect.Union( tools::Rectangle( + Point( nOfsX, (nRow-nTopRow)*GetDataRowHeight() ), + Size( pDataWin->GetSizePixel().Width(), GetDataRowHeight() ) ) ); + pDataWin->Invalidate( aHighlightRect ); + } + + if ( !bSelecting ) + Select(); + else + bSelect = true; + + // restore screen + SAL_INFO("svtools", "BrowseBox::ShowCursor " << this ); + + if ( !isAccessibleAlive() ) + return; + + commitTableEvent( + SELECTION_CHANGED, + Any(), + Any() + ); + commitHeaderBarEvent( + SELECTION_CHANGED, + Any(), + Any(), + true + ); // column header event + + commitHeaderBarEvent( + SELECTION_CHANGED, + Any(), + Any(), + false + ); // row header event +} + + +void BrowseBox::SelectRow( long nRow, bool _bSelect, bool bExpand ) +{ + + if ( !bMultiSelection ) + { + // deselecting is impossible, selecting via cursor + if ( _bSelect ) + GoToRow(nRow, false); + return; + } + + SAL_INFO("svtools", "BrowseBox::HideCursor " << this ); + + // remove old selection? + if ( !bExpand || !bMultiSelection ) + { + ToggleSelection(); + if ( bMultiSelection ) + uRow.pSel->SelectAll(false); + else + uRow.nSel = BROWSER_ENDOFSELECTION; + if ( pColSel ) + pColSel->SelectAll(false); + } + + // set new selection + if ( !bHideSelect + && ( ( bMultiSelection + && uRow.pSel->GetTotalRange().Max() >= nRow + && uRow.pSel->Select( nRow, _bSelect ) + ) + || ( !bMultiSelection + && ( uRow.nSel = nRow ) != BROWSER_ENDOFSELECTION ) + ) + ) + { + // don't highlight handle column + BrowserColumn *pFirstCol = mvCols[ 0 ].get(); + long nOfsX = pFirstCol->GetId() ? 0 : pFirstCol->Width(); + + // highlight only newly selected part + tools::Rectangle aRect( + Point( nOfsX, (nRow-nTopRow)*GetDataRowHeight() ), + Size( pDataWin->GetSizePixel().Width(), GetDataRowHeight() ) ); + pDataWin->Invalidate( aRect ); + } + + if ( !bSelecting ) + Select(); + else + bSelect = true; + + // restore screen + SAL_INFO("svtools", "BrowseBox::ShowCursor " << this ); + + if ( !isAccessibleAlive() ) + return; + + commitTableEvent( + SELECTION_CHANGED, + Any(), + Any() + ); + commitHeaderBarEvent( + SELECTION_CHANGED, + Any(), + Any(), + false + ); // row header event +} + + +long BrowseBox::GetSelectRowCount() const +{ + + return bMultiSelection ? uRow.pSel->GetSelectCount() : + uRow.nSel == BROWSER_ENDOFSELECTION ? 0 : 1; +} + + +void BrowseBox::SelectColumnPos( sal_uInt16 nNewColPos, bool _bSelect, bool bMakeVisible ) +{ + + if ( !bColumnCursor || nNewColPos == BROWSER_INVALIDID ) + return; + + if ( !bMultiSelection ) + { + if ( _bSelect ) + GoToColumnId( mvCols[ nNewColPos ]->GetId(), bMakeVisible ); + return; + } + else + { + if ( !GoToColumnId( mvCols[ nNewColPos ]->GetId(), bMakeVisible ) ) + return; + } + + SAL_INFO("svtools", "BrowseBox::HideCursor " << this ); + ToggleSelection(); + if ( bMultiSelection ) + uRow.pSel->SelectAll(false); + else + uRow.nSel = BROWSER_ENDOFSELECTION; + pColSel->SelectAll(false); + + if ( pColSel->Select( nNewColPos, _bSelect ) ) + { + // GoToColumnId( mvCols->GetObject(nNewColPos)->GetId(), bMakeVisible ); + + // only highlight painted areas + pDataWin->Update(); + tools::Rectangle aFieldRectPix( GetFieldRectPixel( nCurRow, nCurColId, false ) ); + tools::Rectangle aRect( + Point( aFieldRectPix.Left() - MIN_COLUMNWIDTH, 0 ), + Size( mvCols[ nNewColPos ]->Width(), + pDataWin->GetOutputSizePixel().Height() ) ); + pDataWin->Invalidate( aRect ); + if ( !bSelecting ) + Select(); + else + bSelect = true; + + if ( isAccessibleAlive() ) + { + commitTableEvent( + SELECTION_CHANGED, + Any(), + Any() + ); + commitHeaderBarEvent( + SELECTION_CHANGED, + Any(), + Any(), + true + ); // column header event + } + } + + // restore screen + SAL_INFO("svtools", "BrowseBox::ShowCursor " << this ); +} + + +sal_uInt16 BrowseBox::GetSelectColumnCount() const +{ + + // while bAutoSelect (==!pColSel), 1 if any rows (yes rows!) else none + return pColSel ? static_cast<sal_uInt16>(pColSel->GetSelectCount()) : + nCurRow >= 0 ? 1 : 0; +} + + +long BrowseBox::FirstSelectedColumn( ) const +{ + return pColSel ? pColSel->FirstSelected() : BROWSER_ENDOFSELECTION; +} + + +long BrowseBox::FirstSelectedRow() +{ + + return bMultiSelection ? uRow.pSel->FirstSelected() : uRow.nSel; +} + + +long BrowseBox::NextSelectedRow() +{ + + return bMultiSelection ? uRow.pSel->NextSelected() : BROWSER_ENDOFSELECTION; +} + + +long BrowseBox::LastSelectedRow() +{ + + return bMultiSelection ? uRow.pSel->LastSelected() : uRow.nSel; +} + + +bool BrowseBox::IsRowSelected( long nRow ) const +{ + + return bMultiSelection ? uRow.pSel->IsSelected(nRow) : nRow == uRow.nSel; +} + + +bool BrowseBox::IsColumnSelected( sal_uInt16 nColumnId ) const +{ + + return pColSel ? pColSel->IsSelected( GetColumnPos(nColumnId) ) : + nCurColId == nColumnId; +} + + +void BrowseBox::MakeFieldVisible +( + long nRow, // line number of the field (starting with 0) + sal_uInt16 nColId // column ID of the field +) + +/* [Description] + + Makes visible the field described in 'nRow' and 'nColId' by scrolling + accordingly. + +*/ + +{ + if (!pDataWin) + return; + + Size aTestSize = pDataWin->GetSizePixel(); + + if ( !bBootstrapped || aTestSize.IsEmpty() ) + return; + + // is it visible already? + bool bVisible = IsFieldVisible( nRow, nColId, true/*bComplete*/ ); + if ( bVisible ) + return; + + // calculate column position, field rectangle and painting area + sal_uInt16 nColPos = GetColumnPos( nColId ); + tools::Rectangle aFieldRect = GetFieldRectPixel( nRow, nColId, false ); + tools::Rectangle aDataRect( Point(0, 0), pDataWin->GetSizePixel() ); + + // positioned outside on the left? + if ( nColPos >= FrozenColCount() && nColPos < nFirstCol ) + // => scroll to the right + ScrollColumns( nColPos - nFirstCol ); + + // while outside on the right + while ( aDataRect.Right() < aFieldRect.Right() ) + { + // => scroll to the left + if ( ScrollColumns( 1 ) != 1 ) + // no more need to scroll + break; + aFieldRect = GetFieldRectPixel( nRow, nColId, false ); + } + + // positioned outside above? + if ( nRow < nTopRow ) + // scroll further to the bottom + ScrollRows( nRow - nTopRow ); + + // positioned outside below? + long nBottomRow = nTopRow + GetVisibleRows(); + // decrement nBottomRow to make it the number of the last visible line + // (count starts with 0!). + // Example: BrowseBox contains exactly one entry. nBottomRow := 0 + 1 - 1 + if( nBottomRow ) + nBottomRow--; + + if ( nRow > nBottomRow ) + // scroll further to the top + ScrollRows( nRow - nBottomRow ); +} + + +bool BrowseBox::IsFieldVisible( long nRow, sal_uInt16 nColumnId, + bool bCompletely ) const +{ + + // hidden by frozen column? + sal_uInt16 nColPos = GetColumnPos( nColumnId ); + if ( nColPos >= FrozenColCount() && nColPos < nFirstCol ) + return false; + + tools::Rectangle aRect( ImplFieldRectPixel( nRow, nColumnId ) ); + if ( aRect.IsEmpty() ) + return false; + + // get the visible area + tools::Rectangle aOutRect( Point(0, 0), pDataWin->GetOutputSizePixel() ); + + if ( bCompletely ) + // test if the field is completely visible + return aOutRect.IsInside( aRect ); + else + // test if the field is partly of completely visible + return !aOutRect.Intersection( aRect ).IsEmpty(); +} + + +tools::Rectangle BrowseBox::GetFieldRectPixel( long nRow, sal_uInt16 nColumnId, + bool bRelToBrowser) const +{ + + // get the rectangle relative to DataWin + tools::Rectangle aRect( ImplFieldRectPixel( nRow, nColumnId ) ); + if ( aRect.IsEmpty() ) + return aRect; + + // adjust relative to BrowseBox's output area + Point aTopLeft( aRect.TopLeft() ); + if ( bRelToBrowser ) + { + aTopLeft = pDataWin->OutputToScreenPixel( aTopLeft ); + aTopLeft = ScreenToOutputPixel( aTopLeft ); + } + + return tools::Rectangle( aTopLeft, aRect.GetSize() ); +} + + +tools::Rectangle BrowseBox::GetRowRectPixel( long nRow ) const +{ + + // get the rectangle relative to DataWin + tools::Rectangle aRect; + if ( nTopRow > nRow ) + // row is above visible area + return aRect; + aRect = tools::Rectangle( + Point( 0, GetDataRowHeight() * (nRow-nTopRow) ), + Size( pDataWin->GetOutputSizePixel().Width(), GetDataRowHeight() ) ); + if ( aRect.TopLeft().Y() > pDataWin->GetOutputSizePixel().Height() ) + // row is below visible area + return aRect; + + // adjust relative to BrowseBox's output area + Point aTopLeft( aRect.TopLeft() ); + aTopLeft = pDataWin->OutputToScreenPixel( aTopLeft ); + aTopLeft = ScreenToOutputPixel( aTopLeft ); + + return tools::Rectangle( aTopLeft, aRect.GetSize() ); +} + + +tools::Rectangle BrowseBox::ImplFieldRectPixel( long nRow, sal_uInt16 nColumnId ) const +{ + + // compute the X-coordinate relative to DataWin by accumulation + long nColX = 0; + sal_uInt16 nFrozenCols = FrozenColCount(); + size_t nCol; + for ( nCol = 0; + nCol < mvCols.size() && mvCols[ nCol ]->GetId() != nColumnId; + ++nCol ) + if ( mvCols[ nCol ]->IsFrozen() || nCol >= nFirstCol ) + nColX += mvCols[ nCol ]->Width(); + + if ( nCol >= mvCols.size() || ( nCol >= nFrozenCols && nCol < nFirstCol ) ) + return tools::Rectangle(); + + // compute the Y-coordinate relative to DataWin + long nRowY = GetDataRowHeight(); + if ( nRow != BROWSER_ENDOFSELECTION ) // #105497# OJ + nRowY = ( nRow - nTopRow ) * GetDataRowHeight(); + + // assemble the Rectangle relative to DataWin + return tools::Rectangle( + Point( nColX + MIN_COLUMNWIDTH, nRowY ), + Size( (mvCols[nCol]->Width() == LONG_MAX + ? LONG_MAX - (nColX + MIN_COLUMNWIDTH) : mvCols[ nCol ]->Width() - 2*MIN_COLUMNWIDTH), + GetDataRowHeight() - 1 ) ); +} + + +long BrowseBox::GetRowAtYPosPixel( long nY, bool bRelToBrowser ) const +{ + + // compute the Y-coordinate + if ( bRelToBrowser ) + { + Point aDataTopLeft = pDataWin->OutputToScreenPixel( Point(0, 0) ); + Point aTopLeft = OutputToScreenPixel( Point(0, 0) ); + nY -= aDataTopLeft.Y() - aTopLeft.Y(); + } + + // no row there (e.g. in the header) + if ( nY < 0 || nY >= pDataWin->GetOutputSizePixel().Height() ) + return -1; + + return nY / GetDataRowHeight() + nTopRow; +} + + +tools::Rectangle BrowseBox::GetFieldRect( sal_uInt16 nColumnId ) const +{ + + return GetFieldRectPixel( nCurRow, nColumnId ); +} + + +sal_uInt16 BrowseBox::GetColumnAtXPosPixel( long nX ) const +{ + + // accumulate the widths of the visible columns + long nColX = 0; + for ( size_t nCol = 0; nCol < mvCols.size(); ++nCol ) + { + BrowserColumn *pCol = mvCols[ nCol ].get(); + if ( pCol->IsFrozen() || nCol >= nFirstCol ) + nColX += pCol->Width(); + + if ( nColX > nX ) + return nCol; + } + + return BROWSER_INVALIDID; +} + +bool BrowseBox::ReserveControlArea(sal_uInt16 nWidth) +{ + if (nWidth != nControlAreaWidth) + { + OSL_ENSURE(nWidth,"Control area of 0 is not allowed, Use USHRT_MAX instead!"); + nControlAreaWidth = nWidth; + UpdateScrollbars(); + return true; + } + return false; +} + +tools::Rectangle BrowseBox::GetControlArea() const +{ + auto nHeight = aHScroll->GetSizePixel().Height(); + return tools::Rectangle( + Point( 0, GetOutputSizePixel().Height() - nHeight ), + Size( GetOutputSizePixel().Width() - aHScroll->GetSizePixel().Width(), + nHeight ) ); +} + +void BrowseBox::SetMode( BrowserMode nMode ) +{ + + pDataWin->bAutoHScroll = BrowserMode::AUTO_HSCROLL == ( nMode & BrowserMode::AUTO_HSCROLL ); + pDataWin->bAutoVScroll = BrowserMode::AUTO_VSCROLL == ( nMode & BrowserMode::AUTO_VSCROLL ); + pDataWin->bNoHScroll = BrowserMode::NO_HSCROLL == ( nMode & BrowserMode::NO_HSCROLL ); + pDataWin->bNoVScroll = BrowserMode::NO_VSCROLL == ( nMode & BrowserMode::NO_VSCROLL ); + + DBG_ASSERT( !( pDataWin->bAutoHScroll && pDataWin->bNoHScroll ), + "BrowseBox::SetMode: AutoHScroll *and* NoHScroll?" ); + DBG_ASSERT( !( pDataWin->bAutoVScroll && pDataWin->bNoVScroll ), + "BrowseBox::SetMode: AutoVScroll *and* NoVScroll?" ); + if ( pDataWin->bAutoHScroll ) + pDataWin->bNoHScroll = false; + if ( pDataWin->bAutoVScroll ) + pDataWin->bNoVScroll = false; + + if ( pDataWin->bNoHScroll ) + aHScroll->Hide(); + + nControlAreaWidth = USHRT_MAX; + + long nOldRowSel = bMultiSelection ? uRow.pSel->FirstSelected() : uRow.nSel; + MultiSelection *pOldRowSel = bMultiSelection ? uRow.pSel : nullptr; + + pVScroll.disposeAndClear(); + + bMultiSelection = bool( nMode & BrowserMode::MULTISELECTION ); + bColumnCursor = bool( nMode & BrowserMode::COLUMNSELECTION ); + bKeepHighlight = bool( nMode & BrowserMode::KEEPHIGHLIGHT ); + + bHideSelect = ((nMode & BrowserMode::HIDESELECT) == BrowserMode::HIDESELECT); + // default: do not hide the cursor at all (untaken scrolling and such) + bHideCursor = TRISTATE_FALSE; + + if ( BrowserMode::HIDECURSOR == ( nMode & BrowserMode::HIDECURSOR ) ) + { + bHideCursor = TRISTATE_TRUE; + } + + m_bFocusOnlyCursor = ((nMode & BrowserMode::CURSOR_WO_FOCUS) == BrowserMode::NONE); + + bHLines = ( nMode & BrowserMode::HLINES ) == BrowserMode::HLINES; + bVLines = ( nMode & BrowserMode::VLINES ) == BrowserMode::VLINES; + + constexpr WinBits nVScrollWinBits = WB_VSCROLL; + pVScroll = ( nMode & BrowserMode::TRACKING_TIPS ) == BrowserMode::TRACKING_TIPS + ? VclPtr<BrowserScrollBar>::Create( this, nVScrollWinBits, pDataWin.get() ) + : VclPtr<ScrollBar>::Create( this, nVScrollWinBits ); + pVScroll->SetLineSize( 1 ); + pVScroll->SetPageSize(1); + pVScroll->SetScrollHdl( LINK( this, BrowseBox, ScrollHdl ) ); + + pDataWin->bAutoSizeLastCol = + BrowserMode::AUTOSIZE_LASTCOL == ( nMode & BrowserMode::AUTOSIZE_LASTCOL ); + + // create a headerbar. what happens, if a headerbar has to be created and + // there already are columns? + if ( BrowserMode::HEADERBAR_NEW == ( nMode & BrowserMode::HEADERBAR_NEW ) ) + { + if (!pDataWin->pHeaderBar) + pDataWin->pHeaderBar = CreateHeaderBar( this ); + } + else + { + pDataWin->pHeaderBar.disposeAndClear(); + } + + if ( bColumnCursor ) + { + if (!pColSel) + pColSel.reset(new MultiSelection); + pColSel->SetTotalRange( Range( 0, mvCols.size()-1 ) ); + } + else + { + pColSel.reset(); + } + + if ( bMultiSelection ) + { + if ( pOldRowSel ) + uRow.pSel = pOldRowSel; + else + uRow.pSel = new MultiSelection; + } + else + { + uRow.nSel = nOldRowSel; + delete pOldRowSel; + } + + if ( bBootstrapped ) + { + StateChanged( StateChangedType::InitShow ); + if ( bMultiSelection && !pOldRowSel && + nOldRowSel != BROWSER_ENDOFSELECTION ) + uRow.pSel->Select( nOldRowSel ); + } + + if ( pDataWin ) + pDataWin->Invalidate(); + + // no cursor on handle column + if ( nCurColId == HandleColumnId ) + nCurColId = GetColumnId( 1 ); + + m_nCurrentMode = nMode; +} + + +void BrowseBox::VisibleRowsChanged( long, sal_uInt16 ) +{ + + // old behavior: automatically correct NumRows: + if ( nRowCount < GetRowCount() ) + { + RowInserted(nRowCount,GetRowCount() - nRowCount, false); + } + else if ( nRowCount > GetRowCount() ) + { + RowRemoved(nRowCount-(nRowCount - GetRowCount()),nRowCount - GetRowCount(), false); + } +} + + +bool BrowseBox::IsCursorMoveAllowed( long, sal_uInt16 ) const + +/* [Description] + + This virtual method is always called before the cursor is moved directly. + By means of 'return false', we avoid doing this if e.g. a record + contradicts any rules. + + This method is not called, if the cursor movement results from removing or + deleting a row/column (thus, in cases where only a "cursor correction" happens). + + The base implementation currently always returns true. +*/ + +{ + return true; +} + + +long BrowseBox::GetDataRowHeight() const +{ + return CalcZoom(nDataRowHeight ? nDataRowHeight : ImpGetDataRowHeight()); +} + + +VclPtr<BrowserHeader> BrowseBox::CreateHeaderBar( BrowseBox* pParent ) +{ + VclPtr<BrowserHeader> pNewBar = VclPtr<BrowserHeader>::Create( pParent ); + pNewBar->SetStartDragHdl( LINK( this, BrowseBox, StartDragHdl ) ); + return pNewBar; +} + +void BrowseBox::SetHeaderBar( BrowserHeader* pHeaderBar ) +{ + pDataWin->pHeaderBar.disposeAndClear(); + pDataWin->pHeaderBar = pHeaderBar; + pDataWin->pHeaderBar->SetStartDragHdl( LINK( this, BrowseBox, StartDragHdl ) ); +} + +long BrowseBox::GetTitleHeight() const +{ + long nHeight; + // ask the header bar for the text height (if possible), as the header bar's font is adjusted with + // our (and the header's) zoom factor + HeaderBar* pHeaderBar = pDataWin->pHeaderBar; + if ( pHeaderBar ) + nHeight = pHeaderBar->GetTextHeight(); + else + nHeight = GetTextHeight(); + + return nTitleLines ? nTitleLines * nHeight + 4 : 0; +} + +long BrowseBox::CalcReverseZoom(long nVal) +{ + if (IsZoom()) + { + const Fraction& rZoom = GetZoom(); + double n = static_cast<double>(nVal); + n *= static_cast<double>(rZoom.GetDenominator()); + if (!rZoom.GetNumerator()) + throw o3tl::divide_by_zero(); + n /= static_cast<double>(rZoom.GetNumerator()); + nVal = n>0 ? static_cast<long>(n + 0.5) : -static_cast<long>(-n + 0.5); + } + + return nVal; +} + +void BrowseBox::CursorMoved() +{ + // before implementing more here, please adjust the EditBrowseBox + + if ( isAccessibleAlive() && HasFocus() ) + commitTableEvent( + ACTIVE_DESCENDANT_CHANGED, + makeAny( CreateAccessibleCell( GetCurRow(),GetColumnPos( GetCurColumnId() ) ) ), + Any() + ); +} + +void BrowseBox::LoseFocus() +{ + SAL_INFO("svtools", "BrowseBox::LoseFocus " << this ); + + if ( bHasFocus ) + { + SAL_INFO("svtools", "BrowseBox::HideCursor " << this ); + DoHideCursor( "LoseFocus" ); + + if ( !bKeepHighlight ) + { + ToggleSelection(); + bSelectionIsVisible = false; + } + + bHasFocus = false; + } + Control::LoseFocus(); +} + + +void BrowseBox::GetFocus() +{ + SAL_INFO("svtools", "BrowseBox::GetFocus " << this ); + + if ( !bHasFocus ) + { + if ( !bSelectionIsVisible ) + { + bSelectionIsVisible = true; + if ( bBootstrapped ) + ToggleSelection(); + } + + bHasFocus = true; + DoShowCursor( "GetFocus" ); + } + Control::GetFocus(); +} + + +sal_uInt16 BrowseBox::GetVisibleRows() const +{ + return static_cast<sal_uInt16>((pDataWin->GetOutputSizePixel().Height() - 1 )/ GetDataRowHeight() + 1); +} + +vcl::Window& BrowseBox::GetDataWindow() const +{ + return *pDataWin; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/brwbox/brwbox2.cxx b/svtools/source/brwbox/brwbox2.cxx new file mode 100644 index 000000000..e9e725149 --- /dev/null +++ b/svtools/source/brwbox/brwbox2.cxx @@ -0,0 +1,1972 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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/log.hxx> +#include <o3tl/safeint.hxx> +#include <osl/diagnose.h> +#include <tools/debug.hxx> +#include <svtools/brwbox.hxx> +#include "datwin.hxx" +#include <svtools/colorcfg.hxx> +#include <vcl/commandevent.hxx> +#include <vcl/ptrstyle.hxx> +#include <vcl/scrbar.hxx> +#include <vcl/settings.hxx> +#include <vcl/status.hxx> + +#include <tools/multisel.hxx> +#include <tools/fract.hxx> +#include <algorithm> +#include <memory> + +using namespace ::com::sun::star::datatransfer; + + +void BrowseBox::StartDrag( sal_Int8 /* _nAction */, const Point& /* _rPosPixel */ ) +{ + // not interested in this event +} + + +sal_Int8 BrowseBox::AcceptDrop( const AcceptDropEvent& _rEvt ) +{ + AcceptDropEvent aTransformed( _rEvt ); + aTransformed.maPosPixel = pDataWin->ScreenToOutputPixel( OutputToScreenPixel( _rEvt.maPosPixel ) ); + return pDataWin->AcceptDrop( aTransformed ); +} + + +sal_Int8 BrowseBox::ExecuteDrop( const ExecuteDropEvent& _rEvt ) +{ + ExecuteDropEvent aTransformed( _rEvt ); + aTransformed.maPosPixel = pDataWin->ScreenToOutputPixel( OutputToScreenPixel( _rEvt.maPosPixel ) ); + return pDataWin->ExecuteDrop( aTransformed ); +} + + +sal_Int8 BrowseBox::AcceptDrop( const BrowserAcceptDropEvent& ) +{ + // not interested in this event + return DND_ACTION_NONE; +} + + +sal_Int8 BrowseBox::ExecuteDrop( const BrowserExecuteDropEvent& ) +{ + // not interested in this event + return DND_ACTION_NONE; +} + + +const DataFlavorExVector& BrowseBox::GetDataFlavors() const +{ + if (pDataWin->bCallingDropCallback) + return pDataWin->GetDataFlavorExVector(); + return GetDataFlavorExVector(); +} + + +bool BrowseBox::IsDropFormatSupported( SotClipboardFormatId _nFormat ) +{ + if ( pDataWin->bCallingDropCallback ) + return pDataWin->IsDropFormatSupported( _nFormat ); + + return DropTargetHelper::IsDropFormatSupported( _nFormat ); +} + + +void BrowseBox::Command( const CommandEvent& rEvt ) +{ + if ( !pDataWin->bInCommand ) + Control::Command( rEvt ); +} + + +void BrowseBox::StateChanged( StateChangedType nStateChange ) +{ + Control::StateChanged( nStateChange ); + + if ( StateChangedType::Mirroring == nStateChange ) + { + pDataWin->EnableRTL( IsRTLEnabled() ); + + HeaderBar* pHeaderBar = pDataWin->pHeaderBar; + if ( pHeaderBar ) + pHeaderBar->EnableRTL( IsRTLEnabled() ); + aHScroll->EnableRTL( IsRTLEnabled() ); + if( pVScroll ) + pVScroll->EnableRTL( IsRTLEnabled() ); + Resize(); + } + else if ( StateChangedType::InitShow == nStateChange ) + { + bBootstrapped = true; // must be set first! + + Resize(); + if ( bMultiSelection ) + uRow.pSel->SetTotalRange( Range( 0, nRowCount - 1 ) ); + if ( nRowCount == 0 ) + nCurRow = BROWSER_ENDOFSELECTION; + else if ( nCurRow == BROWSER_ENDOFSELECTION ) + nCurRow = 0; + + + if ( HasFocus() ) + { + bSelectionIsVisible = true; + bHasFocus = true; + } + UpdateScrollbars(); + AutoSizeLastColumn(); + CursorMoved(); + } + else if (StateChangedType::Zoom == nStateChange) + { + pDataWin->SetZoom(GetZoom()); + HeaderBar* pHeaderBar = pDataWin->pHeaderBar; + if (pHeaderBar) + pHeaderBar->SetZoom(GetZoom()); + + // let the columns calculate their new widths and adjust the header bar + for (auto & pCol : mvCols) + { + pCol->ZoomChanged(GetZoom()); + if ( pHeaderBar ) + pHeaderBar->SetItemSize( pCol->GetId(), pCol->Width() ); + } + + // all our controls have to be repositioned + Resize(); + } + else if (StateChangedType::Enable == nStateChange) + { + // do we have a handle column? + bool bHandleCol = !mvCols.empty() && (0 == mvCols[ 0 ]->GetId()); + // do we have a header bar? + bool bHeaderBar = (nullptr != pDataWin->pHeaderBar.get()); + + if ( nTitleLines + && ( !bHeaderBar + || bHandleCol + ) + ) + // we draw the text in our header bar in a color dependent on the enabled state. So if this state changed + // -> redraw + Invalidate(tools::Rectangle(Point(0, 0), Size(GetOutputSizePixel().Width(), GetTitleHeight() - 1))); + } +} + + +void BrowseBox::Select() +{ +} + + +void BrowseBox::DoubleClick( const BrowserMouseEvent & ) +{ +} + + +long BrowseBox::QueryMinimumRowHeight() +{ + return CalcZoom( 5 ); +} + + +void BrowseBox::ImplStartTracking() +{ +} + + +void BrowseBox::ImplEndTracking() +{ +} + + +void BrowseBox::RowHeightChanged() +{ +} + + +void BrowseBox::ColumnResized( sal_uInt16 ) +{ +} + + +void BrowseBox::ColumnMoved( sal_uInt16 ) +{ +} + + +void BrowseBox::StartScroll() +{ + DoHideCursor( "StartScroll" ); +} + + +void BrowseBox::EndScroll() +{ + UpdateScrollbars(); + AutoSizeLastColumn(); + DoShowCursor( "EndScroll" ); +} + + +void BrowseBox::ToggleSelection() +{ + + // selection highlight-toggling allowed? + if ( bHideSelect ) + return; + if ( bNotToggleSel || !IsUpdateMode() || !bSelectionIsVisible ) + return; + + // only highlight painted areas! + bNotToggleSel = true; + + // accumulate areas of rows to highlight + std::vector<tools::Rectangle> aHighlightList; + long nLastRowInRect = 0; // for the CFront + + // don't highlight handle column + BrowserColumn *pFirstCol = mvCols.empty() ? nullptr : mvCols[ 0 ].get(); + long nOfsX = (!pFirstCol || pFirstCol->GetId()) ? 0 : pFirstCol->Width(); + + // accumulate old row selection + long nBottomRow = nTopRow + + pDataWin->GetOutputSizePixel().Height() / GetDataRowHeight(); + if ( nBottomRow > GetRowCount() && GetRowCount() ) + nBottomRow = GetRowCount(); + for ( long nRow = bMultiSelection ? uRow.pSel->FirstSelected() : uRow.nSel; + nRow != BROWSER_ENDOFSELECTION && nRow <= nBottomRow; + nRow = bMultiSelection ? uRow.pSel->NextSelected() : BROWSER_ENDOFSELECTION ) + { + if ( nRow < nTopRow ) + continue; + + tools::Rectangle aAddRect( + Point( nOfsX, (nRow-nTopRow)*GetDataRowHeight() ), + Size( pDataWin->GetSizePixel().Width(), GetDataRowHeight() ) ); + if ( !aHighlightList.empty() && nLastRowInRect == ( nRow - 1 ) ) + aHighlightList[ 0 ].Union( aAddRect ); + else + aHighlightList.emplace( aHighlightList.begin(), aAddRect ); + nLastRowInRect = nRow; + } + + // unhighlight the old selection (if any) + while ( !aHighlightList.empty() ) + { + pDataWin->Invalidate( aHighlightList.back() ); + aHighlightList.pop_back(); + } + + // unhighlight old column selection (if any) + for ( long nColId = pColSel ? pColSel->FirstSelected() : BROWSER_ENDOFSELECTION; + nColId != BROWSER_ENDOFSELECTION; + nColId = pColSel->NextSelected() ) + { + tools::Rectangle aRect( GetFieldRectPixel(nCurRow, + mvCols[ nColId ]->GetId(), + false ) ); + aRect.AdjustLeft( -(MIN_COLUMNWIDTH) ); + aRect.AdjustRight(MIN_COLUMNWIDTH ); + aRect.SetTop( 0 ); + aRect.SetBottom( pDataWin->GetOutputSizePixel().Height() ); + pDataWin->Invalidate( aRect ); + } + + bNotToggleSel = false; +} + + +void BrowseBox::DrawCursor() +{ + bool bReallyHide = false; + if ( bHideCursor == TRISTATE_INDET ) + { + if ( !GetSelectRowCount() && !GetSelectColumnCount() ) + bReallyHide = true; + } + else if ( bHideCursor == TRISTATE_TRUE ) + { + bReallyHide = true; + } + + bReallyHide |= !bSelectionIsVisible || !IsUpdateMode() || bScrolling || nCurRow < 0; + + if (PaintCursorIfHiddenOnce()) + bReallyHide |= ( GetCursorHideCount() > 1 ); + else + bReallyHide |= ( GetCursorHideCount() > 0 ); + + // no cursor on handle column + if ( nCurColId == HandleColumnId ) + nCurColId = GetColumnId(1); + + // calculate cursor rectangle + tools::Rectangle aCursor; + if ( bColumnCursor ) + { + aCursor = GetFieldRectPixel( nCurRow, nCurColId, false ); + aCursor.AdjustLeft( -(MIN_COLUMNWIDTH) ); + aCursor.AdjustRight(1 ); + aCursor.AdjustBottom(1 ); + } + else + aCursor = tools::Rectangle( + Point( ( !mvCols.empty() && mvCols[ 0 ]->GetId() == 0 ) ? + mvCols[ 0 ]->Width() : 0, + (nCurRow - nTopRow) * GetDataRowHeight() + 1 ), + Size( pDataWin->GetOutputSizePixel().Width() + 1, + GetDataRowHeight() - 2 ) ); + if ( bHLines ) + { + if ( !bMultiSelection ) + aCursor.AdjustTop( -1 ); + aCursor.AdjustBottom( -1 ); + } + + if (m_aCursorColor == COL_TRANSPARENT) + { + // on these platforms, the StarView focus works correctly + if ( bReallyHide ) + static_cast<Control*>(pDataWin.get())->HideFocus(); + else + static_cast<Control*>(pDataWin.get())->ShowFocus( aCursor ); + } + else + { + Color rCol = bReallyHide ? pDataWin->GetFillColor() : m_aCursorColor; + Color aOldFillColor = pDataWin->GetFillColor(); + Color aOldLineColor = pDataWin->GetLineColor(); + pDataWin->SetFillColor(); + pDataWin->SetLineColor( rCol ); + pDataWin->DrawRect( aCursor ); + pDataWin->SetLineColor( aOldLineColor ); + pDataWin->SetFillColor( aOldFillColor ); + } +} + + +sal_uLong BrowseBox::GetColumnWidth( sal_uInt16 nId ) const +{ + + sal_uInt16 nItemPos = GetColumnPos( nId ); + if ( nItemPos >= mvCols.size() ) + return 0; + return mvCols[ nItemPos ]->Width(); +} + + +sal_uInt16 BrowseBox::GetColumnId( sal_uInt16 nPos ) const +{ + + if ( nPos >= mvCols.size() ) + return BROWSER_INVALIDID; + return mvCols[ nPos ]->GetId(); +} + + +sal_uInt16 BrowseBox::GetColumnPos( sal_uInt16 nId ) const +{ + for ( size_t nPos = 0; nPos < mvCols.size(); ++nPos ) + if ( mvCols[ nPos ]->GetId() == nId ) + return nPos; + return BROWSER_INVALIDID; +} + + +bool BrowseBox::IsFrozen( sal_uInt16 nColumnId ) const +{ + for (auto const & pCol : mvCols) + if ( pCol->GetId() == nColumnId ) + return pCol->IsFrozen(); + return false; +} + + +void BrowseBox::ExpandRowSelection( const BrowserMouseEvent& rEvt ) +{ + + DoHideCursor( "ExpandRowSelection" ); + + // expand the last selection + if ( bMultiSelection ) + { + Range aJustifiedRange( aSelRange ); + aJustifiedRange.Justify(); + + bool bSelectThis = ( bSelect != aJustifiedRange.IsInside( rEvt.GetRow() ) ); + + if ( aJustifiedRange.IsInside( rEvt.GetRow() ) ) + { + // down and up + while ( rEvt.GetRow() < aSelRange.Max() ) + { // ZTC/Mac bug - don't put these statements together! + SelectRow( aSelRange.Max(), bSelectThis ); + --aSelRange.Max(); + } + while ( rEvt.GetRow() > aSelRange.Max() ) + { // ZTC/Mac bug - don't put these statements together! + SelectRow( aSelRange.Max(), bSelectThis ); + ++aSelRange.Max(); + } + } + else + { + // up and down + bool bOldSelecting = bSelecting; + bSelecting = true; + while ( rEvt.GetRow() < aSelRange.Max() ) + { // ZTC/Mac bug - don't put these statements together! + --aSelRange.Max(); + if ( !IsRowSelected( aSelRange.Max() ) ) + { + SelectRow( aSelRange.Max(), bSelectThis ); + bSelect = true; + } + } + while ( rEvt.GetRow() > aSelRange.Max() ) + { // ZTC/Mac bug - don't put these statements together! + ++aSelRange.Max(); + if ( !IsRowSelected( aSelRange.Max() ) ) + { + SelectRow( aSelRange.Max(), bSelectThis ); + bSelect = true; + } + } + bSelecting = bOldSelecting; + if ( bSelect ) + Select(); + } + } + else + if (!IsRowSelected(rEvt.GetRow())) + SelectRow( rEvt.GetRow() ); + + GoToRow( rEvt.GetRow(), false ); + DoShowCursor( "ExpandRowSelection" ); +} + + +void BrowseBox::Resize() +{ + if ( !bBootstrapped && IsReallyVisible() ) + BrowseBox::StateChanged( StateChangedType::InitShow ); + if ( mvCols.empty() ) + { + pDataWin->bResizeOnPaint = true; + return; + } + pDataWin->bResizeOnPaint = false; + + // calc the size of the scrollbars + sal_uLong nSBSize = GetBarHeight(); + if (IsZoom()) + nSBSize = static_cast<sal_uLong>(nSBSize * static_cast<double>(GetZoom())); + + DoHideCursor( "Resize" ); + sal_uInt16 nOldVisibleRows = 0; + //fdo#42694, post #i111125# GetDataRowHeight() can be 0 + if (GetDataRowHeight()) + nOldVisibleRows = static_cast<sal_uInt16>(pDataWin->GetOutputSizePixel().Height() / GetDataRowHeight() + 1); + + // did we need a horizontal scroll bar or is there a Control Area? + if ( !pDataWin->bNoHScroll && + ( ( mvCols.size() - FrozenColCount() ) > 1 ) ) + aHScroll->Show(); + else + aHScroll->Hide(); + + // calculate the size of the data window + long nDataHeight = GetOutputSizePixel().Height() - GetTitleHeight(); + if ( aHScroll->IsVisible() || ( nControlAreaWidth != USHRT_MAX ) ) + nDataHeight -= nSBSize; + + long nDataWidth = GetOutputSizePixel().Width(); + if ( pVScroll->IsVisible() ) + nDataWidth -= nSBSize; + + // adjust position and size of data window + pDataWin->SetPosSizePixel( + Point( 0, GetTitleHeight() ), + Size( nDataWidth, nDataHeight ) ); + + sal_uInt16 nVisibleRows = 0; + + if (GetDataRowHeight()) + nVisibleRows = static_cast<sal_uInt16>(pDataWin->GetOutputSizePixel().Height() / GetDataRowHeight() + 1); + + // TopRow is unchanged, but the number of visible lines has changed. + if ( nVisibleRows != nOldVisibleRows ) + VisibleRowsChanged(nTopRow, nVisibleRows); + + UpdateScrollbars(); + + // Control-Area + tools::Rectangle aInvalidArea( GetControlArea() ); + aInvalidArea.SetRight( GetOutputSizePixel().Width() ); + aInvalidArea.SetLeft( 0 ); + Invalidate( aInvalidArea ); + + // external header-bar + HeaderBar* pHeaderBar = pDataWin->pHeaderBar; + if ( pHeaderBar ) + { + // take the handle column into account + BrowserColumn *pFirstCol = mvCols[ 0 ].get(); + long nOfsX = pFirstCol->GetId() ? 0 : pFirstCol->Width(); + pHeaderBar->SetPosSizePixel( Point( nOfsX, 0 ), Size( GetOutputSizePixel().Width() - nOfsX, GetTitleHeight() ) ); + } + + AutoSizeLastColumn(); // adjust last column width + DoShowCursor( "Resize" ); +} + + +void BrowseBox::Paint(vcl::RenderContext& rRenderContext, const tools::Rectangle& rRect) +{ + + // initializations + if (!bBootstrapped && IsReallyVisible()) + BrowseBox::StateChanged(StateChangedType::InitShow); + if (mvCols.empty()) + return; + + BrowserColumn *pFirstCol = mvCols[ 0 ].get(); + bool bHandleCol = pFirstCol && pFirstCol->GetId() == 0; + bool bHeaderBar = pDataWin->pHeaderBar.get() != nullptr; + + // draw delimitational lines + if (!pDataWin->bNoHScroll) + rRenderContext.DrawLine(Point(0, aHScroll->GetPosPixel().Y()), + Point(GetOutputSizePixel().Width(), + aHScroll->GetPosPixel().Y())); + + if (nTitleLines) + { + if (!bHeaderBar) + { + rRenderContext.DrawLine(Point(0, GetTitleHeight() - 1), + Point(GetOutputSizePixel().Width(), GetTitleHeight() - 1)); + } + else if (bHandleCol) + { + rRenderContext.DrawLine(Point(0, GetTitleHeight() - 1), + Point(pFirstCol->Width(), GetTitleHeight() - 1)); + } + } + + // Title Bar + // If there is a handle column and if the header bar is available, only + // take the HandleColumn into account + if (!(nTitleLines && (!bHeaderBar || bHandleCol))) + return; + + // iterate through columns to redraw + long nX = 0; + size_t nCol; + for (nCol = 0; nCol < mvCols.size() && nX < rRect.Right(); ++nCol) + { + // skip invisible columns between frozen and scrollable area + if (nCol < nFirstCol && !mvCols[nCol]->IsFrozen()) + nCol = nFirstCol; + + // only the handle column? + if (bHeaderBar && bHandleCol && nCol > 0) + break; + + BrowserColumn* pCol = mvCols[nCol].get(); + + // draw the column and increment position + if ( pCol->Width() > 4 ) + { + ButtonFrame aButtonFrame( Point( nX, 0 ), + Size( pCol->Width()-1, GetTitleHeight()-1 ), + pCol->Title(), !IsEnabled()); + aButtonFrame.Draw(rRenderContext); + rRenderContext.DrawLine(Point(nX + pCol->Width() - 1, 0), + Point(nX + pCol->Width() - 1, GetTitleHeight() - 1)); + } + else + { + rRenderContext.Push(PushFlags::FILLCOLOR); + rRenderContext.SetFillColor(COL_BLACK); + rRenderContext.DrawRect(tools::Rectangle(Point(nX, 0), Size(pCol->Width(), GetTitleHeight() - 1))); + rRenderContext.Pop(); + } + + // skip column + nX += pCol->Width(); + } + + // retouching + if ( !bHeaderBar && nCol == mvCols.size() ) + { + const StyleSettings &rSettings = rRenderContext.GetSettings().GetStyleSettings(); + Color aColFace(rSettings.GetFaceColor()); + rRenderContext.Push(PushFlags::FILLCOLOR | PushFlags::LINECOLOR); + rRenderContext.SetFillColor(aColFace); + rRenderContext.SetLineColor(aColFace); + rRenderContext.DrawRect(tools::Rectangle(Point(nX, 0), + Point(rRect.Right(), GetTitleHeight() - 2 ))); + rRenderContext.Pop(); + } +} + +void BrowseBox::Draw( OutputDevice* pDev, const Point& rPos, DrawFlags nFlags ) +{ + // we need pixel coordinates + Size aRealSize = GetSizePixel(); + Point aRealPos = pDev->LogicToPixel(rPos); + + if ((aRealSize.Width() < 3) || (aRealSize.Height() < 3)) + // we want to have two pixels frame ... + return; + + vcl::Font aFont = pDataWin->GetDrawPixelFont( pDev ); + // the 'normal' painting uses always the data window as device to output to, so we have to calc the new font + // relative to the data wins current settings + + pDev->Push(); + pDev->SetMapMode(); + pDev->SetFont( aFont ); + + // draw a frame + const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings(); + pDev->SetLineColor(rStyleSettings.GetDarkShadowColor()); + pDev->DrawLine(Point(aRealPos.X(), aRealPos.Y()), + Point(aRealPos.X(), aRealPos.Y() + aRealSize.Height() - 1)); + pDev->DrawLine(Point(aRealPos.X(), aRealPos.Y()), + Point(aRealPos.X() + aRealSize.Width() - 1, aRealPos.Y())); + pDev->SetLineColor(rStyleSettings.GetShadowColor()); + pDev->DrawLine(Point(aRealPos.X() + aRealSize.Width() - 1, aRealPos.Y() + 1), + Point(aRealPos.X() + aRealSize.Width() - 1, aRealPos.Y() + aRealSize.Height() - 1)); + pDev->DrawLine(Point(aRealPos.X() + aRealSize.Width() - 1, aRealPos.Y() + aRealSize.Height() - 1), + Point(aRealPos.X() + 1, aRealPos.Y() + aRealSize.Height() - 1)); + + HeaderBar* pBar = pDataWin->pHeaderBar; + + // we're drawing onto a foreign device, so we have to fake the DataRowHeight for the subsequent ImplPaintData + // (as it is based on the settings of our data window, not the foreign device) + if (!nDataRowHeight) + ImpGetDataRowHeight(); + long nHeightLogic = PixelToLogic(Size(0, nDataRowHeight), MapMode(MapUnit::Map10thMM)).Height(); + long nForeignHeightPixel = pDev->LogicToPixel(Size(0, nHeightLogic), MapMode(MapUnit::Map10thMM)).Height(); + + long nOriginalHeight = nDataRowHeight; + nDataRowHeight = nForeignHeightPixel; + + // this counts for the column widths, too + size_t nPos; + for ( nPos = 0; nPos < mvCols.size(); ++nPos ) + { + BrowserColumn* pCurrent = mvCols[ nPos ].get(); + + long nWidthLogic = PixelToLogic(Size(pCurrent->Width(), 0), MapMode(MapUnit::Map10thMM)).Width(); + long nForeignWidthPixel = pDev->LogicToPixel(Size(nWidthLogic, 0), MapMode(MapUnit::Map10thMM)).Width(); + + pCurrent->SetWidth(nForeignWidthPixel, GetZoom()); + if ( pBar ) + pBar->SetItemSize( pCurrent->GetId(), pCurrent->Width() ); + } + + // a smaller area for the content + aRealPos.AdjustX( 1 ); + aRealPos.AdjustY( 1 ); + aRealSize.AdjustWidth( -2 ); + aRealSize.AdjustHeight( -2 ); + + // let the header bar draw itself + if ( pBar ) + { + // the title height with respect to the font set for the given device + long nTitleHeight = PixelToLogic(Size(0, GetTitleHeight()), MapMode(MapUnit::Map10thMM)).Height(); + nTitleHeight = pDev->LogicToPixel(Size(0, nTitleHeight), MapMode(MapUnit::Map10thMM)).Height(); + + BrowserColumn* pFirstCol = !mvCols.empty() ? mvCols[ 0 ].get() : nullptr; + + Point aHeaderPos(pFirstCol && (pFirstCol->GetId() == 0) ? pFirstCol->Width() : 0, 0); + Size aHeaderSize(aRealSize.Width() - aHeaderPos.X(), nTitleHeight); + + aHeaderPos += aRealPos; + // do this before converting to logics ! + + // the header's draw expects logic coordinates, again + aHeaderPos = pDev->PixelToLogic(aHeaderPos); + + Size aOrigSize(pBar->GetSizePixel()); + pBar->SetSizePixel(aHeaderSize); + pBar->Draw(pDev, aHeaderPos, nFlags); + pBar->SetSizePixel(aOrigSize); + + // draw the "upper left cell" (the intersection between the header bar and the handle column) + if (pFirstCol && (pFirstCol->GetId() == 0) && (pFirstCol->Width() > 4)) + { + ButtonFrame aButtonFrame( aRealPos, + Size( pFirstCol->Width()-1, nTitleHeight-1 ), + pFirstCol->Title(), !IsEnabled()); + aButtonFrame.Draw( *pDev ); + + pDev->Push( PushFlags::LINECOLOR ); + pDev->SetLineColor( COL_BLACK ); + + pDev->DrawLine( Point( aRealPos.X(), aRealPos.Y() + nTitleHeight-1 ), + Point( aRealPos.X() + pFirstCol->Width() - 1, aRealPos.Y() + nTitleHeight-1 ) ); + pDev->DrawLine( Point( aRealPos.X() + pFirstCol->Width() - 1, aRealPos.Y() ), + Point( aRealPos.X() + pFirstCol->Width() - 1, aRealPos.Y() + nTitleHeight-1 ) ); + + pDev->Pop(); + } + + aRealPos.AdjustY(aHeaderSize.Height() ); + aRealSize.AdjustHeight( -(aHeaderSize.Height()) ); + } + + // draw our own content (with clipping) + vcl::Region aRegion(tools::Rectangle(aRealPos, aRealSize)); + pDev->SetClipRegion( pDev->PixelToLogic( aRegion ) ); + + // do we have to paint the background + bool bBackground = pDataWin->IsControlBackground(); + if ( bBackground ) + { + tools::Rectangle aRect( aRealPos, aRealSize ); + pDev->SetFillColor( pDataWin->GetControlBackground() ); + pDev->DrawRect( aRect ); + } + + ImplPaintData( *pDev, tools::Rectangle( aRealPos, aRealSize ), true ); + + // restore the column widths/data row height + nDataRowHeight = nOriginalHeight; + for ( nPos = 0; nPos < mvCols.size(); ++nPos ) + { + BrowserColumn* pCurrent = mvCols[ nPos ].get(); + + long nForeignWidthLogic = pDev->PixelToLogic(Size(pCurrent->Width(), 0), MapMode(MapUnit::Map10thMM)).Width(); + long nWidthPixel = LogicToPixel(Size(nForeignWidthLogic, 0), MapMode(MapUnit::Map10thMM)).Width(); + + pCurrent->SetWidth(nWidthPixel, GetZoom()); + if ( pBar ) + pBar->SetItemSize( pCurrent->GetId(), pCurrent->Width() ); + } + + pDev->Pop(); +} + +void BrowseBox::ImplPaintData(OutputDevice& _rOut, const tools::Rectangle& _rRect, bool _bForeignDevice) +{ + Point aOverallAreaPos = _bForeignDevice ? _rRect.TopLeft() : Point(0,0); + Size aOverallAreaSize = _bForeignDevice ? _rRect.GetSize() : pDataWin->GetOutputSizePixel(); + Point aOverallAreaBRPos = _bForeignDevice ? _rRect.BottomRight() : Point( aOverallAreaSize.Width(), aOverallAreaSize.Height() ); + + long nDataRowHeigt = GetDataRowHeight(); + + // compute relative rows to redraw + sal_uLong nRelTopRow = 0; + sal_uLong nRelBottomRow = aOverallAreaSize.Height(); + if (!_bForeignDevice && nDataRowHeigt) + { + nRelTopRow = (static_cast<sal_uLong>(_rRect.Top()) / nDataRowHeigt); + nRelBottomRow = static_cast<sal_uLong>(_rRect.Bottom()) / nDataRowHeigt; + } + + // cache frequently used values + Point aPos( aOverallAreaPos.X(), nRelTopRow * nDataRowHeigt + aOverallAreaPos.Y() ); + _rOut.SetLineColor( COL_WHITE ); + const AllSettings& rAllSets = _rOut.GetSettings(); + const StyleSettings &rSettings = rAllSets.GetStyleSettings(); + const Color &rHighlightTextColor = rSettings.GetHighlightTextColor(); + const Color &rHighlightFillColor = rSettings.GetHighlightColor(); + Color aOldTextColor = _rOut.GetTextColor(); + Color aOldFillColor = _rOut.GetFillColor(); + Color aOldLineColor = _rOut.GetLineColor(); + long nHLineX = 0 == mvCols[ 0 ]->GetId() ? mvCols[ 0 ]->Width() : 0; + nHLineX += aOverallAreaPos.X(); + + Color aDelimiterLineColor( ::svtools::ColorConfig().GetColorValue( ::svtools::CALCGRID ).nColor ); + + // redraw the invalid fields + for ( sal_uLong nRelRow = nRelTopRow; + nRelRow <= nRelBottomRow && static_cast<sal_uLong>(nTopRow)+nRelRow < o3tl::make_unsigned(nRowCount); + ++nRelRow, aPos.AdjustY(nDataRowHeigt ) ) + { + // get row + // check valid area, to be on the safe side: + DBG_ASSERT( static_cast<sal_uInt16>(nTopRow+nRelRow) < nRowCount, "BrowseBox::ImplPaintData: invalid seek" ); + if ( (nTopRow+long(nRelRow)) < 0 || static_cast<sal_uInt16>(nTopRow+nRelRow) >= nRowCount ) + continue; + + // prepare row + sal_uLong nRow = nTopRow+nRelRow; + if ( !SeekRow( nRow) ) { + OSL_FAIL("BrowseBox::ImplPaintData: SeekRow failed"); + } + _rOut.SetClipRegion(); + aPos.setX( aOverallAreaPos.X() ); + + + // #73325# don't paint the row outside the painting rectangle (DG) + // prepare auto-highlight + tools::Rectangle aRowRect( Point( _rRect.TopLeft().X(), aPos.Y() ), + Size( _rRect.GetSize().Width(), nDataRowHeigt ) ); + + bool bRowSelected = !bHideSelect + && IsRowSelected( nRow ); + if ( bRowSelected ) + { + _rOut.SetTextColor( rHighlightTextColor ); + _rOut.SetFillColor( rHighlightFillColor ); + _rOut.SetLineColor(); + _rOut.DrawRect( aRowRect ); + } + + // iterate through columns to redraw + size_t nCol; + for ( nCol = 0; nCol < mvCols.size(); ++nCol ) + { + // get column + BrowserColumn *pCol = mvCols[ nCol ].get(); + + // at end of invalid area + if ( aPos.X() >= _rRect.Right() ) + break; + + // skip invisible columns between frozen and scrollable area + if ( nCol < nFirstCol && !pCol->IsFrozen() ) + { + nCol = nFirstCol; + pCol = (nCol < mvCols.size() ) ? mvCols[ nCol ].get() : nullptr; + if (!pCol) + { // FS - 21.05.99 - 66325 + // actually this has been fixed elsewhere (in the right place), + // but let's make sure... + OSL_FAIL("BrowseBox::PaintData : nFirstCol is probably invalid !"); + break; + } + } + + // prepare Column-AutoHighlight + bool bColAutoHighlight = bColumnCursor + && IsColumnSelected( pCol->GetId() ); + if ( bColAutoHighlight ) + { + _rOut.SetClipRegion(); + _rOut.SetTextColor( rHighlightTextColor ); + _rOut.SetFillColor( rHighlightFillColor ); + _rOut.SetLineColor(); + tools::Rectangle aFieldRect( aPos, + Size( pCol->Width(), nDataRowHeigt ) ); + _rOut.DrawRect( aFieldRect ); + } + + if (!m_bFocusOnlyCursor && (pCol->GetId() == GetCurColumnId()) && (nRow == static_cast<sal_uLong>(GetCurRow()))) + DrawCursor(); + + // draw a single field. + // else something is drawn to, e.g. handle column + if (pCol->Width()) + { + // clip the column's output to the field area + if (_bForeignDevice) + { // (not necessary if painting onto the data window) + Size aFieldSize(pCol->Width(), nDataRowHeigt); + + if (aPos.X() + aFieldSize.Width() > aOverallAreaBRPos.X()) + aFieldSize.setWidth( aOverallAreaBRPos.X() - aPos.X() ); + + if (aPos.Y() + aFieldSize.Height() > aOverallAreaBRPos.Y() + 1) + { + // for non-handle cols we don't clip vertically : we just don't draw the cell if the line isn't completely visible + if (pCol->GetId() != 0) + continue; + aFieldSize.setHeight( aOverallAreaBRPos.Y() + 1 - aPos.Y() ); + } + + vcl::Region aClipToField(tools::Rectangle(aPos, aFieldSize)); + _rOut.SetClipRegion(aClipToField); + } + pCol->Draw( *this, _rOut, aPos ); + if (_bForeignDevice) + _rOut.SetClipRegion(); + } + + // reset Column-auto-highlight + if ( bColAutoHighlight ) + { + _rOut.SetTextColor( aOldTextColor ); + _rOut.SetFillColor( aOldFillColor ); + _rOut.SetLineColor( aOldLineColor ); + } + + // skip column + aPos.AdjustX(pCol->Width() ); + } + + // reset auto-highlight + if ( bRowSelected ) + { + _rOut.SetTextColor( aOldTextColor ); + _rOut.SetFillColor( aOldFillColor ); + _rOut.SetLineColor( aOldLineColor ); + } + + if ( bHLines ) + { + // draw horizontal delimitation lines + _rOut.SetClipRegion(); + _rOut.Push( PushFlags::LINECOLOR ); + _rOut.SetLineColor( aDelimiterLineColor ); + long nY = aPos.Y() + nDataRowHeigt - 1; + if (nY <= aOverallAreaBRPos.Y()) + _rOut.DrawLine( Point( nHLineX, nY ), + Point( bVLines + ? std::min(long(aPos.X() - 1), aOverallAreaBRPos.X()) + : aOverallAreaBRPos.X(), + nY ) ); + _rOut.Pop(); + } + } + + if (aPos.Y() > aOverallAreaBRPos.Y() + 1) + aPos.setY( aOverallAreaBRPos.Y() + 1 ); + // needed for some of the following drawing + + // retouching + _rOut.SetClipRegion(); + aOldLineColor = _rOut.GetLineColor(); + aOldFillColor = _rOut.GetFillColor(); + _rOut.SetFillColor( rSettings.GetFaceColor() ); + if ( !mvCols.empty() && ( mvCols[ 0 ]->GetId() == 0 ) && ( aPos.Y() <= _rRect.Bottom() ) ) + { + // fill rectangle gray below handle column + // DG: fill it only until the end of the drawing rect and not to the end, as this may overpaint handle columns + _rOut.SetLineColor( COL_BLACK ); + _rOut.DrawRect( tools::Rectangle( + Point( aOverallAreaPos.X() - 1, aPos.Y() - 1 ), + Point( aOverallAreaPos.X() + mvCols[ 0 ]->Width() - 1, + _rRect.Bottom() + 1) ) ); + } + _rOut.SetFillColor( aOldFillColor ); + + // draw vertical delimitational line between frozen and scrollable cols + _rOut.SetLineColor( COL_BLACK ); + long nFrozenWidth = GetFrozenWidth()-1; + _rOut.DrawLine( Point( aOverallAreaPos.X() + nFrozenWidth, aPos.Y() ), + Point( aOverallAreaPos.X() + nFrozenWidth, bHLines + ? aPos.Y() - 1 + : aOverallAreaBRPos.Y() ) ); + + // draw vertical delimitational lines? + if ( bVLines ) + { + _rOut.SetLineColor( aDelimiterLineColor ); + Point aVertPos( aOverallAreaPos.X() - 1, aOverallAreaPos.Y() ); + long nDeltaY = aOverallAreaBRPos.Y(); + for ( size_t nCol = 0; nCol < mvCols.size(); ++nCol ) + { + // get column + BrowserColumn *pCol = mvCols[ nCol ].get(); + + // skip invisible columns between frozen and scrollable area + if ( nCol < nFirstCol && !pCol->IsFrozen() ) + { + nCol = nFirstCol; + pCol = mvCols[ nCol ].get(); + } + + // skip column + aVertPos.AdjustX(pCol->Width() ); + + // at end of invalid area + // invalid area is first reached when X > Right + // and not >= + if ( aVertPos.X() > _rRect.Right() ) + break; + + // draw a single line + if ( pCol->GetId() != 0 ) + _rOut.DrawLine( aVertPos, Point( aVertPos.X(), + bHLines + ? aPos.Y() - 1 + : aPos.Y() + nDeltaY ) ); + } + } + + _rOut.SetLineColor( aOldLineColor ); +} + +void BrowseBox::PaintData( vcl::Window const & rWin, vcl::RenderContext& rRenderContext, const tools::Rectangle& rRect ) +{ + if (!bBootstrapped && IsReallyVisible()) + BrowseBox::StateChanged(StateChangedType::InitShow); + + // initializations + if (mvCols.empty() || !rWin.IsUpdateMode()) + return; + if (pDataWin->bResizeOnPaint) + Resize(); + // MI: who was that? Window::Update(); + + ImplPaintData(rRenderContext, rRect, false); +} + +long BrowseBox::GetBarHeight() const +{ + // tdf#115941 because some platforms have things like overlay scrollbars, take a max + // of a statusbar height and a scrollbar height as the control area height + + // (we can't ask the scrollbars for their size cause if we're zoomed they still have to be + // resized - which is done in UpdateScrollbars) + + return std::max(aStatusBar->GetSizePixel().Height(), GetSettings().GetStyleSettings().GetScrollBarSize()); +} + +void BrowseBox::UpdateScrollbars() +{ + + if ( !bBootstrapped || !IsUpdateMode() ) + return; + + // protect against recursion + if ( pDataWin->bInUpdateScrollbars ) + { + pDataWin->bHadRecursion = true; + return; + } + pDataWin->bInUpdateScrollbars = true; + + // the size of the corner window (and the width of the VSB/height of the HSB) + sal_uLong nCornerSize = GetBarHeight(); + if (IsZoom()) + nCornerSize = static_cast<sal_uLong>(nCornerSize * static_cast<double>(GetZoom())); + + bool bNeedsVScroll = false; + long nMaxRows = 0; + if (GetDataRowHeight()) + { + // needs VScroll? + nMaxRows = (pDataWin->GetSizePixel().Height()) / GetDataRowHeight(); + bNeedsVScroll = pDataWin->bAutoVScroll + ? nTopRow || ( nRowCount > nMaxRows ) + : !pDataWin->bNoVScroll; + } + Size aDataWinSize = pDataWin->GetSizePixel(); + if ( !bNeedsVScroll ) + { + if ( pVScroll->IsVisible() ) + { + pVScroll->Hide(); + Size aNewSize( aDataWinSize ); + aNewSize.setWidth( GetOutputSizePixel().Width() ); + aDataWinSize = aNewSize; + } + } + else if ( !pVScroll->IsVisible() ) + { + Size aNewSize( aDataWinSize ); + aNewSize.setWidth( GetOutputSizePixel().Width() - nCornerSize ); + aDataWinSize = aNewSize; + } + + // needs HScroll? + sal_uLong nLastCol = GetColumnAtXPosPixel( aDataWinSize.Width() - 1 ); + + sal_uInt16 nFrozenCols = FrozenColCount(); + bool bNeedsHScroll = pDataWin->bAutoHScroll + ? ( nFirstCol > nFrozenCols ) || ( nLastCol <= mvCols.size() ) + : !pDataWin->bNoHScroll; + if ( !bNeedsHScroll ) + { + if ( aHScroll->IsVisible() ) + { + aHScroll->Hide(); + } + aDataWinSize.setHeight( GetOutputSizePixel().Height() - GetTitleHeight() ); + if ( nControlAreaWidth != USHRT_MAX ) + aDataWinSize.AdjustHeight( -sal_Int32(nCornerSize) ); + } + else if ( !aHScroll->IsVisible() ) + { + Size aNewSize( aDataWinSize ); + aNewSize.setHeight( GetOutputSizePixel().Height() - GetTitleHeight() - nCornerSize ); + aDataWinSize = aNewSize; + } + + // adjust position and Width of horizontal scrollbar + sal_uLong nHScrX = nControlAreaWidth == USHRT_MAX + ? 0 + : nControlAreaWidth; + + aHScroll->SetPosSizePixel( + Point( nHScrX, GetOutputSizePixel().Height() - nCornerSize ), + Size( aDataWinSize.Width() - nHScrX, nCornerSize ) ); + + // total scrollable columns + short nScrollCols = short(mvCols.size()) - static_cast<short>(nFrozenCols); + + // visible columns + short nVisibleHSize = nLastCol == BROWSER_INVALIDID + ? static_cast<short>( mvCols.size() - nFirstCol ) + : static_cast<short>( nLastCol - nFirstCol ); + + short nRange = std::max( nScrollCols, short(0) ); + aHScroll->SetVisibleSize( nVisibleHSize ); + aHScroll->SetRange( Range( 0, nRange )); + if ( bNeedsHScroll && !aHScroll->IsVisible() ) + aHScroll->Show(); + + // adjust position and height of vertical scrollbar + pVScroll->SetPageSize( nMaxRows ); + + if ( nTopRow > nRowCount ) + { + nTopRow = nRowCount - 1; + OSL_FAIL("BrowseBox: nTopRow > nRowCount"); + } + + if ( pVScroll->GetThumbPos() != nTopRow ) + pVScroll->SetThumbPos( nTopRow ); + long nVisibleSize = std::min( std::min( nRowCount, nMaxRows ), long(nRowCount-nTopRow) ); + pVScroll->SetVisibleSize( nVisibleSize ? nVisibleSize : 1 ); + pVScroll->SetRange( Range( 0, nRowCount ) ); + pVScroll->SetPosSizePixel( + Point( aDataWinSize.Width(), GetTitleHeight() ), + Size( nCornerSize, aDataWinSize.Height()) ); + long nLclDataRowHeight = GetDataRowHeight(); + if ( nLclDataRowHeight > 0 && nRowCount < long( aDataWinSize.Height() / nLclDataRowHeight ) ) + ScrollRows( -nTopRow ); + if ( bNeedsVScroll && !pVScroll->IsVisible() ) + pVScroll->Show(); + + pDataWin->SetPosSizePixel( + Point( 0, GetTitleHeight() ), + aDataWinSize ); + + // needs corner-window? + // (do that AFTER positioning BOTH scrollbars) + sal_uLong nActualCorderWidth = 0; + if (aHScroll->IsVisible() && pVScroll && pVScroll->IsVisible() ) + { + // if we have both scrollbars, the corner window fills the point of intersection of these two + nActualCorderWidth = nCornerSize; + } + else if ( !aHScroll->IsVisible() && ( nControlAreaWidth != USHRT_MAX ) ) + { + // if we have no horizontal scrollbar, but a control area, we need the corner window to + // fill the space between the control are and the right border + nActualCorderWidth = GetOutputSizePixel().Width() - nControlAreaWidth; + } + if ( nActualCorderWidth ) + { + if ( !pDataWin->pCornerWin ) + pDataWin->pCornerWin = VclPtr<ScrollBarBox>::Create( this, 0 ); + pDataWin->pCornerWin->SetPosSizePixel( + Point( GetOutputSizePixel().Width() - nActualCorderWidth, aHScroll->GetPosPixel().Y() ), + Size( nActualCorderWidth, nCornerSize ) ); + pDataWin->pCornerWin->Show(); + } + else + pDataWin->pCornerWin.disposeAndClear(); + + // scroll headerbar, if necessary + if ( pDataWin->pHeaderBar ) + { + long nWidth = 0; + for ( size_t nCol = 0; + nCol < mvCols.size() && nCol < nFirstCol; + ++nCol ) + { + // not the handle column + if ( mvCols[ nCol ]->GetId() ) + nWidth += mvCols[ nCol ]->Width(); + } + + pDataWin->pHeaderBar->SetOffset( nWidth ); + } + + pDataWin->bInUpdateScrollbars = false; + if ( pDataWin->bHadRecursion ) + { + pDataWin->bHadRecursion = false; + UpdateScrollbars(); + } +} + + +void BrowseBox::SetUpdateMode( bool bUpdate ) +{ + + bool bWasUpdate = IsUpdateMode(); + if ( bWasUpdate == bUpdate ) + return; + + Control::SetUpdateMode( bUpdate ); + // If WB_CLIPCHILDREN is st at the BrowseBox (to minimize flicker), + // the data window is not invalidated by SetUpdateMode. + if( bUpdate ) + pDataWin->Invalidate(); + pDataWin->SetUpdateMode( bUpdate ); + + + if ( bUpdate ) + { + if ( bBootstrapped ) + { + UpdateScrollbars(); + AutoSizeLastColumn(); + } + DoShowCursor( "SetUpdateMode" ); + } + else + DoHideCursor( "SetUpdateMode" ); +} + + +bool BrowseBox::GetUpdateMode() const +{ + + return pDataWin->IsUpdateMode(); +} + + +long BrowseBox::GetFrozenWidth() const +{ + + long nWidth = 0; + for ( size_t nCol = 0; + nCol < mvCols.size() && mvCols[ nCol ]->IsFrozen(); + ++nCol ) + nWidth += mvCols[ nCol ]->Width(); + return nWidth; +} + + +void BrowseBox::ColumnInserted( sal_uInt16 nPos ) +{ + if ( pColSel ) + pColSel->Insert( nPos ); + UpdateScrollbars(); +} + + +sal_uInt16 BrowseBox::FrozenColCount() const +{ + std::size_t nCol; + for ( nCol = 0; + nCol < mvCols.size() && mvCols[ nCol ]->IsFrozen(); + ++nCol ) + /* empty loop */; + return nCol; //TODO: BrowserColumns::size_type -> sal_uInt16! +} + + +IMPL_LINK(BrowseBox, ScrollHdl, ScrollBar*, pBar, void) +{ + if ( pBar->GetDelta() == 0 ) + return; + + if ( pBar == aHScroll.get() ) + ScrollColumns( aHScroll->GetDelta() ); + if ( pBar == pVScroll ) + ScrollRows( pVScroll->GetDelta() ); +} + + +IMPL_LINK( BrowseBox, StartDragHdl, HeaderBar*, pBar, void ) +{ + pBar->SetDragSize( pDataWin->GetOutputSizePixel().Height() ); +} + + +// usually only the first column was resized + +void BrowseBox::MouseButtonDown( const MouseEvent& rEvt ) +{ + + GrabFocus(); + + // only mouse events in the title-line are supported + const Point &rEvtPos = rEvt.GetPosPixel(); + if ( rEvtPos.Y() >= GetTitleHeight() ) + return; + + long nX = 0; + long nWidth = GetOutputSizePixel().Width(); + for ( size_t nCol = 0; nCol < mvCols.size() && nX < nWidth; ++nCol ) + { + // is this column visible? + BrowserColumn *pCol = mvCols[ nCol ].get(); + if ( pCol->IsFrozen() || nCol >= nFirstCol ) + { + // compute right end of column + long nR = nX + pCol->Width() - 1; + + // at the end of a column (and not handle column)? + if ( pCol->GetId() && std::abs( nR - rEvtPos.X() ) < 2 ) + { + // start resizing the column + bResizing = true; + nResizeCol = nCol; + nDragX = nResizeX = rEvtPos.X(); + SetPointer( PointerStyle::HSplit ); + CaptureMouse(); + pDataWin->DrawLine( Point( nDragX, 0 ), + Point( nDragX, pDataWin->GetSizePixel().Height() ) ); + nMinResizeX = nX + MIN_COLUMNWIDTH; + return; + } + else if ( nX < rEvtPos.X() && nR > rEvtPos.X() ) + { + MouseButtonDown( BrowserMouseEvent( + this, rEvt, -1, nCol, pCol->GetId(), tools::Rectangle() ) ); + return; + } + nX = nR + 1; + } + } + + // event occurred out of data area + if ( rEvt.IsRight() ) + pDataWin->Command( + CommandEvent( Point( 1, LONG_MAX ), CommandEventId::ContextMenu, true ) ); + else + SetNoSelection(); +} + + +void BrowseBox::MouseMove( const MouseEvent& rEvt ) +{ + SAL_INFO("svtools", "BrowseBox::MouseMove( MouseEvent )" ); + + PointerStyle aNewPointer = PointerStyle::Arrow; + + sal_uInt16 nX = 0; + for ( size_t nCol = 0; + nCol < mvCols.size() && + ( nX + mvCols[ nCol ]->Width() ) < o3tl::make_unsigned(GetOutputSizePixel().Width()); + ++nCol ) + // is this column visible? + if ( mvCols[ nCol ]->IsFrozen() || nCol >= nFirstCol ) + { + // compute right end of column + BrowserColumn *pCol = mvCols[ nCol ].get(); + sal_uInt16 nR = static_cast<sal_uInt16>(nX + pCol->Width() - 1); + + // show resize-pointer? + if ( bResizing || ( pCol->GetId() && + std::abs( static_cast<long>(nR) - rEvt.GetPosPixel().X() ) < MIN_COLUMNWIDTH ) ) + { + aNewPointer = PointerStyle::HSplit; + if ( bResizing ) + { + // delete old auxiliary line + pDataWin->HideTracking() ; + + // check allowed width and new delta + nDragX = std::max( rEvt.GetPosPixel().X(), nMinResizeX ); + long nDeltaX = nDragX - nResizeX; + sal_uInt16 nId = GetColumnId(nResizeCol); + sal_uLong nOldWidth = GetColumnWidth(nId); + nDragX = nOldWidth + nDeltaX + nResizeX - nOldWidth; + + // draw new auxiliary line + pDataWin->ShowTracking( tools::Rectangle( Point( nDragX, 0 ), + Size( 1, pDataWin->GetSizePixel().Height() ) ), + ShowTrackFlags::Split|ShowTrackFlags::TrackWindow ); + } + + } + + nX = nR + 1; + } + + SetPointer( aNewPointer ); +} + + +void BrowseBox::MouseButtonUp( const MouseEvent & rEvt ) +{ + + if ( bResizing ) + { + // delete auxiliary line + pDataWin->HideTracking(); + + // width changed? + nDragX = std::max( rEvt.GetPosPixel().X(), nMinResizeX ); + if ( (nDragX - nResizeX) != static_cast<long>(mvCols[ nResizeCol ]->Width()) ) + { + // resize column + long nMaxX = pDataWin->GetSizePixel().Width(); + nDragX = std::min( nDragX, nMaxX ); + long nDeltaX = nDragX - nResizeX; + sal_uInt16 nId = GetColumnId(nResizeCol); + SetColumnWidth( GetColumnId(nResizeCol), GetColumnWidth(nId) + nDeltaX ); + ColumnResized( nId ); + } + + // end action + SetPointer( PointerStyle::Arrow ); + ReleaseMouse(); + bResizing = false; + } + else + MouseButtonUp( BrowserMouseEvent( pDataWin, + MouseEvent( Point( rEvt.GetPosPixel().X(), + rEvt.GetPosPixel().Y() - pDataWin->GetPosPixel().Y() ), + rEvt.GetClicks(), rEvt.GetMode(), rEvt.GetButtons(), + rEvt.GetModifier() ) ) ); +} + + +static bool bExtendedMode = false; +static bool bFieldMode = false; + +void BrowseBox::MouseButtonDown( const BrowserMouseEvent& rEvt ) +{ + + GrabFocus(); + + // adjust selection while and after double-click + if ( rEvt.GetClicks() == 2 ) + { + SetNoSelection(); + if ( rEvt.GetRow() >= 0 ) + { + GoToRow( rEvt.GetRow() ); + SelectRow( rEvt.GetRow(), true, false ); + } + else + { + if ( bColumnCursor && rEvt.GetColumn() != 0 ) + { + if ( rEvt.GetColumn() < mvCols.size() ) + SelectColumnPos( rEvt.GetColumn(), true, false); + } + } + DoubleClick( rEvt ); + } + // selections + else if ( ( rEvt.GetMode() & ( MouseEventModifiers::SELECT | MouseEventModifiers::SIMPLECLICK ) ) && + ( bColumnCursor || rEvt.GetRow() >= 0 ) ) + { + if ( rEvt.GetClicks() == 1 ) + { + // initialise flags + bHit = false; + + // selection out of range? + if ( rEvt.GetRow() >= nRowCount || + rEvt.GetColumnId() == BROWSER_INVALIDID ) + { + SetNoSelection(); + return; + } + + // while selecting, no cursor + bSelecting = true; + DoHideCursor( "MouseButtonDown" ); + + // DataRow? + if ( rEvt.GetRow() >= 0 ) + { + // line selection? + if ( rEvt.GetColumnId() == HandleColumnId || !bColumnCursor ) + { + if ( bMultiSelection ) + { + // remove column-selection, if exists + if ( pColSel && pColSel->GetSelectCount() ) + { + ToggleSelection(); + if ( bMultiSelection ) + uRow.pSel->SelectAll(false); + else + uRow.nSel = BROWSER_ENDOFSELECTION; + if ( pColSel ) + pColSel->SelectAll(false); + bSelect = true; + } + + // expanding mode? + if ( rEvt.GetMode() & MouseEventModifiers::RANGESELECT ) + { + // select the further touched rows too + bSelect = true; + ExpandRowSelection( rEvt ); + return; + } + + // click in the selected area? + else if ( IsRowSelected( rEvt.GetRow() ) ) + { + // wait for Drag&Drop + bHit = true; + bExtendedMode = bool( rEvt.GetMode() & MouseEventModifiers::MULTISELECT ); + return; + } + + // extension mode? + else if ( rEvt.GetMode() & MouseEventModifiers::MULTISELECT ) + { + // determine the new selection range + // and selection/deselection + aSelRange = Range( rEvt.GetRow(), rEvt.GetRow() ); + SelectRow( rEvt.GetRow(), + !uRow.pSel->IsSelected( rEvt.GetRow() ) ); + bSelect = true; + return; + } + } + + // select directly + SetNoSelection(); + GoToRow( rEvt.GetRow() ); + SelectRow( rEvt.GetRow() ); + aSelRange = Range( rEvt.GetRow(), rEvt.GetRow() ); + bSelect = true; + } + else // Column/Field-Selection + { + // click in selected column + if ( IsColumnSelected( rEvt.GetColumn() ) || + IsRowSelected( rEvt.GetRow() ) ) + { + bHit = true; + bFieldMode = true; + return; + } + + SetNoSelection(); + GoToRowColumnId( rEvt.GetRow(), rEvt.GetColumnId() ); + bSelect = true; + } + } + else + { + if ( bMultiSelection && rEvt.GetColumnId() == HandleColumnId ) + { + // toggle all-selection + if ( uRow.pSel->GetSelectCount() > ( GetRowCount() / 2 ) ) + SetNoSelection(); + else + SelectAll(); + } + else + SelectColumnPos( GetColumnPos(rEvt.GetColumnId()), true, false); + } + + // turn cursor on again, if necessary + bSelecting = false; + DoShowCursor( "MouseButtonDown" ); + if ( bSelect ) + Select(); + } + } +} + + +void BrowseBox::MouseButtonUp( const BrowserMouseEvent &rEvt ) +{ + + // D&D was possible, but did not occur + if ( bHit ) + { + aSelRange = Range( rEvt.GetRow(), rEvt.GetRow() ); + if ( bExtendedMode ) + SelectRow( rEvt.GetRow(), false ); + else + { + SetNoSelection(); + if ( bFieldMode ) + GoToRowColumnId( rEvt.GetRow(), rEvt.GetColumnId() ); + else + { + GoToRow( rEvt.GetRow() ); + SelectRow( rEvt.GetRow() ); + } + } + bSelect = true; + bExtendedMode = false; + bFieldMode = false; + bHit = false; + } + + // activate cursor + if ( bSelecting ) + { + bSelecting = false; + DoShowCursor( "MouseButtonUp" ); + if ( bSelect ) + Select(); + } +} + + +void BrowseBox::KeyInput( const KeyEvent& rEvt ) +{ + if ( !ProcessKey( rEvt ) ) + Control::KeyInput( rEvt ); +} + + +bool BrowseBox::ProcessKey( const KeyEvent& rEvt ) +{ + + sal_uInt16 nCode = rEvt.GetKeyCode().GetCode(); + bool bShift = rEvt.GetKeyCode().IsShift(); + bool bCtrl = rEvt.GetKeyCode().IsMod1(); + bool bAlt = rEvt.GetKeyCode().IsMod2(); + + sal_uInt16 nId = BROWSER_NONE; + + if ( !bAlt && !bCtrl && !bShift ) + { + switch ( nCode ) + { + case KEY_DOWN: nId = BROWSER_CURSORDOWN; break; + case KEY_UP: nId = BROWSER_CURSORUP; break; + case KEY_HOME: nId = BROWSER_CURSORHOME; break; + case KEY_END: nId = BROWSER_CURSOREND; break; + case KEY_TAB: + if ( !bColumnCursor ) + break; + [[fallthrough]]; + case KEY_RIGHT: nId = BROWSER_CURSORRIGHT; break; + case KEY_LEFT: nId = BROWSER_CURSORLEFT; break; + case KEY_SPACE: nId = BROWSER_SELECT; break; + } + if ( BROWSER_NONE != nId ) + SetNoSelection(); + + switch ( nCode ) + { + case KEY_PAGEDOWN: nId = BROWSER_CURSORPAGEDOWN; break; + case KEY_PAGEUP: nId = BROWSER_CURSORPAGEUP; break; + } + } + + if ( !bAlt && !bCtrl && bShift ) + switch ( nCode ) + { + case KEY_DOWN: nId = BROWSER_SELECTDOWN; break; + case KEY_UP: nId = BROWSER_SELECTUP; break; + case KEY_TAB: + if ( !bColumnCursor ) + break; + nId = BROWSER_CURSORLEFT; break; + case KEY_HOME: nId = BROWSER_SELECTHOME; break; + case KEY_END: nId = BROWSER_SELECTEND; break; + } + + + if ( !bAlt && bCtrl && !bShift ) + switch ( nCode ) + { + case KEY_DOWN: nId = BROWSER_CURSORDOWN; break; + case KEY_UP: nId = BROWSER_CURSORUP; break; + case KEY_PAGEDOWN: nId = BROWSER_CURSORENDOFFILE; break; + case KEY_PAGEUP: nId = BROWSER_CURSORTOPOFFILE; break; + case KEY_HOME: nId = BROWSER_CURSORTOPOFSCREEN; break; + case KEY_END: nId = BROWSER_CURSORENDOFSCREEN; break; + case KEY_SPACE: nId = BROWSER_ENHANCESELECTION; break; + case KEY_LEFT: nId = BROWSER_MOVECOLUMNLEFT; break; + case KEY_RIGHT: nId = BROWSER_MOVECOLUMNRIGHT; break; + } + + if ( nId != BROWSER_NONE ) + Dispatch( nId ); + return nId != BROWSER_NONE; +} + + +void BrowseBox::Dispatch( sal_uInt16 nId ) +{ + + long nRowsOnPage = pDataWin->GetSizePixel().Height() / GetDataRowHeight(); + + switch ( nId ) + { + case BROWSER_SELECTCOLUMN: + if ( ColCount() ) + SelectColumnId( GetCurColumnId() ); + break; + + case BROWSER_CURSORDOWN: + if ( ( GetCurRow() + 1 ) < nRowCount ) + GoToRow( GetCurRow() + 1, false ); + break; + case BROWSER_CURSORUP: + if ( GetCurRow() > 0 ) + GoToRow( GetCurRow() - 1, false ); + break; + case BROWSER_SELECTHOME: + if ( GetRowCount() ) + { + DoHideCursor( "BROWSER_SELECTHOME" ); + for ( long nRow = GetCurRow(); nRow >= 0; --nRow ) + SelectRow( nRow ); + GoToRow( 0, true ); + DoShowCursor( "BROWSER_SELECTHOME" ); + } + break; + case BROWSER_SELECTEND: + if ( GetRowCount() ) + { + DoHideCursor( "BROWSER_SELECTEND" ); + long nRows = GetRowCount(); + for ( long nRow = GetCurRow(); nRow < nRows; ++nRow ) + SelectRow( nRow ); + GoToRow( GetRowCount() - 1, true ); + DoShowCursor( "BROWSER_SELECTEND" ); + } + break; + case BROWSER_SELECTDOWN: + { + if ( GetRowCount() && ( GetCurRow() + 1 ) < nRowCount ) + { + // deselect the current row, if it isn't the first + // and there is no other selected row above + long nRow = GetCurRow(); + bool bLocalSelect = ( !IsRowSelected( nRow ) || + GetSelectRowCount() == 1 || IsRowSelected( nRow - 1 ) ); + SelectRow( nRow, bLocalSelect ); + bool bDone = GoToRow( GetCurRow() + 1, false ); + if ( bDone ) + SelectRow( GetCurRow() ); + } + else + ScrollRows( 1 ); + break; + } + case BROWSER_SELECTUP: + if ( GetRowCount() ) + { + // deselect the current row, if it isn't the first + // and there is no other selected row under + long nRow = GetCurRow(); + bool bLocalSelect = ( !IsRowSelected( nRow ) || + GetSelectRowCount() == 1 || IsRowSelected( nRow + 1 ) ); + SelectRow( nCurRow, bLocalSelect ); + bool bDone = GoToRow( nRow - 1, false ); + if ( bDone ) + SelectRow( GetCurRow() ); + } + break; + case BROWSER_CURSORPAGEDOWN: + ScrollRows( nRowsOnPage ); + break; + case BROWSER_CURSORPAGEUP: + ScrollRows( -nRowsOnPage ); + break; + case BROWSER_CURSOREND: + if ( bColumnCursor ) + { + sal_uInt16 nNewId = GetColumnId(ColCount() -1); + nNewId != HandleColumnId && GoToColumnId( nNewId ); + break; + } + [[fallthrough]]; + case BROWSER_CURSORENDOFFILE: + GoToRow( nRowCount - 1, false ); + break; + case BROWSER_CURSORRIGHT: + if ( bColumnCursor ) + { + sal_uInt16 nNewPos = GetColumnPos( GetCurColumnId() ) + 1; + sal_uInt16 nNewId = GetColumnId( nNewPos ); + if (nNewId != BROWSER_INVALIDID) // At end of row ? + GoToColumnId( nNewId ); + else + { + sal_uInt16 nColId = GetColumnId(0); + if ( nColId == BROWSER_INVALIDID || nColId == HandleColumnId ) + nColId = GetColumnId(1); + if ( GetRowCount() ) + { + if ( nCurRow < GetRowCount() - 1 ) + { + GoToRowColumnId( nCurRow + 1, nColId ); + } + } + else if ( ColCount() ) + GoToColumnId( nColId ); + } + } + else + ScrollColumns( 1 ); + break; + case BROWSER_CURSORHOME: + if ( bColumnCursor ) + { + sal_uInt16 nNewId = GetColumnId(1); + if (nNewId != HandleColumnId) + { + GoToColumnId( nNewId ); + } + break; + } + [[fallthrough]]; + case BROWSER_CURSORTOPOFFILE: + GoToRow( 0, false ); + break; + case BROWSER_CURSORLEFT: + if ( bColumnCursor ) + { + sal_uInt16 nNewPos = GetColumnPos( GetCurColumnId() ) - 1; + sal_uInt16 nNewId = GetColumnId( nNewPos ); + if (nNewId != HandleColumnId) + GoToColumnId( nNewId ); + else + { + if ( GetRowCount() ) + { + if (nCurRow > 0) + { + GoToRowColumnId(nCurRow - 1, GetColumnId(ColCount() -1)); + } + } + else if ( ColCount() ) + GoToColumnId( GetColumnId(ColCount() -1) ); + } + } + else + ScrollColumns( -1 ); + break; + case BROWSER_ENHANCESELECTION: + if ( GetRowCount() ) + SelectRow( GetCurRow(), !IsRowSelected( GetCurRow() ) ); + break; + case BROWSER_SELECT: + if ( GetRowCount() ) + SelectRow( GetCurRow(), !IsRowSelected( GetCurRow() ), false ); + break; + case BROWSER_MOVECOLUMNLEFT: + case BROWSER_MOVECOLUMNRIGHT: + { // check if column moving is allowed + BrowserHeader* pHeaderBar = pDataWin->pHeaderBar; + if ( pHeaderBar && pHeaderBar->IsDragable() ) + { + sal_uInt16 nColId = GetCurColumnId(); + bool bColumnSelected = IsColumnSelected(nColId); + sal_uInt16 nNewPos = GetColumnPos(nColId); + bool bMoveAllowed = false; + if ( BROWSER_MOVECOLUMNLEFT == nId && nNewPos > 1 ) + { + --nNewPos; + bMoveAllowed = true; + } + else if ( BROWSER_MOVECOLUMNRIGHT == nId && nNewPos < (ColCount()-1) ) + { + ++nNewPos; + bMoveAllowed = true; + } + + if ( bMoveAllowed ) + { + SetColumnPos( nColId, nNewPos ); + ColumnMoved( nColId ); + MakeFieldVisible(GetCurRow(), nColId); + if ( bColumnSelected ) + SelectColumnId(nColId); + } + } + } + break; + } +} + + +void BrowseBox::SetCursorColor(const Color& _rCol) +{ + if (_rCol == m_aCursorColor) + return; + + // ensure the cursor is hidden + DoHideCursor("SetCursorColor"); + if (!m_bFocusOnlyCursor) + DoHideCursor("SetCursorColor - force"); + + m_aCursorColor = _rCol; + + if (!m_bFocusOnlyCursor) + DoShowCursor("SetCursorColor - force"); + DoShowCursor("SetCursorColor"); +} + +tools::Rectangle BrowseBox::calcHeaderRect(bool _bIsColumnBar, bool _bOnScreen) +{ + vcl::Window* pParent = nullptr; + if ( !_bOnScreen ) + pParent = GetAccessibleParentWindow(); + + Point aTopLeft; + long nWidth; + long nHeight; + if ( _bIsColumnBar ) + { + nWidth = pDataWin->GetOutputSizePixel().Width(); + nHeight = GetDataRowHeight(); + } + else + { + aTopLeft.setY( GetDataRowHeight() ); + nWidth = GetColumnWidth(0); + nHeight = GetWindowExtentsRelative( pParent ).GetHeight() - aTopLeft.Y() - GetControlArea().GetSize().Height(); + } + aTopLeft += GetWindowExtentsRelative( pParent ).TopLeft(); + return tools::Rectangle(aTopLeft,Size(nWidth,nHeight)); +} + +tools::Rectangle BrowseBox::calcTableRect(bool _bOnScreen) +{ + vcl::Window* pParent = nullptr; + if ( !_bOnScreen ) + pParent = GetAccessibleParentWindow(); + + tools::Rectangle aRect( GetWindowExtentsRelative( pParent ) ); + tools::Rectangle aRowBar = calcHeaderRect(false, pParent == nullptr); + + long nX = aRowBar.Right() - aRect.Left(); + long nY = aRowBar.Top() - aRect.Top(); + Size aSize(aRect.GetSize()); + + return tools::Rectangle(aRowBar.TopRight(), Size(aSize.Width() - nX, aSize.Height() - nY - GetBarHeight()) ); +} + +tools::Rectangle BrowseBox::GetFieldRectPixelAbs( sal_Int32 _nRowId, sal_uInt16 _nColId, bool /*_bIsHeader*/, bool _bOnScreen ) +{ + vcl::Window* pParent = nullptr; + if ( !_bOnScreen ) + pParent = GetAccessibleParentWindow(); + + tools::Rectangle aRect = GetFieldRectPixel(_nRowId,_nColId,_bOnScreen); + + Point aTopLeft = aRect.TopLeft(); + aTopLeft += GetWindowExtentsRelative( pParent ).TopLeft(); + + return tools::Rectangle(aTopLeft,aRect.GetSize()); +} + +// ------------------------------------------------------------------------- EOF + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/brwbox/brwbox3.cxx b/svtools/source/brwbox/brwbox3.cxx new file mode 100644 index 000000000..0c4f60316 --- /dev/null +++ b/svtools/source/brwbox/brwbox3.cxx @@ -0,0 +1,559 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <svtools/brwbox.hxx> +#include <vcl/AccessibleBrowseBoxObjType.hxx> +#include <vcl/accessiblefactory.hxx> +#include <unotools/accessiblestatesethelper.hxx> +#include <sal/log.hxx> +#include <tools/debug.hxx> +#include <tools/multisel.hxx> +#include "brwimpl.hxx" +#include <com/sun/star/accessibility/AccessibleStateType.hpp> + +// Accessibility ============================================================== + +using namespace ::com::sun::star::uno; +using ::com::sun::star::accessibility::XAccessible; +using namespace ::com::sun::star::accessibility; + + +namespace svt +{ + using namespace ::com::sun::star::lang; + using namespace utl; + + static Reference< XAccessible > getHeaderCell( BrowseBoxImpl::THeaderCellMap& _raHeaderCells, + sal_Int32 _nPos, + vcl::AccessibleBrowseBoxObjType _eType, + const Reference< XAccessible >& _rParent, + BrowseBox& _rBrowseBox, + vcl::IAccessibleFactory const & rFactory + ) + { + Reference< XAccessible > xRet; + BrowseBoxImpl::THeaderCellMap::iterator aFind = _raHeaderCells.find( _nPos ); + if ( aFind == _raHeaderCells.end() ) + { + Reference< XAccessible > xAccessible = rFactory.createAccessibleBrowseBoxHeaderCell( + _nPos, + _rParent, + _rBrowseBox, + nullptr, + _eType + ); + aFind = _raHeaderCells.emplace( _nPos, xAccessible ).first; + } + if ( aFind != _raHeaderCells.end() ) + xRet = aFind->second; + return xRet; + } + + + Reference< XAccessible > BrowseBoxImpl::getAccessibleHeaderBar( vcl::AccessibleBrowseBoxObjType _eObjType ) + { + if ( m_pAccessible && m_pAccessible->isAlive() ) + return m_pAccessible->getHeaderBar( _eObjType ); + return nullptr; + } + + + Reference< XAccessible > BrowseBoxImpl::getAccessibleTable( ) + { + if ( m_pAccessible && m_pAccessible->isAlive() ) + return m_pAccessible->getTable( ); + return nullptr; + } +} + + +Reference< XAccessible > BrowseBox::CreateAccessible() +{ + vcl::Window* pParent = GetAccessibleParentWindow(); + DBG_ASSERT( pParent, "BrowseBox::CreateAccessible - parent not found" ); + + if( pParent && !m_pImpl->m_pAccessible) + { + Reference< XAccessible > xAccParent = pParent->GetAccessible(); + if( xAccParent.is() ) + { + m_pImpl->m_pAccessible = getAccessibleFactory().createAccessibleBrowseBox( + xAccParent, *this + ); + } + } + + Reference< XAccessible > xAccessible; + if ( m_pImpl->m_pAccessible ) + xAccessible = m_pImpl->m_pAccessible->getMyself(); + + return xAccessible; +} + + +// Children ------------------------------------------------------------------- + +Reference< XAccessible > BrowseBox::CreateAccessibleCell( sal_Int32 _nRow, sal_uInt16 _nColumnPos ) +{ + // BBINDEX_TABLE must be the table + OSL_ENSURE(m_pImpl->m_pAccessible,"Invalid call: Accessible is null"); + + return m_pImpl->m_aFactoryAccess.getFactory().createAccessibleBrowseBoxTableCell( + m_pImpl->getAccessibleTable(), + *this, + nullptr, + _nRow, + _nColumnPos, + OFFSET_DEFAULT + ); +} + + +Reference< XAccessible > BrowseBox::CreateAccessibleRowHeader( sal_Int32 _nRow ) +{ + return svt::getHeaderCell( + m_pImpl->m_aRowHeaderCellMap, + _nRow, + vcl::BBTYPE_ROWHEADERCELL, + m_pImpl->getAccessibleHeaderBar(vcl::BBTYPE_ROWHEADERBAR), + *this, + m_pImpl->m_aFactoryAccess.getFactory() + ); +} + + +Reference< XAccessible > BrowseBox::CreateAccessibleColumnHeader( sal_uInt16 _nColumnPos ) +{ + return svt::getHeaderCell( + m_pImpl->m_aColHeaderCellMap, + _nColumnPos, + vcl::BBTYPE_COLUMNHEADERCELL, + m_pImpl->getAccessibleHeaderBar(vcl::BBTYPE_COLUMNHEADERBAR), + *this, + m_pImpl->m_aFactoryAccess.getFactory() + ); +} + + +sal_Int32 BrowseBox::GetAccessibleControlCount() const +{ + return 0; +} + + +Reference< XAccessible > BrowseBox::CreateAccessibleControl( sal_Int32 ) +{ + SAL_WARN( "svtools", "BrowseBox::CreateAccessibleControl: to be overwritten!" ); + return nullptr; +} + + +// Conversions ---------------------------------------------------------------- + +bool BrowseBox::ConvertPointToCellAddress( + sal_Int32& rnRow, sal_uInt16& rnColumnPos, const Point& rPoint ) +{ + //! TODO has to be checked + rnRow = GetRowAtYPosPixel(rPoint.Y()); + rnColumnPos = GetColumnAtXPosPixel(rPoint.X()); + return rnRow != BROWSER_INVALIDID && rnColumnPos != BROWSER_INVALIDID; +} + + +bool BrowseBox::ConvertPointToRowHeader( sal_Int32& rnRow, const Point& rPoint ) +{ + rnRow = GetRowAtYPosPixel(rPoint.Y()); + // sal_uInt16 nColumnId = GetColumnAtXPosPixel(rPoint.X()); + return rnRow != BROWSER_INVALIDID;// && nColumnId == 0; +} + + +bool BrowseBox::ConvertPointToColumnHeader( sal_uInt16& _rnColumnPos, const Point& _rPoint ) +{ + _rnColumnPos = GetColumnAtXPosPixel(_rPoint.X()); + return _rnColumnPos != BROWSER_INVALIDID; +} + + +bool BrowseBox::ConvertPointToControlIndex( sal_Int32& _rnIndex, const Point& _rPoint ) +{ + //! TODO has to be checked + sal_Int32 nRow = 0; + sal_uInt16 nColumn = 0; + bool bRet = ConvertPointToCellAddress(nRow,nColumn,_rPoint); + if ( bRet ) + _rnIndex = nRow * ColCount() + nColumn; + + return bRet; +} + + +// Object data and state ------------------------------------------------------ + +OUString BrowseBox::GetAccessibleObjectName( ::vcl::AccessibleBrowseBoxObjType eObjType,sal_Int32 _nPosition) const +{ + OUString aRetText; + switch( eObjType ) + { + case ::vcl::BBTYPE_BROWSEBOX: + aRetText = "BrowseBox"; + break; + case ::vcl::BBTYPE_TABLE: + aRetText = "Table"; + break; + case ::vcl::BBTYPE_ROWHEADERBAR: + aRetText = "RowHeaderBar"; + break; + case ::vcl::BBTYPE_COLUMNHEADERBAR: + aRetText = "ColumnHeaderBar"; + break; + case ::vcl::BBTYPE_TABLECELL: + if( ColCount() !=0 && GetRowCount()!=0) + { + + sal_Int32 columnId = _nPosition % ColCount() +1; + aRetText = GetColumnDescription( sal_Int16( columnId ) ); + sal_Int32 rowId = _nPosition / GetRowCount() + 1; + aRetText += OUString::number(rowId); + } + else + aRetText = "TableCell"; +#if OSL_DEBUG_LEVEL > 0 + aRetText += " [" + + OUString::number(sal_Int32(GetCurRow())) + + "," + + OUString::number(sal_Int32(GetCurColumnId())) + + "]"; +#endif + break; + case ::vcl::BBTYPE_ROWHEADERCELL: + { + sal_Int32 rowId = _nPosition + 1; + aRetText = OUString::number( rowId ); + } +#if OSL_DEBUG_LEVEL > 0 + aRetText += " [" + + OUString::number(sal_Int32(GetCurRow())) + + "," + + OUString::number(sal_Int32(GetCurColumnId())) + + "]"; +#endif + break; + case ::vcl::BBTYPE_COLUMNHEADERCELL: + aRetText = GetColumnDescription( sal_Int16( _nPosition ) ); +#if OSL_DEBUG_LEVEL > 0 + aRetText += " [" + + OUString::number(sal_Int32(GetCurRow())) + + "," + + OUString::number(sal_Int32(GetCurColumnId())) + + "]"; +#endif + break; + default: + OSL_FAIL("BrowseBox::GetAccessibleName: invalid enum!"); + } + return aRetText; +} + + +OUString BrowseBox::GetAccessibleObjectDescription( ::vcl::AccessibleBrowseBoxObjType eObjType,sal_Int32 ) const +{ + OUString aRetText; + switch( eObjType ) + { + case ::vcl::BBTYPE_BROWSEBOX: + aRetText = "BrowseBox description"; + break; + case ::vcl::BBTYPE_TABLE: + // aRetText = "TABLE description"; + break; + case ::vcl::BBTYPE_ROWHEADERBAR: + // aRetText = "ROWHEADERBAR description"; + break; + case ::vcl::BBTYPE_COLUMNHEADERBAR: + // aRetText = "COLUMNHEADERBAR description"; + break; + case ::vcl::BBTYPE_TABLECELL: + // aRetText = "TABLECELL description"; + break; + case ::vcl::BBTYPE_ROWHEADERCELL: + // aRetText = "ROWHEADERCELL description"; + break; + case ::vcl::BBTYPE_COLUMNHEADERCELL: + // aRetText = "COLUMNHEADERCELL description"; + break; + case ::vcl::BBTYPE_CHECKBOXCELL: + break; + } + return aRetText; +} + + +OUString BrowseBox::GetRowDescription( sal_Int32 ) const +{ + return OUString(); +} + + +OUString BrowseBox::GetColumnDescription( sal_uInt16 _nColumn ) const +{ + return GetColumnTitle( GetColumnId( _nColumn ) ); +} + + +void BrowseBox::FillAccessibleStateSet( + ::utl::AccessibleStateSetHelper& rStateSet, + ::vcl::AccessibleBrowseBoxObjType eObjType ) const +{ + switch( eObjType ) + { + case ::vcl::BBTYPE_BROWSEBOX: + case ::vcl::BBTYPE_TABLE: + + rStateSet.AddState( AccessibleStateType::FOCUSABLE ); + if ( HasFocus() ) + rStateSet.AddState( AccessibleStateType::FOCUSED ); + if ( IsActive() ) + rStateSet.AddState( AccessibleStateType::ACTIVE ); + if ( GetUpdateMode() ) + rStateSet.AddState( AccessibleStateType::EDITABLE ); + if ( IsEnabled() ) + { + rStateSet.AddState( AccessibleStateType::ENABLED ); + rStateSet.AddState( AccessibleStateType::SENSITIVE ); + } + if ( IsReallyVisible() ) + rStateSet.AddState( AccessibleStateType::VISIBLE ); + if ( eObjType == ::vcl::BBTYPE_TABLE ) + rStateSet.AddState( AccessibleStateType::MANAGES_DESCENDANTS ); + + break; + case ::vcl::BBTYPE_ROWHEADERBAR: + rStateSet.AddState( AccessibleStateType::FOCUSABLE ); + rStateSet.AddState( AccessibleStateType::VISIBLE ); + if ( GetSelectRowCount() ) + rStateSet.AddState( AccessibleStateType::FOCUSED ); + rStateSet.AddState( AccessibleStateType::MANAGES_DESCENDANTS ); + break; + case ::vcl::BBTYPE_COLUMNHEADERBAR: + rStateSet.AddState( AccessibleStateType::FOCUSABLE ); + rStateSet.AddState( AccessibleStateType::VISIBLE ); + if ( GetSelectColumnCount() ) + rStateSet.AddState( AccessibleStateType::FOCUSED ); + rStateSet.AddState( AccessibleStateType::MANAGES_DESCENDANTS ); + break; + case ::vcl::BBTYPE_TABLECELL: + { + sal_Int32 nRow = GetCurRow(); + sal_uInt16 nColumn = GetCurColumnId(); + if ( IsFieldVisible(nRow,nColumn) ) + rStateSet.AddState( AccessibleStateType::VISIBLE ); + if ( !IsFrozen( nColumn ) ) + rStateSet.AddState( AccessibleStateType::FOCUSABLE ); + rStateSet.AddState( AccessibleStateType::TRANSIENT ); + } + break; + case ::vcl::BBTYPE_ROWHEADERCELL: + case ::vcl::BBTYPE_COLUMNHEADERCELL: + case ::vcl::BBTYPE_CHECKBOXCELL: + OSL_FAIL("Illegal call here!"); + break; + } +} + +void BrowseBox::FillAccessibleStateSetForCell( ::utl::AccessibleStateSetHelper& _rStateSet, + sal_Int32 _nRow, sal_uInt16 _nColumnPos ) const +{ + //! TODO check if the state is valid for table cells + if ( IsCellVisible( _nRow, _nColumnPos ) ) + _rStateSet.AddState( AccessibleStateType::VISIBLE ); + if ( GetCurrRow() == _nRow && GetCurrColumn() == _nColumnPos ) + _rStateSet.AddState( AccessibleStateType::FOCUSED ); + else // only transient when column is not focused + _rStateSet.AddState( AccessibleStateType::TRANSIENT ); +} + + +void BrowseBox::GrabTableFocus() +{ + GrabFocus(); +} + +OUString BrowseBox::GetCellText(long, sal_uInt16 ) const +{ + SAL_WARN("svtools", "This method has to be implemented by the derived classes! BUG!!"); + return OUString(); +} + + +void BrowseBox::commitHeaderBarEvent(sal_Int16 nEventId, + const Any& rNewValue, const Any& rOldValue, bool _bColumnHeaderBar ) +{ + if ( isAccessibleAlive() ) + m_pImpl->m_pAccessible->commitHeaderBarEvent( nEventId, + rNewValue, rOldValue, _bColumnHeaderBar ); +} + +void BrowseBox::commitTableEvent( sal_Int16 _nEventId, const Any& _rNewValue, const Any& _rOldValue ) +{ + if ( isAccessibleAlive() ) + m_pImpl->m_pAccessible->commitTableEvent( _nEventId, _rNewValue, _rOldValue ); +} + +void BrowseBox::commitBrowseBoxEvent( sal_Int16 _nEventId, const Any& _rNewValue, const Any& _rOldValue ) +{ + if ( isAccessibleAlive() ) + m_pImpl->m_pAccessible->commitEvent( _nEventId, _rNewValue, _rOldValue); +} + +::vcl::IAccessibleFactory& BrowseBox::getAccessibleFactory() +{ + return m_pImpl->m_aFactoryAccess.getFactory(); +} + +bool BrowseBox::isAccessibleAlive( ) const +{ + return ( nullptr != m_pImpl->m_pAccessible ) && m_pImpl->m_pAccessible->isAlive(); +} + +// IAccessibleTableProvider + +sal_Int32 BrowseBox::GetCurrRow() const +{ + return GetCurRow(); +} + +sal_uInt16 BrowseBox::GetCurrColumn() const +{ + return GetColumnPos( GetCurColumnId() ); +} + +bool BrowseBox::HasRowHeader() const +{ + return ( GetColumnId( 0 ) == HandleColumnId ); // HandleColumn == RowHeader +} + +bool BrowseBox::GoToCell( sal_Int32 _nRow, sal_uInt16 _nColumn ) +{ + return GoToRowColumnId( _nRow, GetColumnId( _nColumn ) ); +} + +void BrowseBox::SelectColumn( sal_uInt16 _nColumn, bool _bSelect ) +{ + SelectColumnPos( _nColumn, _bSelect ); +} + +bool BrowseBox::IsColumnSelected( long _nColumn ) const +{ + return ( pColSel && (0 <= _nColumn) && (_nColumn <= 0xFFF) ) && + pColSel->IsSelected( static_cast< sal_uInt16 >( _nColumn ) ); +} + +sal_Int32 BrowseBox::GetSelectedRowCount() const +{ + return GetSelectRowCount(); +} + +sal_Int32 BrowseBox::GetSelectedColumnCount() const +{ + const MultiSelection* pColumnSel = GetColumnSelection(); + return pColumnSel ? pColumnSel->GetSelectCount() : 0; +} + +void BrowseBox::GetAllSelectedRows( css::uno::Sequence< sal_Int32 >& _rRows ) const +{ + sal_Int32 nCount = GetSelectRowCount(); + if( nCount ) + { + _rRows.realloc( nCount ); + _rRows[ 0 ] = const_cast< BrowseBox* >( this )->FirstSelectedRow(); + for( sal_Int32 nIndex = 1; nIndex < nCount; ++nIndex ) + _rRows[ nIndex ] = const_cast< BrowseBox* >( this )->NextSelectedRow(); + DBG_ASSERT( const_cast< BrowseBox* >( this )->NextSelectedRow() == BROWSER_ENDOFSELECTION, + "BrowseBox::GetAllSelectedRows - too many selected rows found" ); + } +} + +void BrowseBox::GetAllSelectedColumns( css::uno::Sequence< sal_Int32 >& _rColumns ) const +{ + const MultiSelection* pColumnSel = GetColumnSelection(); + sal_Int32 nCount = GetSelectedColumnCount(); + if( !(pColumnSel && nCount) ) + return; + + _rColumns.realloc( nCount ); + + sal_Int32 nIndex = 0; + const size_t nRangeCount = pColumnSel->GetRangeCount(); + for( size_t nRange = 0; nRange < nRangeCount; ++nRange ) + { + const Range& rRange = pColumnSel->GetRange( nRange ); + // loop has to include aRange.Max() + for( sal_Int32 nCol = rRange.Min(); nCol <= static_cast<sal_Int32>(rRange.Max()); ++nCol ) + { + DBG_ASSERT( nIndex < nCount, + "GetAllSelectedColumns - range overflow" ); + _rColumns[ nIndex ] = nCol; + ++nIndex; + } + } +} + +bool BrowseBox::IsCellVisible( sal_Int32 _nRow, sal_uInt16 _nColumnPos ) const +{ + return IsFieldVisible( _nRow, GetColumnId( _nColumnPos ) ); +} + +OUString BrowseBox::GetAccessibleCellText(long _nRow, sal_uInt16 _nColPos) const +{ + return GetCellText( _nRow, GetColumnId( _nColPos ) ); +} + + +bool BrowseBox::GetGlyphBoundRects( const Point& rOrigin, const OUString& rStr, int nIndex, int nLen, MetricVector& rVector ) +{ + return Control::GetGlyphBoundRects( rOrigin, rStr, nIndex, nLen, rVector ); +} + +tools::Rectangle BrowseBox::GetWindowExtentsRelative( vcl::Window *pRelativeWindow ) const +{ + return Control::GetWindowExtentsRelative( pRelativeWindow ); +} + +void BrowseBox::GrabFocus() +{ + Control::GrabFocus(); +} + +Reference< XAccessible > BrowseBox::GetAccessible() +{ + return Control::GetAccessible(); +} + +vcl::Window* BrowseBox::GetAccessibleParentWindow() const +{ + return Control::GetAccessibleParentWindow(); +} + +vcl::Window* BrowseBox::GetWindowInstance() +{ + return this; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/brwbox/brwhead.cxx b/svtools/source/brwbox/brwhead.cxx new file mode 100644 index 000000000..fa42bfe29 --- /dev/null +++ b/svtools/source/brwbox/brwhead.cxx @@ -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 . + */ + + +#include <svtools/brwhead.hxx> +#include <svtools/brwbox.hxx> +#include <vcl/commandevent.hxx> + + +BrowserHeader::BrowserHeader( BrowseBox* pParent, WinBits nWinBits ) + :HeaderBar( pParent, nWinBits ) + ,_pBrowseBox( pParent ) +{ + long nHeight = pParent->IsZoom() ? pParent->CalcZoom(pParent->GetTitleHeight()) : pParent->GetTitleHeight(); + + SetPosSizePixel( Point( 0, 0), + Size( pParent->GetOutputSizePixel().Width(), + nHeight ) ); + Show(); +} + + +BrowserHeader::~BrowserHeader() +{ + disposeOnce(); +} + +void BrowserHeader::dispose() +{ + _pBrowseBox.clear(); + HeaderBar::dispose(); +} + + +void BrowserHeader::Command( const CommandEvent& rCEvt ) +{ + if ( !GetCurItemId() && CommandEventId::ContextMenu == rCEvt.GetCommand() ) + { + Point aPos( rCEvt.GetMousePosPixel() ); + if ( _pBrowseBox->IsFrozen(0) ) + aPos.AdjustX(_pBrowseBox->GetColumnWidth(0) ); + _pBrowseBox->GetDataWindow().Command( CommandEvent( + Point( aPos.X(), aPos.Y() - GetSizePixel().Height() ), + CommandEventId::ContextMenu, rCEvt.IsMouseEvent() ) ); + } +} + + +void BrowserHeader::EndDrag() +{ + // call before other actions, it looks more nice in most cases + HeaderBar::EndDrag(); + PaintImmediately(); + + // not aborted? + sal_uInt16 nId = GetCurItemId(); + if ( !nId ) + return; + + // handle column? + if ( nId == USHRT_MAX-1 ) + nId = 0; + + if ( !IsItemMode() ) + { + // column resize + _pBrowseBox->SetColumnWidth( nId, GetItemSize( nId ) ); + _pBrowseBox->ColumnResized( nId ); + SetItemSize( nId, _pBrowseBox->GetColumnWidth( nId ) ); + } + else + { + // column drag + // did the position actually change? + // take the handle column into account + sal_uInt16 nOldPos = _pBrowseBox->GetColumnPos(nId), + nNewPos = GetItemPos( nId ); + + if (_pBrowseBox->GetColumnId(0) == BrowseBox::HandleColumnId) + nNewPos++; + + if (nOldPos != nNewPos) + { + _pBrowseBox->SetColumnPos( nId, nNewPos ); + _pBrowseBox->ColumnMoved( nId ); + } + } +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/brwbox/brwimpl.hxx b/svtools/source/brwbox/brwimpl.hxx new file mode 100644 index 000000000..95623570c --- /dev/null +++ b/svtools/source/brwbox/brwimpl.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 <vcl/accessibletableprovider.hxx> +#include <vcl/svtaccessiblefactory.hxx> +#include <com/sun/star/lang/XComponent.hpp> +#include <com/sun/star/accessibility/XAccessible.hpp> +#include <osl/diagnose.h> +#include <tools/diagnose_ex.h> + +#include <map> + +namespace svt +{ + class BrowseBoxImpl + { + // member + public: + typedef ::std::map< sal_Int32, css::uno::Reference< css::accessibility::XAccessible > > THeaderCellMap; + + struct THeaderCellMapFunctorDispose + { + void operator()(const THeaderCellMap::value_type& _aType) + { + css::uno::Reference< css::lang::XComponent > xComp( _aType.second, css::uno::UNO_QUERY ); + OSL_ENSURE( xComp.is() || !_aType.second.is(), "THeaderCellMapFunctorDispose: invalid accessible cell (no XComponent)!" ); + if ( xComp.is() ) + try + { + xComp->dispose(); + } + catch( const css::uno::Exception& ) + { + TOOLS_WARN_EXCEPTION( "svtools", "THeaderCellMapFunctorDispose" ); + } + } + }; + + public: + vcl::AccessibleFactoryAccess m_aFactoryAccess; + vcl::IAccessibleBrowseBox* m_pAccessible; + THeaderCellMap m_aColHeaderCellMap; + THeaderCellMap m_aRowHeaderCellMap; + + public: + BrowseBoxImpl() : m_pAccessible(nullptr) + { + } + + + /// @see AccessibleBrowseBox::getHeaderBar + css::uno::Reference< css::accessibility::XAccessible > + getAccessibleHeaderBar( vcl::AccessibleBrowseBoxObjType _eObjType ); + + /// @see AccessibleBrowseBox::getTable + css::uno::Reference< css::accessibility::XAccessible > + getAccessibleTable( ); + + }; +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/brwbox/datwin.cxx b/svtools/source/brwbox/datwin.cxx new file mode 100644 index 000000000..f22ddb19e --- /dev/null +++ b/svtools/source/brwbox/datwin.cxx @@ -0,0 +1,691 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 "datwin.hxx" +#include <o3tl/numeric.hxx> +#include <vcl/commandevent.hxx> +#include <vcl/help.hxx> +#include <vcl/settings.hxx> +#include <vcl/scrbar.hxx> +#include <vcl/ptrstyle.hxx> +#include <tools/debug.hxx> +#include <tools/fract.hxx> + + +void ButtonFrame::Draw( OutputDevice& rDev ) +{ + Color aOldFillColor = rDev.GetFillColor(); + Color aOldLineColor = rDev.GetLineColor(); + + const StyleSettings &rSettings = rDev.GetSettings().GetStyleSettings(); + Color aColLight( rSettings.GetLightColor() ); + Color aColShadow( rSettings.GetShadowColor() ); + Color aColFace( rSettings.GetFaceColor() ); + + rDev.SetLineColor( aColFace ); + rDev.SetFillColor( aColFace ); + rDev.DrawRect( aRect ); + + if( rDev.GetOutDevType() != OUTDEV_WINDOW ) + { + rDev.SetLineColor( aColLight ); + rDev.DrawLine( aRect.TopLeft(), Point( aRect.Right(), aRect.Top() ) ); + rDev.DrawLine( aRect.TopLeft(), Point( aRect.Left(), aRect.Bottom() - 1 ) ); + rDev.SetLineColor( aColShadow ); + rDev.DrawLine( aRect.BottomRight(), Point( aRect.Right(), aRect.Top() ) ); + rDev.DrawLine( aRect.BottomRight(), Point( aRect.Left(), aRect.Bottom() ) ); + } + + if ( !aText.isEmpty() ) + { + OUString aVal = rDev.GetEllipsisString(aText,aInnerRect.GetWidth() - 2*MIN_COLUMNWIDTH); + + vcl::Font aFont( rDev.GetFont() ); + bool bOldTransp = aFont.IsTransparent(); + if ( !bOldTransp ) + { + aFont.SetTransparent( true ); + rDev.SetFont( aFont ); + } + + Color aOldColor = rDev.GetTextColor(); + if (m_bDrawDisabled) + rDev.SetTextColor(rSettings.GetDisableColor()); + + rDev.DrawText( Point( + ( aInnerRect.Left() + aInnerRect.Right() ) / 2 - ( rDev.GetTextWidth(aVal) / 2 ), + aInnerRect.Top() ), aVal ); + + // restore settings + if ( !bOldTransp ) + { + aFont.SetTransparent(false); + rDev.SetFont( aFont ); + } + if (m_bDrawDisabled) + rDev.SetTextColor(aOldColor); + } + + rDev.SetLineColor( aOldLineColor ); + rDev.SetFillColor( aOldFillColor ); +} + +BrowserColumn::BrowserColumn( sal_uInt16 nItemId, + const OUString& rTitle, sal_uLong nWidthPixel, const Fraction& rCurrentZoom ) +: _nId( nItemId ), + _nWidth( nWidthPixel ), + _aTitle( rTitle ), + _bFrozen( false ) +{ + double n = static_cast<double>(_nWidth); + n *= static_cast<double>(rCurrentZoom.GetDenominator()); + if (!rCurrentZoom.GetNumerator()) + throw o3tl::divide_by_zero(); + n /= static_cast<double>(rCurrentZoom.GetNumerator()); + _nOriginalWidth = n>0 ? static_cast<long>(n+0.5) : -static_cast<long>(-n+0.5); +} + +BrowserColumn::~BrowserColumn() +{ +} + +void BrowserColumn::SetWidth(sal_uLong nNewWidthPixel, const Fraction& rCurrentZoom) +{ + _nWidth = nNewWidthPixel; + // Avoid overflow when called with LONG_MAX from + // BrowseBox::AutoSizeLastColumn: + if (_nWidth == LONG_MAX) + { + _nOriginalWidth = _nWidth; + } + else + { + double n = static_cast<double>(_nWidth); + n *= static_cast<double>(rCurrentZoom.GetDenominator()); + if (!rCurrentZoom.GetNumerator()) + throw o3tl::divide_by_zero(); + n /= static_cast<double>(rCurrentZoom.GetNumerator()); + _nOriginalWidth = n>0 ? static_cast<long>(n+0.5) : -static_cast<long>(-n+0.5); + } +} + +void BrowserColumn::Draw( BrowseBox const & rBox, OutputDevice& rDev, const Point& rPos ) +{ + if ( _nId == 0 ) + { + // paint handle column + ButtonFrame( rPos, Size( Width()-1, rBox.GetDataRowHeight()-1 ), + "", false ).Draw( rDev ); + Color aOldLineColor = rDev.GetLineColor(); + rDev.SetLineColor( COL_BLACK ); + rDev.DrawLine( + Point( rPos.X(), rPos.Y()+rBox.GetDataRowHeight()-1 ), + Point( rPos.X() + Width() - 1, rPos.Y()+rBox.GetDataRowHeight()-1 ) ); + rDev.DrawLine( + Point( rPos.X() + Width() - 1, rPos.Y() ), + Point( rPos.X() + Width() - 1, rPos.Y()+rBox.GetDataRowHeight()-1 ) ); + rDev.SetLineColor( aOldLineColor ); + + rBox.DoPaintField( rDev, + tools::Rectangle( + Point( rPos.X() + 2, rPos.Y() + 2 ), + Size( Width()-1, rBox.GetDataRowHeight()-1 ) ), + GetId(), + BrowseBox::BrowserColumnAccess() ); + } + else + { + // paint data column + long nWidth = Width() == LONG_MAX ? rBox.GetDataWindow().GetSizePixel().Width() : Width(); + + rBox.DoPaintField( rDev, + tools::Rectangle( + Point( rPos.X() + MIN_COLUMNWIDTH, rPos.Y() ), + Size( nWidth-2*MIN_COLUMNWIDTH, rBox.GetDataRowHeight()-1 ) ), + GetId(), + BrowseBox::BrowserColumnAccess() ); + } +} + + +void BrowserColumn::ZoomChanged(const Fraction& rNewZoom) +{ + double n(_nOriginalWidth * rNewZoom); + _nWidth = n>0 ? static_cast<long>(n+0.5) : -static_cast<long>(-n+0.5); +} + + +BrowserDataWin::BrowserDataWin( BrowseBox* pParent ) + :Control( pParent, WB_CLIPCHILDREN ) + ,DragSourceHelper( this ) + ,DropTargetHelper( this ) + ,pHeaderBar( nullptr ) + ,pCornerWin( nullptr ) + ,bInDtor( false ) + ,bInPaint( false ) + ,bInCommand( false ) + ,bNoHScroll( false ) + ,bNoVScroll( false ) + ,bAutoHScroll(false) + ,bAutoVScroll(false) + ,bUpdateMode( true ) + ,bAutoSizeLastCol(false) + ,bResizeOnPaint( false ) + ,bUpdateOnUnlock( false ) + ,bInUpdateScrollbars( false ) + ,bHadRecursion( false ) + ,bCallingDropCallback( false ) + ,nUpdateLock( 0 ) + ,nCursorHidden( 0 ) + ,m_nDragRowDividerLimit( 0 ) + ,m_nDragRowDividerOffset( 0 ) +{ + aMouseTimer.SetInvokeHandler( LINK( this, BrowserDataWin, RepeatedMouseMove ) ); + aMouseTimer.SetTimeout( 100 ); +} + + +BrowserDataWin::~BrowserDataWin() +{ + disposeOnce(); +} + +void BrowserDataWin::dispose() +{ + bInDtor = true; + + aInvalidRegion.clear(); + pHeaderBar.clear(); + pCornerWin.clear(); + DragSourceHelper::dispose(); + DropTargetHelper::dispose(); + Control::dispose(); +} + + +void BrowserDataWin::LeaveUpdateLock() +{ + if ( !--nUpdateLock ) + { + DoOutstandingInvalidations(); + if (bUpdateOnUnlock ) + { + Control::PaintImmediately(); + bUpdateOnUnlock = false; + } + } +} + +void InitSettings_Impl(vcl::Window* pWin) +{ + const StyleSettings& rStyleSettings = pWin->GetSettings().GetStyleSettings(); + + pWin->ApplyControlFont(*pWin, rStyleSettings.GetFieldFont()); + pWin->ApplyControlForeground(*pWin, rStyleSettings.GetWindowTextColor()); + pWin->ApplyControlBackground(*pWin, rStyleSettings.GetWindowColor()); +} + + +void BrowserDataWin::Update() +{ + if ( !nUpdateLock ) + Control::PaintImmediately(); + else + bUpdateOnUnlock = true; +} + + +void BrowserDataWin::DataChanged( const DataChangedEvent& rDCEvt ) +{ + if ( (rDCEvt.GetType() == DataChangedEventType::SETTINGS) && + (rDCEvt.GetFlags() & AllSettingsFlags::STYLE) ) + { + InitSettings_Impl(this); + Invalidate(); + InitSettings_Impl(GetParent()); + GetParent()->Invalidate(); + GetParent()->Resize(); + } + else + Control::DataChanged( rDCEvt ); +} + + +void BrowserDataWin::Paint(vcl::RenderContext& rRenderContext, const tools::Rectangle& rRect) +{ + if (!nUpdateLock && GetUpdateMode()) + { + if (bInPaint) + { + aInvalidRegion.emplace_back(rRect); + return; + } + bInPaint = true; + GetParent()->PaintData(*this, rRenderContext, rRect); + bInPaint = false; + DoOutstandingInvalidations(); + } + else + { + aInvalidRegion.emplace_back(rRect); + } +} + + +BrowseEvent BrowserDataWin::CreateBrowseEvent( const Point& rPosPixel ) +{ + BrowseBox *pBox = GetParent(); + + // seek to row under mouse + long nRelRow = rPosPixel.Y() < 0 + ? -1 + : rPosPixel.Y() / pBox->GetDataRowHeight(); + long nRow = nRelRow < 0 ? -1 : nRelRow + pBox->nTopRow; + + // find column under mouse + long nMouseX = rPosPixel.X(); + long nColX = 0; + size_t nCol; + for ( nCol = 0; + nCol < pBox->mvCols.size() && nColX < GetSizePixel().Width(); + ++nCol ) + if ( pBox->mvCols[ nCol ]->IsFrozen() || nCol >= pBox->nFirstCol ) + { + nColX += pBox->mvCols[ nCol ]->Width(); + if ( nMouseX < nColX ) + break; + } + sal_uInt16 nColId = BROWSER_INVALIDID; + if ( nCol < pBox->mvCols.size() ) + nColId = pBox->mvCols[ nCol ]->GetId(); + + // compute the field rectangle and field relative MouseEvent + tools::Rectangle aFieldRect; + if ( nCol < pBox->mvCols.size() ) + { + nColX -= pBox->mvCols[ nCol ]->Width(); + aFieldRect = tools::Rectangle( + Point( nColX, nRelRow * pBox->GetDataRowHeight() ), + Size( pBox->mvCols[ nCol ]->Width(), + pBox->GetDataRowHeight() ) ); + } + + // assemble and return the BrowseEvent + return BrowseEvent( this, nRow, nCol, nColId, aFieldRect ); +} + + +sal_Int8 BrowserDataWin::AcceptDrop( const AcceptDropEvent& _rEvt ) +{ + bCallingDropCallback = true; + sal_Int8 nReturn = GetParent()->AcceptDrop( BrowserAcceptDropEvent( this, _rEvt ) ); + bCallingDropCallback = false; + return nReturn; +} + + +sal_Int8 BrowserDataWin::ExecuteDrop( const ExecuteDropEvent& _rEvt ) +{ + bCallingDropCallback = true; + sal_Int8 nReturn = GetParent()->ExecuteDrop( BrowserExecuteDropEvent( this, _rEvt ) ); + bCallingDropCallback = false; + return nReturn; +} + + +void BrowserDataWin::StartDrag( sal_Int8 _nAction, const Point& _rPosPixel ) +{ + if ( !GetParent()->bRowDividerDrag ) + { + Point aEventPos( _rPosPixel ); + aEventPos.AdjustY(GetParent()->GetTitleHeight() ); + GetParent()->StartDrag( _nAction, aEventPos ); + } +} + + +void BrowserDataWin::Command( const CommandEvent& rEvt ) +{ + // scroll mouse event? + BrowseBox *pBox = GetParent(); + if ( ( (rEvt.GetCommand() == CommandEventId::Wheel) || + (rEvt.GetCommand() == CommandEventId::StartAutoScroll) || + (rEvt.GetCommand() == CommandEventId::AutoScroll) ) && + ( HandleScrollCommand( rEvt, pBox->aHScroll.get(), pBox->pVScroll ) ) ) + return; + + Point aEventPos( rEvt.GetMousePosPixel() ); + long nRow = pBox->GetRowAtYPosPixel( aEventPos.Y(), false); + MouseEvent aMouseEvt( aEventPos, 1, MouseEventModifiers::SELECT, MOUSE_LEFT ); + if ( CommandEventId::ContextMenu == rEvt.GetCommand() && rEvt.IsMouseEvent() && + nRow < pBox->GetRowCount() && !pBox->IsRowSelected(nRow) ) + { + bInCommand = true; + MouseButtonDown( aMouseEvt ); + if( bInDtor ) + return; + MouseButtonUp( aMouseEvt ); + if( bInDtor ) + return; + bInCommand = false; + } + + aEventPos.AdjustY(GetParent()->GetTitleHeight() ); + CommandEvent aEvt( aEventPos, rEvt.GetCommand(), + rEvt.IsMouseEvent(), rEvt.GetEventData() ); + bInCommand = true; + GetParent()->Command( aEvt ); + if( bInDtor ) + return; + bInCommand = false; + + if ( CommandEventId::StartDrag == rEvt.GetCommand() ) + MouseButtonUp( aMouseEvt ); + + Control::Command( rEvt ); +} + + +bool BrowserDataWin::ImplRowDividerHitTest( const BrowserMouseEvent& _rEvent ) +{ + if ( ! ( GetParent()->IsInteractiveRowHeightEnabled() + && ( _rEvent.GetRow() >= 0 ) + && ( _rEvent.GetRow() < GetParent()->GetRowCount() ) + && ( _rEvent.GetColumnId() == BrowseBox::HandleColumnId ) + ) + ) + return false; + + long nDividerDistance = GetParent()->GetDataRowHeight() - ( _rEvent.GetPosPixel().Y() % GetParent()->GetDataRowHeight() ); + return ( nDividerDistance <= 4 ); +} + + +void BrowserDataWin::MouseButtonDown( const MouseEvent& rEvt ) +{ + aLastMousePos = OutputToScreenPixel( rEvt.GetPosPixel() ); + + BrowserMouseEvent aBrowserEvent( this, rEvt ); + if ( ( aBrowserEvent.GetClicks() == 1 ) && ImplRowDividerHitTest( aBrowserEvent ) ) + { + StartRowDividerDrag( aBrowserEvent.GetPosPixel() ); + return; + } + + GetParent()->MouseButtonDown( BrowserMouseEvent( this, rEvt ) ); +} + + +void BrowserDataWin::MouseMove( const MouseEvent& rEvt ) +{ + // avoid pseudo MouseMoves + Point aNewPos = OutputToScreenPixel( rEvt.GetPosPixel() ); + if ( aNewPos == aLastMousePos ) + return; + aLastMousePos = aNewPos; + + // transform to a BrowseEvent + BrowserMouseEvent aBrowserEvent( this, rEvt ); + GetParent()->MouseMove( aBrowserEvent ); + + // pointer shape + PointerStyle ePointerStyle = PointerStyle::Arrow; + if ( ImplRowDividerHitTest( aBrowserEvent ) ) + ePointerStyle = PointerStyle::VSizeBar; + SetPointer( ePointerStyle ); + + // dragging out of the visible area? + if ( rEvt.IsLeft() && + ( rEvt.GetPosPixel().Y() > GetSizePixel().Height() || + rEvt.GetPosPixel().Y() < 0 ) ) + { + // repeat the event + aRepeatEvt = rEvt; + aMouseTimer.Start(); + } + else + // killing old repeat-event + if ( aMouseTimer.IsActive() ) + aMouseTimer.Stop(); +} + + +IMPL_LINK_NOARG(BrowserDataWin, RepeatedMouseMove, Timer *, void) +{ + GetParent()->MouseMove( BrowserMouseEvent( this, aRepeatEvt ) ); +} + +void BrowserDataWin::MouseButtonUp( const MouseEvent& rEvt ) +{ + // avoid pseudo MouseMoves + Point aNewPos = OutputToScreenPixel( rEvt.GetPosPixel() ); + aLastMousePos = aNewPos; + + // simulate a move to the current position + MouseMove( rEvt ); + + // actual button up handling + ReleaseMouse(); + if ( aMouseTimer.IsActive() ) + aMouseTimer.Stop(); + GetParent()->MouseButtonUp( BrowserMouseEvent( this, rEvt ) ); +} + + +void BrowserDataWin::StartRowDividerDrag( const Point& _rStartPos ) +{ + long nDataRowHeight = GetParent()->GetDataRowHeight(); + // the exact separation pos of the two rows + long nDragRowDividerCurrentPos = _rStartPos.Y(); + if ( ( nDragRowDividerCurrentPos % nDataRowHeight ) > nDataRowHeight / 2 ) + nDragRowDividerCurrentPos += nDataRowHeight; + nDragRowDividerCurrentPos /= nDataRowHeight; + nDragRowDividerCurrentPos *= nDataRowHeight; + + m_nDragRowDividerOffset = nDragRowDividerCurrentPos - _rStartPos.Y(); + + m_nDragRowDividerLimit = nDragRowDividerCurrentPos - nDataRowHeight; + + GetParent()->bRowDividerDrag = true; + GetParent()->ImplStartTracking(); + + tools::Rectangle aDragSplitRect( 0, m_nDragRowDividerLimit, GetOutputSizePixel().Width(), nDragRowDividerCurrentPos ); + ShowTracking( aDragSplitRect ); + + StartTracking(); +} + + +void BrowserDataWin::Tracking( const TrackingEvent& rTEvt ) +{ + if ( !GetParent()->bRowDividerDrag ) + return; + + Point aMousePos = rTEvt.GetMouseEvent().GetPosPixel(); + // stop resizing at our bottom line + if ( aMousePos.Y() > GetOutputSizePixel().Height() ) + aMousePos.setY( GetOutputSizePixel().Height() ); + + if ( rTEvt.IsTrackingEnded() ) + { + HideTracking(); + GetParent()->bRowDividerDrag = false; + GetParent()->ImplEndTracking(); + + if ( !rTEvt.IsTrackingCanceled() ) + { + long nNewRowHeight = aMousePos.Y() + m_nDragRowDividerOffset - m_nDragRowDividerLimit; + + // care for minimum row height + if ( nNewRowHeight < GetParent()->QueryMinimumRowHeight() ) + nNewRowHeight = GetParent()->QueryMinimumRowHeight(); + + GetParent()->SetDataRowHeight( nNewRowHeight ); + GetParent()->RowHeightChanged(); + } + } + else + { + long nDragRowDividerCurrentPos = aMousePos.Y() + m_nDragRowDividerOffset; + + // care for minimum row height + if ( nDragRowDividerCurrentPos < m_nDragRowDividerLimit + GetParent()->QueryMinimumRowHeight() ) + nDragRowDividerCurrentPos = m_nDragRowDividerLimit + GetParent()->QueryMinimumRowHeight(); + + tools::Rectangle aDragSplitRect( 0, m_nDragRowDividerLimit, GetOutputSizePixel().Width(), nDragRowDividerCurrentPos ); + ShowTracking( aDragSplitRect ); + } +} + + +void BrowserDataWin::KeyInput( const KeyEvent& rEvt ) +{ + // pass to parent window + if ( !GetParent()->ProcessKey( rEvt ) ) + Control::KeyInput( rEvt ); +} + + +void BrowserDataWin::RequestHelp( const HelpEvent& rHEvt ) +{ + GetParent()->RequestHelp( rHEvt ); +} + + +BrowseEvent::BrowseEvent( vcl::Window* pWindow, + long nAbsRow, sal_uInt16 nColumn, sal_uInt16 nColumnId, + const tools::Rectangle& rRect ): + pWin(pWindow), + nRow(nAbsRow), + aRect(rRect), + nCol(nColumn), + nColId(nColumnId) +{ +} + + +BrowserMouseEvent::BrowserMouseEvent( BrowserDataWin *pWindow, + const MouseEvent& rEvt ): + MouseEvent(rEvt), + BrowseEvent( pWindow->CreateBrowseEvent( rEvt.GetPosPixel() ) ) +{ +} + + +BrowserMouseEvent::BrowserMouseEvent( vcl::Window *pWindow, const MouseEvent& rEvt, + long nAbsRow, sal_uInt16 nColumn, sal_uInt16 nColumnId, + const tools::Rectangle& rRect ): + MouseEvent(rEvt), + BrowseEvent( pWindow, nAbsRow, nColumn, nColumnId, rRect ) +{ +} + + +BrowserAcceptDropEvent::BrowserAcceptDropEvent( BrowserDataWin *pWindow, const AcceptDropEvent& rEvt ) + :AcceptDropEvent(rEvt) + ,BrowseEvent( pWindow->CreateBrowseEvent( rEvt.maPosPixel ) ) +{ +} + + +BrowserExecuteDropEvent::BrowserExecuteDropEvent( BrowserDataWin *pWindow, const ExecuteDropEvent& rEvt ) + :ExecuteDropEvent(rEvt) + ,BrowseEvent( pWindow->CreateBrowseEvent( rEvt.maPosPixel ) ) +{ +} + + +void BrowserDataWin::SetUpdateMode( bool bMode ) +{ + DBG_ASSERT( !bUpdateMode || aInvalidRegion.empty(), "invalid region not empty" ); + if ( bMode == bUpdateMode ) + return; + + bUpdateMode = bMode; + if ( bMode ) + DoOutstandingInvalidations(); +} + + +void BrowserDataWin::DoOutstandingInvalidations() +{ + for (const auto& rRect : aInvalidRegion) + Control::Invalidate( rRect ); + aInvalidRegion.clear(); +} + + +void BrowserDataWin::Invalidate( InvalidateFlags nFlags ) +{ + if ( !GetUpdateMode() ) + { + aInvalidRegion.clear(); + aInvalidRegion.emplace_back( Point( 0, 0 ), GetOutputSizePixel() ); + } + else + Window::Invalidate( nFlags ); +} + + +void BrowserDataWin::Invalidate( const tools::Rectangle& rRect, InvalidateFlags nFlags ) +{ + if ( !GetUpdateMode() ) + aInvalidRegion.emplace_back( rRect ); + else + Window::Invalidate( rRect, nFlags ); +} + +BrowserScrollBar::~BrowserScrollBar() +{ + disposeOnce(); +} + +void BrowserScrollBar::dispose() +{ + _pDataWin.clear(); + ScrollBar::dispose(); +} + +void BrowserScrollBar::Tracking( const TrackingEvent& rTEvt ) +{ + sal_uLong nPos = GetThumbPos(); + if ( nPos != _nLastPos ) + { + OUString aTip = OUString::number(nPos) + "/"; + if ( !_pDataWin->GetRealRowCount().isEmpty() ) + aTip += _pDataWin->GetRealRowCount(); + else + aTip += OUString::number(GetRangeMax()); + + tools::Rectangle aRect(GetPointerPosPixel(), Size(GetTextWidth(aTip), GetTextHeight())); + Help::ShowQuickHelp(this, aRect, aTip); + _nLastPos = nPos; + } + + ScrollBar::Tracking( rTEvt ); +} + +void BrowserScrollBar::EndScroll() +{ + Help::HideBalloonAndQuickHelp(); + ScrollBar::EndScroll(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/brwbox/datwin.hxx b/svtools/source/brwbox/datwin.hxx new file mode 100644 index 000000000..1105708cc --- /dev/null +++ b/svtools/source/brwbox/datwin.hxx @@ -0,0 +1,189 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <svtools/brwbox.hxx> +#include <svtools/brwhead.hxx> +#include <vcl/scrbar.hxx> +#include <vcl/timer.hxx> +#include <vcl/transfer.hxx> +#include <vector> + +#define MIN_COLUMNWIDTH 2 + +class ButtonFrame +{ + tools::Rectangle aRect; + tools::Rectangle aInnerRect; + OUString aText; + bool m_bDrawDisabled; + +public: + ButtonFrame( const Point& rPt, const Size& rSz, + const OUString &rText, + bool _bDrawDisabled) + :aRect( rPt, rSz ) + ,aInnerRect( Point( aRect.Left()+1, aRect.Top()+1 ), + Size( aRect.GetWidth()-2, aRect.GetHeight()-2 ) ) + ,aText(rText) + ,m_bDrawDisabled(_bDrawDisabled) + { + } + + void Draw( OutputDevice& rDev ); +}; + + +class BrowserColumn final +{ + sal_uInt16 _nId; + sal_uLong _nOriginalWidth; + sal_uLong _nWidth; + OUString _aTitle; + bool _bFrozen; + +public: + BrowserColumn( sal_uInt16 nItemId, + const OUString& rTitle, sal_uLong nWidthPixel, const Fraction& rCurrentZoom ); + ~BrowserColumn(); + + sal_uInt16 GetId() const { return _nId; } + + sal_uLong Width() { return _nWidth; } + OUString& Title() { return _aTitle; } + + bool IsFrozen() const { return _bFrozen; } + void Freeze() { _bFrozen = true; } + + void Draw( BrowseBox const & rBox, OutputDevice& rDev, + const Point& rPos ); + + void SetWidth(sal_uLong nNewWidthPixel, const Fraction& rCurrentZoom); + void ZoomChanged(const Fraction& rNewZoom); +}; + + +class BrowserDataWin + :public Control + ,public DragSourceHelper + ,public DropTargetHelper +{ +public: + VclPtr<BrowserHeader> pHeaderBar; // only for BrowserMode::HEADERBAR_NEW + VclPtr<ScrollBarBox> 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<tools::Rectangle> 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 + + long m_nDragRowDividerLimit; + 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 + { return static_cast<BrowseBox*>( Window::GetParent() ); } + 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; + +protected: + void StartRowDividerDrag( const Point& _rStartPos ); + bool ImplRowDividerHitTest( const BrowserMouseEvent& _rEvent ); +}; + + +class BrowserScrollBar: public ScrollBar +{ + sal_uLong _nLastPos; + VclPtr<BrowserDataWin> _pDataWin; + +public: + BrowserScrollBar( vcl::Window* pParent, WinBits nStyle, + BrowserDataWin *pDataWin ) + : ScrollBar( pParent, nStyle ), + _nLastPos( ULONG_MAX ), + _pDataWin( pDataWin ) + {} + virtual ~BrowserScrollBar() override; + virtual void dispose() override; + //ScrollBar( vcl::Window* pParent, const ResId& rResId ); + + virtual void Tracking( const TrackingEvent& rTEvt ) override; + virtual void EndScroll() override; +}; + + +void InitSettings_Impl( vcl::Window *pWin ); + + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/brwbox/ebbcontrols.cxx b/svtools/source/brwbox/ebbcontrols.cxx new file mode 100644 index 000000000..e402f0a42 --- /dev/null +++ b/svtools/source/brwbox/ebbcontrols.cxx @@ -0,0 +1,566 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <svtools/editbrowsebox.hxx> +#include <vcl/button.hxx> +#include <vcl/spinfld.hxx> +#include <vcl/fmtfield.hxx> +#include <vcl/xtextedt.hxx> +#include <vcl/textview.hxx> + +namespace svt +{ + + //= ComboBoxControl + ComboBoxControl::ComboBoxControl(vcl::Window* pParent) + : ControlBase(pParent, "svt/ui/combocontrol.ui", "ComboControl") + , m_xWidget(m_xBuilder->weld_combo_box("combobox")) + { + m_xWidget->set_entry_width_chars(1); // so a smaller than default width can be used + m_xWidget->connect_changed(LINK(this, ComboBoxControl, SelectHdl)); + } + + void ComboBoxControl::dispose() + { + m_xWidget.reset(); + ControlBase::dispose(); + } + + IMPL_LINK_NOARG(ComboBoxControl, SelectHdl, weld::ComboBox&, void) + { + CallModifyHdls(); + } + + //= ComboBoxCellController + ComboBoxCellController::ComboBoxCellController(ComboBoxControl* pWin) + :CellController(pWin) + { + static_cast<ComboBoxControl&>(GetWindow()).SetModifyHdl(LINK(this, ComboBoxCellController, ModifyHdl)); + } + + IMPL_LINK_NOARG(ComboBoxCellController, ModifyHdl, LinkParamNone*, void) + { + callModifyHdl(); + } + + bool ComboBoxCellController::MoveAllowed(const KeyEvent& rEvt) const + { + weld::ComboBox& rBox = GetComboBox(); + switch (rEvt.GetKeyCode().GetCode()) + { + case KEY_END: + case KEY_RIGHT: + { + int nStartPos, nEndPos; + bool bNoSelection = rBox.get_entry_selection_bounds(nStartPos, nEndPos); + return bNoSelection && nEndPos == rBox.get_active_text().getLength(); + } + case KEY_HOME: + case KEY_LEFT: + { + int nStartPos, nEndPos; + bool bNoSelection = rBox.get_entry_selection_bounds(nStartPos, nEndPos); + return bNoSelection && nStartPos == 0; + } + case KEY_UP: + case KEY_DOWN: + if (rBox.get_popup_shown()) + return false; + if (!rEvt.GetKeyCode().IsShift() && + rEvt.GetKeyCode().IsMod1()) + return false; + // drop down the list box + else if (rEvt.GetKeyCode().IsMod2() && rEvt.GetKeyCode().GetCode() == KEY_DOWN) + return false; + [[fallthrough]]; + case KEY_PAGEUP: + case KEY_PAGEDOWN: + case KEY_RETURN: + if (rBox.get_popup_shown()) + return false; + [[fallthrough]]; + default: + return true; + } + } + + bool ComboBoxCellController::IsModified() const + { + return GetComboBox().get_value_changed_from_saved(); + } + + void ComboBoxCellController::ClearModified() + { + GetComboBox().save_value(); + } + + //= ListBoxControl + ListBoxControl::ListBoxControl(vcl::Window* pParent) + : ControlBase(pParent, "svt/ui/listcontrol.ui", "ListControl") + , m_xWidget(m_xBuilder->weld_combo_box("listbox")) + { + m_xWidget->set_size_request(42, -1); // so a later narrow size request can stick + m_xWidget->connect_changed(LINK(this, ListBoxControl, SelectHdl)); + } + + void ListBoxControl::dispose() + { + m_xWidget.reset(); + ControlBase::dispose(); + } + + IMPL_LINK_NOARG(ListBoxControl, SelectHdl, weld::ComboBox&, void) + { + CallModifyHdls(); + } + + //= ListBoxCellController + ListBoxCellController::ListBoxCellController(ListBoxControl* pWin) + :CellController(pWin) + { + static_cast<ListBoxControl&>(GetWindow()).SetModifyHdl(LINK(this, ListBoxCellController, ListBoxSelectHdl)); + } + + bool ListBoxCellController::MoveAllowed(const KeyEvent& rEvt) const + { + const weld::ComboBox& rBox = GetListBox(); + switch (rEvt.GetKeyCode().GetCode()) + { + case KEY_UP: + case KEY_DOWN: + if (!rEvt.GetKeyCode().IsShift() && + rEvt.GetKeyCode().IsMod1()) + return false; + // drop down the list box + else + if (rEvt.GetKeyCode().IsMod2() && rEvt.GetKeyCode().GetCode() == KEY_DOWN) + return false; + [[fallthrough]]; + case KEY_PAGEUP: + case KEY_PAGEDOWN: + if (rBox.get_popup_shown()) + return false; + [[fallthrough]]; + default: + return true; + } + } + + bool ListBoxCellController::IsModified() const + { + return GetListBox().get_value_changed_from_saved(); + } + + void ListBoxCellController::ClearModified() + { + GetListBox().save_value(); + } + + IMPL_LINK_NOARG(ListBoxCellController, ListBoxSelectHdl, LinkParamNone*, void) + { + callModifyHdl(); + } + + //= CheckBoxControl + CheckBoxControl::CheckBoxControl(vcl::Window* pParent) + :Control(pParent, 0) + { + const Wallpaper& rParentBackground = pParent->GetBackground(); + if ( (pParent->GetStyle() & WB_CLIPCHILDREN) || rParentBackground.IsFixed() ) + SetBackground( rParentBackground ); + else + { + SetPaintTransparent( true ); + SetBackground(); + } + + EnableChildTransparentMode(); + + pBox = VclPtr<CheckBox>::Create(this,WB_CENTER|WB_VCENTER); + pBox->EnableTriState( true ); + pBox->SetLegacyNoTextAlign( true ); + pBox->EnableChildTransparentMode(); + pBox->SetPaintTransparent( true ); + pBox->SetClickHdl( LINK( this, CheckBoxControl, OnClick ) ); + pBox->Show(); + } + + CheckBoxControl::~CheckBoxControl() + { + disposeOnce(); + } + + void CheckBoxControl::dispose() + { + pBox.disposeAndClear(); + Control::dispose(); + } + + + IMPL_LINK_NOARG(CheckBoxControl, OnClick, Button*, void) + { + m_aClickLink.Call(pBox); + m_aModifyLink.Call(nullptr); + } + + + void CheckBoxControl::Resize() + { + Control::Resize(); + pBox->SetPosSizePixel(Point(0,0),GetSizePixel()); + } + + + void CheckBoxControl::DataChanged( const DataChangedEvent& _rEvent ) + { + if ( _rEvent.GetType() == DataChangedEventType::SETTINGS ) + pBox->SetSettings( GetSettings() ); + } + + + void CheckBoxControl::StateChanged( StateChangedType nStateChange ) + { + Control::StateChanged(nStateChange); + if ( nStateChange == StateChangedType::Zoom ) + pBox->SetZoom(GetZoom()); + } + + void CheckBoxControl::Draw( OutputDevice* pDev, const Point& rPos, DrawFlags nFlags ) + { + pBox->Draw(pDev, rPos, nFlags); + } + + void CheckBoxControl::GetFocus() + { + if (pBox) + pBox->GrabFocus(); + } + + + void CheckBoxControl::Paint(vcl::RenderContext& rRenderContext, const tools::Rectangle& rClientRect) + { + Control::Paint(rRenderContext, rClientRect); + if (HasFocus()) + ShowFocus(tools::Rectangle()); + } + + + bool CheckBoxControl::PreNotify(NotifyEvent& rEvt) + { + switch (rEvt.GetType()) + { + case MouseNotifyEvent::GETFOCUS: + ShowFocus(tools::Rectangle()); + break; + case MouseNotifyEvent::LOSEFOCUS: + HideFocus(); + break; + default: + break; + } + return Control::PreNotify(rEvt); + } + + + //= CheckBoxCellController + + + CheckBoxCellController::CheckBoxCellController(CheckBoxControl* pWin) + : CellController(pWin) + { + static_cast<CheckBoxControl &>(GetWindow()).SetModifyHdl( LINK(this, CheckBoxCellController, ModifyHdl) ); + } + + bool CheckBoxCellController::WantMouseEvent() const + { + return true; + } + + + CheckBox& CheckBoxCellController::GetCheckBox() const + { + return static_cast<CheckBoxControl &>(GetWindow()).GetBox(); + } + + + bool CheckBoxCellController::IsModified() const + { + return GetCheckBox().IsValueChangedFromSaved(); + } + + + void CheckBoxCellController::ClearModified() + { + GetCheckBox().SaveValue(); + } + + + IMPL_LINK_NOARG(CheckBoxCellController, ModifyHdl, LinkParamNone*, void) + { + callModifyHdl(); + } + + //= MultiLineEditImplementation + + + OUString MultiLineEditImplementation::GetText( LineEnd aSeparator ) const + { + return const_cast< MultiLineEditImplementation* >( this )->GetEditWindow().GetText( aSeparator ); + } + + + OUString MultiLineEditImplementation::GetSelected( LineEnd aSeparator ) const + { + return const_cast< MultiLineEditImplementation* >( this )->GetEditWindow().GetSelected( aSeparator ); + } + + + //= EditCellController + + + EditCellController::EditCellController( Edit* _pEdit ) + :CellController( _pEdit ) + ,m_pEditImplementation( new EditImplementation( *_pEdit ) ) + ,m_bOwnImplementation( true ) + { + m_pEditImplementation->SetModifyHdl( LINK(this, EditCellController, ModifyHdl) ); + } + + + EditCellController::EditCellController( IEditImplementation* _pImplementation ) + :CellController( &_pImplementation->GetControl() ) + ,m_pEditImplementation( _pImplementation ) + ,m_bOwnImplementation( false ) + { + m_pEditImplementation->SetModifyHdl( LINK(this, EditCellController, ModifyHdl) ); + } + + + EditCellController::~EditCellController( ) + { + if ( m_bOwnImplementation ) + DELETEZ( m_pEditImplementation ); + } + + + void EditCellController::SetModified() + { + m_pEditImplementation->SetModified(); + } + + + void EditCellController::ClearModified() + { + m_pEditImplementation->ClearModified(); + } + + + bool EditCellController::MoveAllowed(const KeyEvent& rEvt) const + { + bool bResult; + switch (rEvt.GetKeyCode().GetCode()) + { + case KEY_END: + case KEY_RIGHT: + { + Selection aSel = m_pEditImplementation->GetSelection(); + bResult = !aSel && aSel.Max() == m_pEditImplementation->GetText( LINEEND_LF ).getLength(); + } break; + case KEY_HOME: + case KEY_LEFT: + { + Selection aSel = m_pEditImplementation->GetSelection(); + bResult = !aSel && aSel.Min() == 0; + } break; + default: + bResult = true; + } + return bResult; + } + + + bool EditCellController::IsModified() const + { + return m_pEditImplementation->IsModified(); + } + + + IMPL_LINK_NOARG(EditCellController, ModifyHdl, Edit&, void) + { + callModifyHdl(); + } + + //= SpinCellController + + + SpinCellController::SpinCellController(SpinField* pWin) + :CellController(pWin) + { + GetSpinWindow().SetModifyHdl( LINK(this, SpinCellController, ModifyHdl) ); + } + + const SpinField& SpinCellController::GetSpinWindow() const + { + return static_cast<const SpinField &>(GetWindow()); + } + + SpinField& SpinCellController::GetSpinWindow() + { + return static_cast<SpinField &>(GetWindow()); + } + + void SpinCellController::SetModified() + { + GetSpinWindow().SetModifyFlag(); + } + + + void SpinCellController::ClearModified() + { + GetSpinWindow().ClearModifyFlag(); + } + + + bool SpinCellController::MoveAllowed(const KeyEvent& rEvt) const + { + bool bResult; + switch (rEvt.GetKeyCode().GetCode()) + { + case KEY_END: + case KEY_RIGHT: + { + Selection aSel = GetSpinWindow().GetSelection(); + bResult = !aSel && aSel.Max() == GetSpinWindow().GetText().getLength(); + } break; + case KEY_HOME: + case KEY_LEFT: + { + Selection aSel = GetSpinWindow().GetSelection(); + bResult = !aSel && aSel.Min() == 0; + } break; + default: + bResult = true; + } + return bResult; + } + + + bool SpinCellController::IsModified() const + { + return GetSpinWindow().IsModified(); + } + + IMPL_LINK_NOARG(SpinCellController, ModifyHdl, Edit&, void) + { + callModifyHdl(); + } + + //= FormattedFieldCellController + + + FormattedFieldCellController::FormattedFieldCellController( FormattedField* _pFormatted ) + :EditCellController( _pFormatted ) + { + } + + + void FormattedFieldCellController::CommitModifications() + { + static_cast< FormattedField& >( GetWindow() ).Commit(); + } + + + //= MultiLineTextCell + + + void MultiLineTextCell::Modify() + { + GetTextEngine()->SetModified( true ); + VclMultiLineEdit::Modify(); + } + + + bool MultiLineTextCell::dispatchKeyEvent( const KeyEvent& _rEvent ) + { + Selection aOldSelection( GetSelection() ); + + bool bWasModified = IsModified(); + ClearModifyFlag( ); + + bool bHandled = GetTextView()->KeyInput( _rEvent ); + + bool bIsModified = IsModified(); + if ( bWasModified && !bIsModified ) + // not sure whether this can really happen + SetModifyFlag(); + + if ( bHandled ) // the view claimed it handled the key input + { + // unfortunately, KeyInput also returns <TRUE/> (means "I handled this key input") + // when nothing really changed. Let's care for this. + Selection aNewSelection( GetSelection() ); + if ( aNewSelection != aOldSelection // selection changed + || bIsModified // or some other modification + ) + return true; + } + return false; + } + + + bool MultiLineTextCell::PreNotify( NotifyEvent& rNEvt ) + { + if ( rNEvt.GetType() == MouseNotifyEvent::KEYINPUT ) + { + if ( IsWindowOrChild( rNEvt.GetWindow() ) ) + { + // give the text view a chance to handle the keys + // this is necessary since a lot of keys which are normally handled + // by this view (in KeyInput) are intercepted by the EditBrowseBox, + // which uses them for other reasons. An example is the KeyUp key, + // which is used by both the text view and the edit browse box + + const KeyEvent* pKeyEvent = rNEvt.GetKeyEvent(); + const vcl::KeyCode& rKeyCode = pKeyEvent->GetKeyCode(); + sal_uInt16 nCode = rKeyCode.GetCode(); + + if ( ( nCode == KEY_RETURN ) && ( rKeyCode.GetModifier() == KEY_MOD1 ) ) + { + KeyEvent aEvent( pKeyEvent->GetCharCode(), + vcl::KeyCode( KEY_RETURN ), + pKeyEvent->GetRepeat() + ); + if ( dispatchKeyEvent( aEvent ) ) + return true; + } + + if ( ( nCode != KEY_TAB ) && ( nCode != KEY_RETURN ) ) // everything but tab and enter + { + if ( dispatchKeyEvent( *pKeyEvent ) ) + return true; + } + } + } + return VclMultiLineEdit::PreNotify( rNEvt ); + } + + +} // namespace svt + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/brwbox/editbrowsebox.cxx b/svtools/source/brwbox/editbrowsebox.cxx new file mode 100644 index 000000000..12ef6d6fd --- /dev/null +++ b/svtools/source/brwbox/editbrowsebox.cxx @@ -0,0 +1,1326 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <svtools/editbrowsebox.hxx> + +#include <vcl/svapp.hxx> +#include <tools/debug.hxx> +#include <vcl/window.hxx> + +#include <vcl/button.hxx> +#include <vcl/edit.hxx> +#include <vcl/settings.hxx> + +#include <bitmaps.hlst> + +#include <algorithm> +#include "editbrowseboximpl.hxx" +#include <com/sun/star/accessibility/AccessibleEventId.hpp> + + +namespace svt +{ + + namespace + { + + GetFocusFlags getRealGetFocusFlags( vcl::Window* _pWindow ) + { + GetFocusFlags nFlags = GetFocusFlags::NONE; + while ( _pWindow && nFlags == GetFocusFlags::NONE ) + { + nFlags = _pWindow->GetGetFocusFlags( ); + _pWindow = _pWindow->GetParent(); + } + return nFlags; + } + } + + using namespace ::com::sun::star::uno; + using namespace com::sun::star::accessibility::AccessibleEventId; + + + IEditImplementation::~IEditImplementation() + { + } + + //= EditBrowserHeader + + void EditBrowserHeader::DoubleClick() + { + sal_uInt16 nColId = GetCurItemId(); + if (nColId) + { + sal_uInt32 nAutoWidth = static_cast<EditBrowseBox*>(GetParent())->GetAutoColumnWidth(nColId); + if (nAutoWidth != static_cast<EditBrowseBox*>(GetParent())->GetColumnWidth(nColId)) + { + static_cast<EditBrowseBox*>(GetParent())->SetColumnWidth(nColId, nAutoWidth); + static_cast<EditBrowseBox*>(GetParent())->ColumnResized(nColId); + } + } + } + + //= EditBrowseBox + + void EditBrowseBox::BrowserMouseEventPtr::Clear() + { + pEvent.reset(); + } + + void EditBrowseBox::BrowserMouseEventPtr::Set(const BrowserMouseEvent* pEvt, bool bIsDown) + { + if (pEvt == pEvent.get()) + { + bDown = bIsDown; + return; + } + pEvent.reset(); + if (pEvt) + { + pEvent.reset(new BrowserMouseEvent(pEvt->GetWindow(), + *pEvt, + pEvt->GetRow(), + pEvt->GetColumn(), + pEvt->GetColumnId(), + pEvt->GetRect())); + bDown = bIsDown; + } + } + + EditBrowseBox::EditBrowseBox( vcl::Window* pParent, EditBrowseBoxFlags nBrowserFlags, WinBits nBits, BrowserMode _nMode ) + :BrowseBox( pParent, nBits, _nMode ) + ,nStartEvent(nullptr) + ,nEndEvent(nullptr) + ,nCellModifiedEvent(nullptr) + ,m_pFocusWhileRequest(nullptr) + ,nPaintRow(-1) + ,nEditRow(-1) + ,nEditCol(0) + ,bHasFocus(false) + ,bPaintStatus(true) + ,bActiveBeforeTracking( false ) + ,m_nBrowserFlags(nBrowserFlags) + ,pHeader(nullptr) + { + m_aImpl.reset(new EditBrowseBoxImpl); + + SetCompoundControl(true); + + ImplInitSettings(true, true, true); + + pCheckBoxPaint = VclPtr<CheckBoxControl>::Create(&GetDataWindow()); + pCheckBoxPaint->SetPaintTransparent( true ); + pCheckBoxPaint->SetBackground(); + } + + void EditBrowseBox::Init() + { + // late construction + } + + EditBrowseBox::~EditBrowseBox() + { + disposeOnce(); + } + + void EditBrowseBox::dispose() + { + if (nStartEvent) + Application::RemoveUserEvent(nStartEvent); + if (nEndEvent) + Application::RemoveUserEvent(nEndEvent); + if (nCellModifiedEvent) + Application::RemoveUserEvent(nCellModifiedEvent); + + pCheckBoxPaint.disposeAndClear(); + m_pFocusWhileRequest.clear(); + pHeader.clear(); + BrowseBox::dispose(); + } + + + void EditBrowseBox::RemoveRows() + { + BrowseBox::Clear(); + nEditRow = nPaintRow = -1; + nEditCol = 0; + } + + + VclPtr<BrowserHeader> EditBrowseBox::CreateHeaderBar(BrowseBox* pParent) + { + pHeader = imp_CreateHeaderBar(pParent); + if (!IsUpdateMode()) + pHeader->SetUpdateMode(false); + return pHeader; + } + + + VclPtr<BrowserHeader> EditBrowseBox::imp_CreateHeaderBar(BrowseBox* pParent) + { + return VclPtr<EditBrowserHeader>::Create(pParent); + } + + + void EditBrowseBox::LoseFocus() + { + BrowseBox::LoseFocus(); + DetermineFocus(); + } + + + void EditBrowseBox::GetFocus() + { + BrowseBox::GetFocus(); + + // This should handle the case that the BrowseBox (or one of its children) + // gets the focus from outside by pressing Tab + if (IsEditing() && Controller()->GetWindow().IsVisible()) + Controller()->GetWindow().GrabFocus(); + + DetermineFocus( getRealGetFocusFlags( this ) ); + } + + + bool EditBrowseBox::SeekRow(long nRow) + { + nPaintRow = nRow; + return true; + } + + + IMPL_LINK_NOARG(EditBrowseBox, StartEditHdl, void*, void) + { + nStartEvent = nullptr; + if (IsEditing()) + { + EnableAndShow(); + if (!ControlHasFocus() && (m_pFocusWhileRequest.get() == Application::GetFocusWindow())) + aController->GetWindow().GrabFocus(); + } + } + + void EditBrowseBox::PaintField( vcl::RenderContext& rDev, const tools::Rectangle& rRect, + sal_uInt16 nColumnId ) const + { + if (nColumnId == HandleColumnId) + { + if (bPaintStatus) + PaintStatusCell(rDev, rRect); + } + else + { + // don't paint the current cell + if (&rDev == &GetDataWindow()) + // but only if we're painting onto our data win (which is the usual painting) + if (nPaintRow == nEditRow) + { + if (IsEditing() && nEditCol == nColumnId && aController->GetWindow().IsVisible()) + return; + } + PaintCell(rDev, rRect, nColumnId); + } + } + + Image EditBrowseBox::GetImage(RowStatus eStatus) const + { + BitmapEx aBitmap; + bool bNeedMirror = IsRTLEnabled(); + switch (eStatus) + { + case CURRENT: + aBitmap = BitmapEx(BMP_CURRENT); + break; + case CURRENTNEW: + aBitmap = BitmapEx(BMP_CURRENTNEW); + break; + case MODIFIED: + aBitmap = BitmapEx(BMP_MODIFIED); + bNeedMirror = false; // the pen is not mirrored + break; + case NEW: + aBitmap = BitmapEx(BMP_NEW); + break; + case DELETED: + aBitmap = BitmapEx(BMP_DELETED); + break; + case PRIMARYKEY: + aBitmap = BitmapEx(BMP_PRIMARYKEY); + break; + case CURRENT_PRIMARYKEY: + aBitmap = BitmapEx(BMP_CURRENT_PRIMARYKEY); + break; + case FILTER: + aBitmap = BitmapEx(BMP_FILTER); + break; + case HEADERFOOTER: + aBitmap = BitmapEx(BMP_HEADERFOOTER); + break; + case CLEAN: + break; + } + if ( bNeedMirror ) + { + aBitmap.Mirror( BmpMirrorFlags::Horizontal ); + } + return Image(aBitmap); + } + + void EditBrowseBox::PaintStatusCell(OutputDevice& rDev, const tools::Rectangle& rRect) const + { + if (nPaintRow < 0) + return; + + RowStatus eStatus = GetRowStatus( nPaintRow ); + EditBrowseBoxFlags nBrowserFlags = GetBrowserFlags(); + + if (nBrowserFlags & EditBrowseBoxFlags::NO_HANDLE_COLUMN_CONTENT) + return; + + // draw the text of the header column + if (nBrowserFlags & EditBrowseBoxFlags::HANDLE_COLUMN_TEXT ) + { + rDev.DrawText( rRect, GetCellText( nPaintRow, 0 ), + DrawTextFlags::Center | DrawTextFlags::VCenter | DrawTextFlags::Clip ); + } + // draw an image + else if (eStatus != CLEAN && rDev.GetOutDevType() == OUTDEV_WINDOW) + { + Image aImage(GetImage(eStatus)); + // calc the image position + Size aImageSize(aImage.GetSizePixel()); + aImageSize.setWidth( CalcZoom(aImageSize.Width()) ); + aImageSize.setHeight( CalcZoom(aImageSize.Height()) ); + Point aPos( rRect.TopLeft() ); + + if ( ( aImageSize.Width() > rRect.GetWidth() ) || ( aImageSize.Height() > rRect.GetHeight() ) ) + rDev.SetClipRegion(vcl::Region(rRect)); + + if ( aImageSize.Width() < rRect.GetWidth() ) + aPos.AdjustX(( rRect.GetWidth() - aImageSize.Width() ) / 2 ); + + if ( aImageSize.Height() < rRect.GetHeight() ) + aPos.AdjustY(( rRect.GetHeight() - aImageSize.Height() ) / 2 ); + + if ( IsZoom() ) + rDev.DrawImage( aPos, aImageSize, aImage ); + else + rDev.DrawImage( aPos, aImage ); + + if (rDev.IsClipRegion()) + rDev.SetClipRegion(); + } + } + + + void EditBrowseBox::ImplStartTracking() + { + bActiveBeforeTracking = IsEditing(); + if ( bActiveBeforeTracking ) + { + DeactivateCell(); + PaintImmediately(); + } + + BrowseBox::ImplStartTracking(); + } + + + void EditBrowseBox::ImplEndTracking() + { + if ( bActiveBeforeTracking ) + ActivateCell(); + bActiveBeforeTracking = false; + + BrowseBox::ImplEndTracking(); + } + + + void EditBrowseBox::RowHeightChanged() + { + if ( IsEditing() ) + { + tools::Rectangle aRect( GetCellRect( nEditRow, nEditCol, false ) ); + CellControllerRef aCellController( Controller() ); + ResizeController( aCellController, aRect ); + aCellController->GetWindow().GrabFocus(); + } + + BrowseBox::RowHeightChanged(); + } + + + EditBrowseBox::RowStatus EditBrowseBox::GetRowStatus(long) const + { + return CLEAN; + } + + + void EditBrowseBox::KeyInput( const KeyEvent& rEvt ) + { + sal_uInt16 nCode = rEvt.GetKeyCode().GetCode(); + bool bShift = rEvt.GetKeyCode().IsShift(); + bool bCtrl = rEvt.GetKeyCode().IsMod1(); + + switch (nCode) + { + case KEY_RETURN: + if (!bCtrl && !bShift && IsTabAllowed(true)) + { + Dispatch(BROWSER_CURSORRIGHT); + } + else + BrowseBox::KeyInput(rEvt); + return; + case KEY_TAB: + if (!bCtrl && !bShift) + { + if (IsTabAllowed(true)) + Dispatch(BROWSER_CURSORRIGHT); + else + // do NOT call BrowseBox::KeyInput : this would handle the tab, but we already now + // that tab isn't allowed here. So give the Control class a chance + Control::KeyInput(rEvt); + return; + } + else if (!bCtrl && bShift) + { + if (IsTabAllowed(false)) + Dispatch(BROWSER_CURSORLEFT); + else + // do NOT call BrowseBox::KeyInput : this would handle the tab, but we already now + // that tab isn't allowed here. So give the Control class a chance + Control::KeyInput(rEvt); + return; + } + [[fallthrough]]; + default: + BrowseBox::KeyInput(rEvt); + } + } + + + void EditBrowseBox::MouseButtonDown(const BrowserMouseEvent& rEvt) + { + // absorb double clicks + if (rEvt.GetClicks() > 1 && rEvt.GetRow() >= 0) + return; + + // we are about to leave the current cell. If there is a "this cell has been modified" notification + // pending (asynchronously), this may be deadly -> do it synchronously + if ( nCellModifiedEvent ) + { + Application::RemoveUserEvent( nCellModifiedEvent ); + nCellModifiedEvent = nullptr; + LINK( this, EditBrowseBox, CellModifiedHdl ).Call( nullptr ); + } + + if (rEvt.GetColumnId() == HandleColumnId) + { // it was the handle column. save the current cell content if necessary + // (clicking on the handle column results in selecting the current row) + if (IsEditing() && aController->IsModified()) + SaveModified(); + } + + aMouseEvent.Set(&rEvt,true); + BrowseBox::MouseButtonDown(rEvt); + aMouseEvent.Clear(); + + if (m_nBrowserFlags & EditBrowseBoxFlags::ACTIVATE_ON_BUTTONDOWN) + { + // the base class does not travel upon MouseButtonDown, but implActivateCellOnMouseEvent assumes we traveled ... + GoToRowColumnId( rEvt.GetRow(), rEvt.GetColumnId() ); + if (rEvt.GetRow() >= 0) + implActivateCellOnMouseEvent(rEvt, false); + } + } + + + void EditBrowseBox::MouseButtonUp( const BrowserMouseEvent& rEvt ) + { + // absorb double clicks + if (rEvt.GetClicks() > 1 && rEvt.GetRow() >= 0) + return; + + aMouseEvent.Set(&rEvt,false); + BrowseBox::MouseButtonUp(rEvt); + aMouseEvent.Clear(); + + if (!(m_nBrowserFlags & EditBrowseBoxFlags::ACTIVATE_ON_BUTTONDOWN)) + if (rEvt.GetRow() >= 0) + implActivateCellOnMouseEvent(rEvt, true); + } + + bool EditBrowseBox::ControlHasFocus() const + { + Window* pControlWindow = aController ? &aController->GetWindow() : nullptr; + if (ControlBase* pControlBase = dynamic_cast<ControlBase*>(pControlWindow)) + return pControlBase->ControlHasFocus(); + return pControlWindow && pControlWindow->HasChildPathFocus(); + } + + void EditBrowseBox::implActivateCellOnMouseEvent(const BrowserMouseEvent& _rEvt, bool _bUp) + { + if (!IsEditing()) + ActivateCell(); + else if (IsEditing() && !aController->GetWindow().IsEnabled()) + DeactivateCell(); + else if (IsEditing() && !ControlHasFocus()) + AsynchGetFocus(); + + if (!(IsEditing() && aController->GetWindow().IsEnabled() && aController->WantMouseEvent())) + return; + +// forwards the event to the control + + // If the field has been moved previously, we have to adjust the position + + aController->GetWindow().GrabFocus(); + + // the position of the event relative to the controller's window + Point aPos = _rEvt.GetPosPixel() - _rEvt.GetRect().TopLeft(); + // the (child) window which should really get the event + vcl::Window* pRealHandler = aController->GetWindow().FindWindow(aPos); + if (pRealHandler) + // the coords relative to this real handler + aPos -= pRealHandler->GetPosPixel(); + else + pRealHandler = &aController->GetWindow(); + + // the faked event + MouseEvent aEvent(aPos, _rEvt.GetClicks(), _rEvt.GetMode(), + _rEvt.GetButtons(), + _rEvt.GetModifier()); + + pRealHandler->MouseButtonDown(aEvent); + if (_bUp) + pRealHandler->MouseButtonUp(aEvent); + + vcl::Window *pWin = &aController->GetWindow(); + if (!pWin->IsTracking()) + { + for (pWin = pWin->GetWindow(GetWindowType::FirstChild); + pWin && !pWin->IsTracking(); + pWin = pWin->GetWindow(GetWindowType::Next)) + { + } + } + if (pWin && pWin->IsTracking()) + pWin->EndTracking(); + } + + + void EditBrowseBox::Dispatch( sal_uInt16 _nId ) + { + if ( _nId == BROWSER_ENHANCESELECTION ) + { // this is a workaround for the bug in the base class: + // if the row selection is to be extended (which is what BROWSER_ENHANCESELECTION tells us) + // then the base class does not revert any column selections, while, for doing a "simple" + // selection (BROWSER_SELECT), it does. In fact, it does not only revert the col selection then, + // but also any current row selections. + // This clearly tells me that the both ids are for row selection only - there this behaviour does + // make sense. + // But here, where we have column selection, too, we take care of this ourself. + if ( GetSelectColumnCount( ) ) + { + while ( GetSelectColumnCount( ) ) + SelectColumnPos( + sal::static_int_cast< sal_uInt16 >(FirstSelectedColumn()), + false ); + Select(); + } + } + BrowseBox::Dispatch( _nId ); + } + + bool EditBrowseBox::PreNotify(NotifyEvent& rEvt) + { + if (rEvt.GetType() == MouseNotifyEvent::KEYINPUT) + { + if ( (IsEditing() && ControlHasFocus()) + || rEvt.GetWindow() == &GetDataWindow() + || (!IsEditing() && HasChildPathFocus()) + ) + { + const KeyEvent* pKeyEvent = rEvt.GetKeyEvent(); + sal_uInt16 nCode = pKeyEvent->GetKeyCode().GetCode(); + bool bShift = pKeyEvent->GetKeyCode().IsShift(); + bool bCtrl = pKeyEvent->GetKeyCode().IsMod1(); + bool bAlt = pKeyEvent->GetKeyCode().IsMod2(); + bool bLocalSelect = false; + bool bNonEditOnly = false; + sal_uInt16 nId = BROWSER_NONE; + + if (!bAlt && !bCtrl && !bShift ) + switch ( nCode ) + { + case KEY_DOWN: nId = BROWSER_CURSORDOWN; break; + case KEY_UP: nId = BROWSER_CURSORUP; break; + case KEY_PAGEDOWN: nId = BROWSER_CURSORPAGEDOWN; break; + case KEY_PAGEUP: nId = BROWSER_CURSORPAGEUP; break; + case KEY_HOME: nId = BROWSER_CURSORHOME; break; + case KEY_END: nId = BROWSER_CURSOREND; break; + + case KEY_TAB: + // ask if traveling to the next cell is allowed + if (IsTabAllowed(true)) + nId = BROWSER_CURSORRIGHT; + break; + + case KEY_RETURN: + // save the cell content (if necessary) + if (IsEditing() && aController->IsModified() && !SaveModified()) + { + // maybe we're not visible ... + EnableAndShow(); + aController->GetWindow().GrabFocus(); + return true; + } + // ask if traveling to the next cell is allowed + if (IsTabAllowed(true)) + nId = BROWSER_CURSORRIGHT; + + break; + case KEY_RIGHT: nId = BROWSER_CURSORRIGHT; break; + case KEY_LEFT: nId = BROWSER_CURSORLEFT; break; + case KEY_SPACE: nId = BROWSER_SELECT; bNonEditOnly = bLocalSelect = true; break; + } + + if ( !bAlt && !bCtrl && bShift ) + switch ( nCode ) + { + case KEY_DOWN: nId = BROWSER_SELECTDOWN; bLocalSelect = true; break; + case KEY_UP: nId = BROWSER_SELECTUP; bLocalSelect = true; break; + case KEY_HOME: nId = BROWSER_SELECTHOME; bLocalSelect = true; break; + case KEY_END: nId = BROWSER_SELECTEND; bLocalSelect = true; break; + case KEY_TAB: + if (IsTabAllowed(false)) + nId = BROWSER_CURSORLEFT; + break; + } + + if ( !bAlt && bCtrl && bShift ) + switch ( nCode ) + { + case KEY_SPACE: nId = BROWSER_SELECTCOLUMN; bLocalSelect = true; break; + } + + + if ( !bAlt && bCtrl && !bShift ) + switch ( nCode ) + { + case KEY_DOWN: nId = BROWSER_SCROLLUP; break; + case KEY_UP: nId = BROWSER_SCROLLDOWN; break; + case KEY_PAGEDOWN: nId = BROWSER_CURSORENDOFFILE; break; + case KEY_PAGEUP: nId = BROWSER_CURSORTOPOFFILE; break; + case KEY_HOME: nId = BROWSER_CURSORTOPOFSCREEN; break; + case KEY_END: nId = BROWSER_CURSORENDOFSCREEN; break; + case KEY_SPACE: nId = BROWSER_ENHANCESELECTION; bLocalSelect = true; break; + } + + + if ( ( nId != BROWSER_NONE ) + && ( !IsEditing() + || ( !bNonEditOnly + && aController->MoveAllowed( *pKeyEvent ) + ) + ) + ) + { + if (nId == BROWSER_SELECT || BROWSER_SELECTCOLUMN == nId ) + { + // save the cell content (if necessary) + if (IsEditing() && aController->IsModified() && !SaveModified()) + { + // maybe we're not visible ... + EnableAndShow(); + aController->GetWindow().GrabFocus(); + return true; + } + } + + Dispatch(nId); + + if (bLocalSelect && (GetSelectRowCount() || GetSelection() != nullptr)) + DeactivateCell(); + return true; + } + } + } + return BrowseBox::PreNotify(rEvt); + } + + bool EditBrowseBox::IsTabAllowed(bool) const + { + return true; + } + + + bool EditBrowseBox::EventNotify(NotifyEvent& rEvt) + { + switch (rEvt.GetType()) + { + case MouseNotifyEvent::GETFOCUS: + DetermineFocus( getRealGetFocusFlags( this ) ); + break; + + case MouseNotifyEvent::LOSEFOCUS: + DetermineFocus(); + break; + + default: + break; + } + return BrowseBox::EventNotify(rEvt); + } + + + void EditBrowseBox::StateChanged( StateChangedType nType ) + { + BrowseBox::StateChanged( nType ); + + bool bNeedCellReActivation = false; + if ( nType == StateChangedType::Mirroring ) + { + bNeedCellReActivation = true; + } + else if ( nType == StateChangedType::Zoom ) + { + ImplInitSettings( true, false, false ); + bNeedCellReActivation = true; + } + else if ( nType == StateChangedType::ControlFont ) + { + ImplInitSettings( true, false, false ); + Invalidate(); + } + else if ( nType == StateChangedType::ControlForeground ) + { + ImplInitSettings( false, true, false ); + Invalidate(); + } + else if ( nType == StateChangedType::ControlBackground ) + { + ImplInitSettings( false, false, true ); + Invalidate(); + } + else if (nType == StateChangedType::Style) + { + WinBits nStyle = GetStyle(); + if (!(nStyle & WB_NOTABSTOP) ) + nStyle |= WB_TABSTOP; + + SetStyle(nStyle); + } + if ( bNeedCellReActivation ) + { + if ( IsEditing() ) + { + DeactivateCell(); + ActivateCell(); + } + } + } + + + void EditBrowseBox::DataChanged( const DataChangedEvent& rDCEvt ) + { + BrowseBox::DataChanged( rDCEvt ); + + if ((( rDCEvt.GetType() == DataChangedEventType::SETTINGS ) || + ( rDCEvt.GetType() == DataChangedEventType::DISPLAY )) && + ( rDCEvt.GetFlags() & AllSettingsFlags::STYLE )) + { + ImplInitSettings( true, true, true ); + Invalidate(); + } + } + + void EditBrowseBox::ImplInitSettings( bool bFont, bool bForeground, bool bBackground ) + { + const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings(); + + if (bFont) + { + vcl::Font aFont = rStyleSettings.GetFieldFont(); + if (IsControlFont()) + { + GetDataWindow().SetControlFont(GetControlFont()); + aFont.Merge(GetControlFont()); + } + else + GetDataWindow().SetControlFont(); + + GetDataWindow().SetZoomedPointFont(GetDataWindow(), aFont); + } + + if (bFont || bForeground) + { + Color aTextColor = rStyleSettings.GetFieldTextColor(); + if (IsControlForeground()) + { + aTextColor = GetControlForeground(); + GetDataWindow().SetControlForeground(aTextColor); + } + else + GetDataWindow().SetControlForeground(); + + GetDataWindow().SetTextColor( aTextColor ); + } + + if (!bBackground) // FIXME: Outside of Paint Hierarchy + return; + + if (GetDataWindow().IsControlBackground()) + { + GetDataWindow().SetControlBackground(GetControlBackground()); + GetDataWindow().SetBackground(GetDataWindow().GetControlBackground()); + GetDataWindow().SetFillColor(GetDataWindow().GetControlBackground()); + } + else + { + GetDataWindow().SetControlBackground(); + GetDataWindow().SetBackground(rStyleSettings.GetFieldColor()); + GetDataWindow().SetFillColor(rStyleSettings.GetFieldColor()); + } + } + + + bool EditBrowseBox::IsCursorMoveAllowed(long nNewRow, sal_uInt16 nNewColId) const + { + sal_uInt16 nInfo = 0; + + if (GetSelectColumnCount() || (aMouseEvent.Is() && aMouseEvent->GetRow() < 0)) + nInfo |= COLSELECT; + if ((GetSelection() != nullptr && GetSelectRowCount()) || + (aMouseEvent.Is() && aMouseEvent->GetColumnId() == HandleColumnId)) + nInfo |= ROWSELECT; + if (!nInfo && nNewRow != nEditRow) + nInfo |= ROWCHANGE; + if (!nInfo && nNewColId != nEditCol) + nInfo |= COLCHANGE; + + if (nInfo == 0) // nothing happened + return true; + + // save the cell content + if (IsEditing() && aController->IsModified() && !const_cast<EditBrowseBox *>(this)->SaveModified()) + { + // maybe we're not visible ... + EnableAndShow(); + aController->GetWindow().GrabFocus(); + return false; + } + + EditBrowseBox * pTHIS = const_cast<EditBrowseBox *> (this); + + // save the cell content if + // a) a selection is being made + // b) the row is changing + if (IsModified() && (nInfo & (ROWCHANGE | COLSELECT | ROWSELECT)) && + !pTHIS->SaveRow()) + { + if (nInfo & COLSELECT || + nInfo & ROWSELECT) + { + // cancel selected + pTHIS->SetNoSelection(); + } + + if (IsEditing()) + { + if (!Controller()->GetWindow().IsVisible()) + { + EnableAndShow(); + } + aController->GetWindow().GrabFocus(); + } + return false; + } + + if (nNewRow != nEditRow) + { + vcl::Window& rWindow = GetDataWindow(); + if ((nEditRow >= 0) && !(GetBrowserFlags() & EditBrowseBoxFlags::NO_HANDLE_COLUMN_CONTENT)) + { + tools::Rectangle aRect = GetFieldRectPixel(nEditRow, 0, false ); + // status cell should be painted if and only if text is displayed + pTHIS->bPaintStatus = ( GetBrowserFlags() & EditBrowseBoxFlags::HANDLE_COLUMN_TEXT ) == EditBrowseBoxFlags::HANDLE_COLUMN_TEXT; + rWindow.Invalidate(aRect); + pTHIS->bPaintStatus = true; + } + + // don't paint during row change + rWindow.EnablePaint(false); + + // the last veto chance for derived classes + if (!pTHIS->CursorMoving(nNewRow, nNewColId)) + { + pTHIS->InvalidateStatusCell(nEditRow); + rWindow.EnablePaint(true); + return false; + } + else + { + rWindow.EnablePaint(true); + return true; + } + } + else + return pTHIS->CursorMoving(nNewRow, nNewColId); + } + + + void EditBrowseBox::ColumnMoved(sal_uInt16 nId) + { + BrowseBox::ColumnMoved(nId); + if (IsEditing()) + { + tools::Rectangle aRect( GetCellRect(nEditRow, nEditCol, false)); + CellControllerRef aControllerRef = Controller(); + ResizeController(aControllerRef, aRect); + Controller()->GetWindow().GrabFocus(); + } + } + + + bool EditBrowseBox::SaveRow() + { + return true; + } + + + bool EditBrowseBox::CursorMoving(long, sal_uInt16) + { + DeactivateCell(false); + return true; + } + + + void EditBrowseBox::CursorMoved() + { + long nNewRow = GetCurRow(); + if (nEditRow != nNewRow) + { + if (!(GetBrowserFlags() & EditBrowseBoxFlags::NO_HANDLE_COLUMN_CONTENT)) + InvalidateStatusCell(nNewRow); + nEditRow = nNewRow; + } + ActivateCell(); + GetDataWindow().EnablePaint(true); + // should not be called here because the descant event is not needed here + //BrowseBox::CursorMoved(); + } + + + void EditBrowseBox::EndScroll() + { + if (IsEditing()) + { + tools::Rectangle aRect = GetCellRect(nEditRow, nEditCol, false); + ResizeController(aController,aRect); + AsynchGetFocus(); + } + BrowseBox::EndScroll(); + } + + + void EditBrowseBox::ActivateCell(long nRow, sal_uInt16 nCol, bool bCellFocus) + { + if (IsEditing()) + return; + + nEditCol = nCol; + + if ((GetSelectRowCount() && GetSelection() != nullptr) || GetSelectColumnCount() || + (aMouseEvent.Is() && (aMouseEvent.IsDown() || aMouseEvent->GetClicks() > 1))) // nothing happens on MouseDown + { + return; + } + + if (!(nEditRow >= 0 && nEditCol > HandleColumnId)) + return; + + aController = GetController(nRow, nCol); + if (aController.is()) + { + tools::Rectangle aRect( GetCellRect(nEditRow, nEditCol, false)); + ResizeController(aController, aRect); + + InitController(aController, nEditRow, nEditCol); + + aController->ClearModified(); + aController->SetModifyHdl(LINK(this,EditBrowseBox,ModifyHdl)); + EnableAndShow(); + + if ( isAccessibleAlive() ) + implCreateActiveAccessible(); + + // activate the cell only of the browser has the focus + if ( bHasFocus && bCellFocus ) + AsynchGetFocus(); + } + else + { + // no controller -> we have a new "active descendant" + if ( isAccessibleAlive() && HasFocus() ) + { + commitTableEvent( + ACTIVE_DESCENDANT_CHANGED, + makeAny( CreateAccessibleCell( nRow, GetColumnPos( nCol -1) ) ), + Any() + ); + } + } + } + + + void EditBrowseBox::DeactivateCell(bool bUpdate) + { + if (!IsEditing()) + return; + + if ( isAccessibleAlive() ) + { + commitBrowseBoxEvent( CHILD, Any(), makeAny( m_aImpl->m_xActiveCell ) ); + m_aImpl->clearActiveCell(); + } + + aOldController = aController; + aController.clear(); + + // reset the modify handler + aOldController->SetModifyHdl(Link<LinkParamNone*,void>()); + + if (bHasFocus) + GrabFocus(); // ensure that we have (and keep) the focus + + aOldController->suspend(); + + // update if requested + if (bUpdate) + PaintImmediately(); + + // release the controller (asynchronously) + if (nEndEvent) + Application::RemoveUserEvent(nEndEvent); + nEndEvent = Application::PostUserEvent(LINK(this,EditBrowseBox,EndEditHdl), nullptr, true); + } + + + tools::Rectangle EditBrowseBox::GetCellRect(long nRow, sal_uInt16 nColId, bool bRel) const + { + tools::Rectangle aRect( GetFieldRectPixel(nRow, nColId, bRel)); + if ((GetMode() & BrowserMode::CURSOR_WO_FOCUS) == BrowserMode::CURSOR_WO_FOCUS) + { + aRect.AdjustTop(1 ); + aRect.AdjustBottom( -1 ); + } + return aRect; + } + + + IMPL_LINK_NOARG(EditBrowseBox, EndEditHdl, void*, void) + { + nEndEvent = nullptr; + + aOldController = CellControllerRef(); + } + + + IMPL_LINK_NOARG(EditBrowseBox, ModifyHdl, LinkParamNone*, void) + { + if (nCellModifiedEvent) + Application::RemoveUserEvent(nCellModifiedEvent); + nCellModifiedEvent = Application::PostUserEvent(LINK(this,EditBrowseBox,CellModifiedHdl), nullptr, true); + } + + + IMPL_LINK_NOARG(EditBrowseBox, CellModifiedHdl, void*, void) + { + nCellModifiedEvent = nullptr; + CellModified(); + } + + + void EditBrowseBox::ColumnResized( sal_uInt16 ) + { + if (IsEditing()) + { + tools::Rectangle aRect( GetCellRect(nEditRow, nEditCol, false)); + CellControllerRef aControllerRef = Controller(); + ResizeController(aControllerRef, aRect); + Controller()->GetWindow().GrabFocus(); + } + } + + + sal_uInt16 EditBrowseBox::AppendColumn(const OUString& rName, sal_uInt16 nWidth, sal_uInt16 nPos, sal_uInt16 nId) + { + if (nId == BROWSER_INVALIDID) + { + // look for the next free id + for (nId = ColCount(); nId > 0 && GetColumnPos(nId) != BROWSER_INVALIDID; nId--) + ; + + if (!nId) + { + // if there is no handle column + // increment the id + if ( ColCount() == 0 || GetColumnId(0) != HandleColumnId ) + nId = ColCount() + 1; + } + } + + DBG_ASSERT(nId, "EditBrowseBox::AppendColumn: invalid id!"); + + long w = nWidth; + if (!w) + w = GetDefaultColumnWidth(rName); + + InsertDataColumn(nId, rName, w, (HeaderBarItemBits::CENTER | HeaderBarItemBits::CLICKABLE), nPos); + return nId; + } + + void EditBrowseBox::Resize() + { + BrowseBox::Resize(); + + // if the window is smaller than "title line height" + "control area", + // do nothing + if (GetOutputSizePixel().Height() < + (GetControlArea().GetHeight() + GetDataWindow().GetPosPixel().Y())) + return; + + // the size of the control area + Point aPoint(GetControlArea().TopLeft()); + sal_uInt16 nX = static_cast<sal_uInt16>(aPoint.X()); + + ArrangeControls(nX, static_cast<sal_uInt16>(aPoint.Y())); + + if (!nX) + nX = USHRT_MAX; + + bool bChanged = ReserveControlArea(nX); + + //tdf#97731 if the reserved area changed size, give the controls a + //chance to adapt to the new size + if (bChanged) + { + nX = static_cast<sal_uInt16>(aPoint.X()); + ArrangeControls(nX, static_cast<sal_uInt16>(aPoint.Y())); + } + } + + void EditBrowseBox::ArrangeControls(sal_uInt16&, sal_uInt16) + { + } + + CellController* EditBrowseBox::GetController(long, sal_uInt16) + { + return nullptr; + } + + void EditBrowseBox::ResizeController(CellControllerRef const & rController, const tools::Rectangle& rRect) + { + Point aPoint(rRect.TopLeft()); + Size aSize(rRect.GetSize()); + Control& rControl = rController->GetWindow(); + auto nMinHeight = rControl.get_preferred_size().Height(); + if (nMinHeight > aSize.Height()) + { + auto nOffset = (nMinHeight - aSize.Height()) / 2; + aPoint.AdjustY(-nOffset); + aSize.setHeight(nMinHeight); + } + rControl.SetPosSizePixel(aPoint, aSize); + } + + void EditBrowseBox::InitController(CellControllerRef&, long, sal_uInt16) + { + } + + + void EditBrowseBox::CellModified() + { + } + + + bool EditBrowseBox::SaveModified() + { + return true; + } + + + void EditBrowseBox::DoubleClick(const BrowserMouseEvent& rEvt) + { + // when double clicking on the column, the optimum size will be calculated + sal_uInt16 nColId = rEvt.GetColumnId(); + if (nColId != HandleColumnId) + SetColumnWidth(nColId, GetAutoColumnWidth(nColId)); + } + + + sal_uInt32 EditBrowseBox::GetAutoColumnWidth(sal_uInt16 nColId) + { + sal_uInt32 nCurColWidth = GetColumnWidth(nColId); + sal_uInt32 nMinColWidth = CalcZoom(20); // minimum + sal_uInt32 nNewColWidth = nMinColWidth; + long nMaxRows = std::min(long(GetVisibleRows()), GetRowCount()); + long nLastVisRow = GetTopRow() + nMaxRows - 1; + + if (GetTopRow() <= nLastVisRow) // calc the column with using the cell contents + { + for (long i = GetTopRow(); i <= nLastVisRow; ++i) + nNewColWidth = std::max(nNewColWidth,GetTotalCellWidth(i,nColId) + 12); + + if (nNewColWidth == nCurColWidth) // size has not changed + nNewColWidth = GetDefaultColumnWidth(GetColumnTitle(nColId)); + } + else + nNewColWidth = GetDefaultColumnWidth(GetColumnTitle(nColId)); + return nNewColWidth; + } + + + sal_uInt32 EditBrowseBox::GetTotalCellWidth(long, sal_uInt16) + { + return 0; + } + + + void EditBrowseBox::InvalidateHandleColumn() + { + tools::Rectangle aHdlFieldRect( GetFieldRectPixel( 0, 0 )); + tools::Rectangle aInvalidRect( Point(0,0), GetOutputSizePixel() ); + aInvalidRect.SetRight( aHdlFieldRect.Right() ); + Invalidate( aInvalidRect ); + } + + + void EditBrowseBox::PaintTristate(const tools::Rectangle& rRect, const TriState& eState, bool _bEnabled) const + { + pCheckBoxPaint->GetBox().SetState(eState); + pCheckBoxPaint->SetPosSizePixel(rRect.TopLeft(), rRect.GetSize()); + + pCheckBoxPaint->GetBox().Enable(_bEnabled); + pCheckBoxPaint->Show(); + pCheckBoxPaint->SetParentUpdateMode( false ); + pCheckBoxPaint->PaintImmediately(); + pCheckBoxPaint->Hide(); + pCheckBoxPaint->SetParentUpdateMode( true ); + } + + + void EditBrowseBox::AsynchGetFocus() + { + if (nStartEvent) + Application::RemoveUserEvent(nStartEvent); + + m_pFocusWhileRequest = Application::GetFocusWindow(); + nStartEvent = Application::PostUserEvent(LINK(this,EditBrowseBox,StartEditHdl), nullptr, true); + } + + + void EditBrowseBox::SetBrowserFlags(EditBrowseBoxFlags nFlags) + { + if (m_nBrowserFlags == nFlags) + return; + + bool RowPicturesChanges = ((m_nBrowserFlags & EditBrowseBoxFlags::NO_HANDLE_COLUMN_CONTENT) != + (nFlags & EditBrowseBoxFlags::NO_HANDLE_COLUMN_CONTENT)); + m_nBrowserFlags = nFlags; + + if (RowPicturesChanges) + InvalidateStatusCell(GetCurRow()); + } + + inline void EditBrowseBox::EnableAndShow() const + { + Controller()->resume(); + } + + + CellController::CellController(Control* pW) + :pWindow( pW ) + ,bSuspended( true ) + { + + DBG_ASSERT(pWindow, "CellController::CellController: missing the window!"); + DBG_ASSERT(!pWindow->IsVisible(), "CellController::CellController: window should not be visible!"); + } + + + CellController::~CellController() + { + + } + + + void CellController::suspend( ) + { + DBG_ASSERT( bSuspended == !GetWindow().IsVisible(), "CellController::suspend: inconsistence!" ); + if ( !isSuspended( ) ) + { + CommitModifications(); + GetWindow().Hide( ); + GetWindow().Disable( ); + bSuspended = true; + } + } + + + void CellController::resume( ) + { + DBG_ASSERT( bSuspended == !GetWindow().IsVisible(), "CellController::resume: inconsistence!" ); + if ( isSuspended( ) ) + { + GetWindow().Enable( ); + GetWindow().Show( ); + bSuspended = false; + } + } + + + void CellController::CommitModifications() + { + // nothing to do in this base class + } + + + bool CellController::WantMouseEvent() const + { + return false; + } + + + void CellController::SetModified() + { + } + + + bool CellController::MoveAllowed(const KeyEvent&) const + { + return true; + } + +} // namespace svt + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/brwbox/editbrowsebox2.cxx b/svtools/source/brwbox/editbrowsebox2.cxx new file mode 100644 index 000000000..7c84cf5eb --- /dev/null +++ b/svtools/source/brwbox/editbrowsebox2.cxx @@ -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 . + */ + +#include <svtools/editbrowsebox.hxx> +#include <com/sun/star/accessibility/XAccessible.hpp> +#include <com/sun/star/accessibility/AccessibleEventId.hpp> +#include "editbrowseboximpl.hxx" +#include <comphelper/types.hxx> +#include <toolkit/helper/vclunohelper.hxx> +#include <vcl/accessiblefactory.hxx> +#include <vcl/svapp.hxx> +#include <osl/diagnose.h> +#include <tools/debug.hxx> + +namespace svt +{ + using namespace com::sun::star::accessibility; + using namespace com::sun::star::uno; + using namespace ::com::sun::star::accessibility::AccessibleEventId; + + +Reference< XAccessible > EditBrowseBox::CreateAccessibleCheckBoxCell(long _nRow, sal_uInt16 _nColumnPos,const TriState& eState) +{ + Reference< XAccessible > xAccessible( GetAccessible() ); + Reference< XAccessibleContext > xAccContext; + if ( xAccessible.is() ) + xAccContext = xAccessible->getAccessibleContext(); + + Reference< XAccessible > xReturn; + if ( xAccContext.is() ) + { + xReturn = getAccessibleFactory().createAccessibleCheckBoxCell( + xAccContext->getAccessibleChild( ::vcl::BBINDEX_TABLE ), + *this, + nullptr, + _nRow, + _nColumnPos, + eState, + true + ); + } + return xReturn; +} + +sal_Int32 EditBrowseBox::GetAccessibleControlCount() const +{ + return IsEditing() ? 1 : 0; +} + +void EditBrowseBox::implCreateActiveAccessible( ) +{ + DBG_ASSERT( IsEditing(), "EditBrowseBox::implCreateActiveAccessible: not to be called if we're not editing currently!" ); + DBG_ASSERT( !m_aImpl->m_xActiveCell.is(), "EditBrowseBox::implCreateActiveAccessible: not to be called if the old one is still alive!" ); + + if ( !(!m_aImpl->m_xActiveCell.is() && IsEditing()) ) + return; + + Reference< XAccessible > xCont = aController->GetWindow().GetAccessible(); + Reference< XAccessible > xMy = GetAccessible(); + if ( !(xMy.is() && xCont.is()) ) + return; + + m_aImpl->m_xActiveCell = getAccessibleFactory().createEditBrowseBoxTableCellAccess( + xMy, // parent accessible + xCont, // control accessible + VCLUnoHelper::GetInterface( &aController->GetWindow() ), // focus window (for notifications) + *this, // the browse box + GetCurRow(), + GetColumnPos( GetCurColumnId() ) + ); + + commitBrowseBoxEvent( CHILD, makeAny( m_aImpl->m_xActiveCell ), Any() ); +} + + +Reference< XAccessible > EditBrowseBox::CreateAccessibleControl( sal_Int32 _nIndex ) +{ + DBG_ASSERT( 0 == _nIndex, "EditBrowseBox::CreateAccessibleControl: invalid index!" ); + + if ( isAccessibleAlive() ) + { + if ( !m_aImpl->m_xActiveCell.is() ) + implCreateActiveAccessible(); + } + + return m_aImpl->m_xActiveCell; +} + +void EditBrowseBoxImpl::clearActiveCell() +{ + try + { + ::comphelper::disposeComponent(m_xActiveCell); + } + catch(const Exception&) + { + OSL_FAIL( "EditBrowseBoxImpl::clearActiveCell: caught an exception while disposing the AccessibleCell!" ); + } + + m_xActiveCell = nullptr; +} + +void EditBrowseBox::GrabTableFocus() +{ + if ( aController.is() ) + aController->GetWindow().GrabFocus(); +} + +void EditBrowseBox::DetermineFocus( const GetFocusFlags _nGetFocusFlags ) +{ + bool bFocus = ControlHasFocus(); + for (vcl::Window* pWindow = Application::GetFocusWindow(); + pWindow && !bFocus; + pWindow = pWindow->GetParent()) + bFocus = pWindow == this; + + if (bFocus == bHasFocus) + return; + + bHasFocus = bFocus; + + if ( !(GetBrowserFlags( ) & EditBrowseBoxFlags::SMART_TAB_TRAVEL) ) + return; + + if ( !(bHasFocus // we got the focus + && ( _nGetFocusFlags & GetFocusFlags::Tab )) // using the TAB key + ) + return; + + long nRows = GetRowCount(); + sal_uInt16 nCols = ColCount(); + + if ( ( nRows > 0 ) && ( nCols > 0 ) ) + { + if ( _nGetFocusFlags & GetFocusFlags::Forward ) + { + if ( GetColumnId( 0 ) != HandleColumnId ) + { + GoToRowColumnId( 0, GetColumnId( 0 ) ); + } + else + { // the first column is the handle column -> not focussable + if ( nCols > 1 ) + GoToRowColumnId( 0, GetColumnId( 1 ) ); + } + } + else if ( _nGetFocusFlags & GetFocusFlags::Backward ) + { + GoToRowColumnId( nRows - 1, GetColumnId( nCols -1 ) ); + } + } +} + +tools::Rectangle EditBrowseBox::GetFieldCharacterBounds(sal_Int32 _nRow,sal_Int32 _nColumnPos,sal_Int32 _nIndex) +{ + tools::Rectangle aRect; + if ( SeekRow(_nRow) ) + { + CellController* pController = GetController( + _nRow, GetColumnId( sal::static_int_cast< sal_uInt16 >(_nColumnPos) ) ); + if ( pController ) + aRect = pController->GetWindow().GetCharacterBounds(_nIndex); + } + return aRect; +} + +sal_Int32 EditBrowseBox::GetFieldIndexAtPoint(sal_Int32 _nRow,sal_Int32 _nColumnPos,const Point& _rPoint) +{ + sal_Int32 nRet = -1; + if ( SeekRow(_nRow) ) + { + CellController* pController = GetController( + _nRow, GetColumnId( sal::static_int_cast< sal_uInt16 >(_nColumnPos) ) ); + if ( pController ) + nRet = pController->GetWindow().GetIndexForPoint(_rPoint); + } + return nRet; +} + + +} // namespace svt + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/brwbox/editbrowseboximpl.hxx b/svtools/source/brwbox/editbrowseboximpl.hxx new file mode 100644 index 000000000..f71aab9b7 --- /dev/null +++ b/svtools/source/brwbox/editbrowseboximpl.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 . + */ +#pragma once + +#include <com/sun/star/accessibility/XAccessible.hpp> + +namespace svt +{ + // impl class for the class EditBrowseBox + class EditBrowseBoxImpl + { + public: + css::uno::Reference< css::accessibility::XAccessible > m_xActiveCell; + + void clearActiveCell(); + }; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/config/accessibilityoptions.cxx b/svtools/source/config/accessibilityoptions.cxx new file mode 100644 index 000000000..43fa4287f --- /dev/null +++ b/svtools/source/config/accessibilityoptions.cxx @@ -0,0 +1,414 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <svtools/accessibilityoptions.hxx> + +#include <unotools/configmgr.hxx> +#include <com/sun/star/uno/Any.hxx> + +#include <com/sun/star/beans/XPropertySet.hpp> +#include <com/sun/star/container/XNameAccess.hpp> +#include <comphelper/configurationhelper.hxx> +#include <comphelper/processfactory.hxx> + +#include <vcl/settings.hxx> +#include <vcl/svapp.hxx> +#include <rtl/instance.hxx> +#include <tools/diagnose_ex.h> + +#include "itemholder2.hxx" + +using namespace utl; +using namespace com::sun::star::uno; + +#define HELP_TIP_TIMEOUT 0xffff // max. timeout setting to pretend a non-timeout + +// class SvtAccessibilityOptions_Impl --------------------------------------------- + +class SvtAccessibilityOptions_Impl +{ +private: + css::uno::Reference< css::container::XNameAccess > m_xCfg; + +public: + SvtAccessibilityOptions_Impl(); + + void SetVCLSettings(); + bool GetIsForPagePreviews() const; + bool GetIsHelpTipsDisappear() const; + bool GetIsAllowAnimatedGraphics() const; + bool GetIsAllowAnimatedText() const; + bool GetIsAutomaticFontColor() const; + sal_Int16 GetHelpTipSeconds() const; + bool IsSelectionInReadonly() const; + sal_Int16 GetEdgeBlending() const; + sal_Int16 GetListBoxMaximumLineCount() const; + sal_Int16 GetColorValueSetColumnCount() const; + bool GetPreviewUsesCheckeredBackground() const; +}; + +// initialization of static members -------------------------------------- + +SvtAccessibilityOptions_Impl* SvtAccessibilityOptions::sm_pSingleImplConfig =nullptr; +sal_Int32 SvtAccessibilityOptions::sm_nAccessibilityRefCount(0); + +namespace +{ + struct SingletonMutex + : public rtl::Static< ::osl::Mutex, SingletonMutex > {}; +} + + +// class SvtAccessibilityOptions_Impl --------------------------------------------- + +SvtAccessibilityOptions_Impl::SvtAccessibilityOptions_Impl() +{ + try + { + m_xCfg.set( + ::comphelper::ConfigurationHelper::openConfig( + comphelper::getProcessComponentContext(), + "org.openoffice.Office.Common/Accessibility", + ::comphelper::EConfigurationModes::Standard ), + css::uno::UNO_QUERY); + } + catch(const css::uno::Exception&) + { + DBG_UNHANDLED_EXCEPTION("svtools.config"); + m_xCfg.clear(); + } +} + +bool SvtAccessibilityOptions_Impl::GetIsForPagePreviews() const +{ + css::uno::Reference< css::beans::XPropertySet > xNode(m_xCfg, css::uno::UNO_QUERY); + bool bRet = true; + + try + { + if(xNode.is()) + xNode->getPropertyValue("IsForPagePreviews") >>= bRet; + } + catch(const css::uno::Exception&) + { + DBG_UNHANDLED_EXCEPTION("svtools.config"); + } + return bRet; +} + +bool SvtAccessibilityOptions_Impl::GetIsHelpTipsDisappear() const +{ + css::uno::Reference< css::beans::XPropertySet > xNode(m_xCfg, css::uno::UNO_QUERY); + bool bRet = true; + + try + { + if(xNode.is()) + xNode->getPropertyValue("IsHelpTipsDisappear") >>= bRet; + } + catch(const css::uno::Exception&) + { + DBG_UNHANDLED_EXCEPTION("svtools.config"); + } + + return bRet; +} + +bool SvtAccessibilityOptions_Impl::GetIsAllowAnimatedGraphics() const +{ + css::uno::Reference< css::beans::XPropertySet > xNode(m_xCfg, css::uno::UNO_QUERY); + bool bRet = true; + + try + { + if(xNode.is()) + xNode->getPropertyValue("IsAllowAnimatedGraphics") >>= bRet; + } + catch(const css::uno::Exception&) + { + DBG_UNHANDLED_EXCEPTION("svtools.config"); + } + + return bRet; +} + +bool SvtAccessibilityOptions_Impl::GetIsAllowAnimatedText() const +{ + css::uno::Reference< css::beans::XPropertySet > xNode(m_xCfg, css::uno::UNO_QUERY); + bool bRet = true; + + try + { + if(xNode.is()) + xNode->getPropertyValue("IsAllowAnimatedText") >>= bRet; + } + catch(const css::uno::Exception&) + { + DBG_UNHANDLED_EXCEPTION("svtools.config"); + } + + return bRet; +} + +bool SvtAccessibilityOptions_Impl::GetIsAutomaticFontColor() const +{ + css::uno::Reference< css::beans::XPropertySet > xNode(m_xCfg, css::uno::UNO_QUERY); + bool bRet = false; + + try + { + if(xNode.is()) + xNode->getPropertyValue("IsAutomaticFontColor") >>= bRet; + } + catch(const css::uno::Exception&) + { + DBG_UNHANDLED_EXCEPTION("svtools.config"); + } + + return bRet; +} + +sal_Int16 SvtAccessibilityOptions_Impl::GetHelpTipSeconds() const +{ + css::uno::Reference< css::beans::XPropertySet > xNode(m_xCfg, css::uno::UNO_QUERY); + sal_Int16 nRet = 4; + + try + { + if(xNode.is()) + xNode->getPropertyValue("HelpTipSeconds") >>= nRet; + } + catch(const css::uno::Exception&) + { + DBG_UNHANDLED_EXCEPTION("svtools.config"); + } + + return nRet; +} + +bool SvtAccessibilityOptions_Impl::IsSelectionInReadonly() const +{ + css::uno::Reference< css::beans::XPropertySet > xNode(m_xCfg, css::uno::UNO_QUERY); + bool bRet = false; + + try + { + if(xNode.is()) + xNode->getPropertyValue("IsSelectionInReadonly") >>= bRet; + } + catch(const css::uno::Exception&) + { + DBG_UNHANDLED_EXCEPTION("svtools.config"); + } + + return bRet; +} + +sal_Int16 SvtAccessibilityOptions_Impl::GetEdgeBlending() const +{ + css::uno::Reference< css::beans::XPropertySet > xNode(m_xCfg, css::uno::UNO_QUERY); + sal_Int16 nRet = 35; + + try + { + if(xNode.is()) + xNode->getPropertyValue("EdgeBlending") >>= nRet; + } + catch(const css::uno::Exception&) + { + DBG_UNHANDLED_EXCEPTION("svtools.config"); + } + + return nRet; +} + +sal_Int16 SvtAccessibilityOptions_Impl::GetListBoxMaximumLineCount() const +{ + css::uno::Reference< css::beans::XPropertySet > xNode(m_xCfg, css::uno::UNO_QUERY); + sal_Int16 nRet = 25; + + try + { + if(xNode.is()) + xNode->getPropertyValue("ListBoxMaximumLineCount") >>= nRet; + } + catch(const css::uno::Exception&) + { + DBG_UNHANDLED_EXCEPTION("svtools.config"); + } + + return nRet; +} + +sal_Int16 SvtAccessibilityOptions_Impl::GetColorValueSetColumnCount() const +{ +#ifdef IOS + return 4; +#else + css::uno::Reference< css::beans::XPropertySet > xNode(m_xCfg, css::uno::UNO_QUERY); + sal_Int16 nRet = 12; + + try + { + if(xNode.is()) + xNode->getPropertyValue("ColorValueSetColumnCount") >>= nRet; + } + catch(const css::uno::Exception&) + { + DBG_UNHANDLED_EXCEPTION("svtools.config"); + } + + return nRet; +#endif +} + +bool SvtAccessibilityOptions_Impl::GetPreviewUsesCheckeredBackground() const +{ + css::uno::Reference< css::beans::XPropertySet > xNode(m_xCfg, css::uno::UNO_QUERY); + bool bRet = false; + + try + { + if(xNode.is()) + xNode->getPropertyValue("PreviewUsesCheckeredBackground") >>= bRet; + } + catch(const css::uno::Exception&) + { + DBG_UNHANDLED_EXCEPTION("svtools.config"); + } + + return bRet; +} + +void SvtAccessibilityOptions_Impl::SetVCLSettings() +{ + AllSettings aAllSettings(Application::GetSettings()); + StyleSettings aStyleSettings(aAllSettings.GetStyleSettings()); + HelpSettings aHelpSettings(aAllSettings.GetHelpSettings()); + bool StyleSettingsChanged(false); + + aHelpSettings.SetTipTimeout( GetIsHelpTipsDisappear() ? GetHelpTipSeconds() * 1000 : HELP_TIP_TIMEOUT); + aAllSettings.SetHelpSettings(aHelpSettings); + + const sal_Int16 nEdgeBlendingCountA(GetEdgeBlending()); + OSL_ENSURE(nEdgeBlendingCountA >= 0, "OOps, negative values for EdgeBlending are not allowed (!)"); + const sal_uInt16 nEdgeBlendingCountB(static_cast< sal_uInt16 >(nEdgeBlendingCountA >= 0 ? nEdgeBlendingCountA : 0)); + + if(aStyleSettings.GetEdgeBlending() != nEdgeBlendingCountB) + { + aStyleSettings.SetEdgeBlending(nEdgeBlendingCountB); + StyleSettingsChanged = true; + } + + const sal_Int16 nMaxLineCountA(GetListBoxMaximumLineCount()); + OSL_ENSURE(nMaxLineCountA >= 0, "OOps, negative values for ListBoxMaximumLineCount are not allowed (!)"); + const sal_uInt16 nMaxLineCountB(static_cast< sal_uInt16 >(nMaxLineCountA >= 0 ? nMaxLineCountA : 0)); + + if(aStyleSettings.GetListBoxMaximumLineCount() != nMaxLineCountB) + { + aStyleSettings.SetListBoxMaximumLineCount(nMaxLineCountB); + StyleSettingsChanged = true; + } + + const sal_Int16 nMaxColumnCountA(GetColorValueSetColumnCount()); + OSL_ENSURE(nMaxColumnCountA >= 0, "OOps, negative values for ColorValueSetColumnCount are not allowed (!)"); + const sal_uInt16 nMaxColumnCountB(static_cast< sal_uInt16 >(nMaxColumnCountA >= 0 ? nMaxColumnCountA : 0)); + + if(aStyleSettings.GetColorValueSetColumnCount() != nMaxColumnCountB) + { + aStyleSettings.SetColorValueSetColumnCount(nMaxColumnCountB); + StyleSettingsChanged = true; + } + + const bool bPreviewUsesCheckeredBackground(GetPreviewUsesCheckeredBackground()); + + if(aStyleSettings.GetPreviewUsesCheckeredBackground() != bPreviewUsesCheckeredBackground) + { + aStyleSettings.SetPreviewUsesCheckeredBackground(bPreviewUsesCheckeredBackground); + StyleSettingsChanged = true; + } + + if(StyleSettingsChanged) + { + aAllSettings.SetStyleSettings(aStyleSettings); + Application::MergeSystemSettings(aAllSettings); + } + + Application::SetSettings(aAllSettings); +} + +// class SvtAccessibilityOptions -------------------------------------------------- + +SvtAccessibilityOptions::SvtAccessibilityOptions() +{ + if (!utl::ConfigManager::IsFuzzing()) + { + ::osl::MutexGuard aGuard( SingletonMutex::get() ); + if(!sm_pSingleImplConfig) + { + sm_pSingleImplConfig = new SvtAccessibilityOptions_Impl; + svtools::ItemHolder2::holdConfigItem(EItem::AccessibilityOptions); + } + ++sm_nAccessibilityRefCount; + } + //StartListening( *sm_pSingleImplConfig, sal_True ); +} + +SvtAccessibilityOptions::~SvtAccessibilityOptions() +{ + //EndListening( *sm_pSingleImplConfig, sal_True ); + ::osl::MutexGuard aGuard( SingletonMutex::get() ); + if( !--sm_nAccessibilityRefCount ) + { + //if( sm_pSingleImplConfig->IsModified() ) + // sm_pSingleImplConfig->Commit(); + DELETEZ( sm_pSingleImplConfig ); + } +} + +bool SvtAccessibilityOptions::GetIsForPagePreviews() const +{ + return sm_pSingleImplConfig->GetIsForPagePreviews(); +} +bool SvtAccessibilityOptions::GetIsAllowAnimatedGraphics() const +{ + return sm_pSingleImplConfig->GetIsAllowAnimatedGraphics(); +} +bool SvtAccessibilityOptions::GetIsAllowAnimatedText() const +{ + return sm_pSingleImplConfig->GetIsAllowAnimatedText(); +} +bool SvtAccessibilityOptions::GetIsAutomaticFontColor() const +{ + return sm_pSingleImplConfig->GetIsAutomaticFontColor(); +} +bool SvtAccessibilityOptions::IsSelectionInReadonly() const +{ + return sm_pSingleImplConfig->IsSelectionInReadonly(); +} + + +void SvtAccessibilityOptions::SetVCLSettings() +{ + sm_pSingleImplConfig->SetVCLSettings(); +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/config/apearcfg.cxx b/svtools/source/config/apearcfg.cxx new file mode 100644 index 000000000..681b9282e --- /dev/null +++ b/svtools/source/config/apearcfg.cxx @@ -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 . + */ + + +#include <svtools/apearcfg.hxx> + +#include <o3tl/any.hxx> +#include <tools/debug.hxx> +#include <vcl/settings.hxx> +#include <vcl/svapp.hxx> + +#include <com/sun/star/uno/Sequence.hxx> + +#define DEFAULT_DRAGMODE DragMode::SystemDep +#define DEFAULT_SNAPMODE SnapType::ToButton +#define DEFAULT_AAMINHEIGHT 8 + +using namespace ::com::sun::star::uno; + +bool SvtTabAppearanceCfg::bInitialized = false; + +SvtTabAppearanceCfg::SvtTabAppearanceCfg() + :ConfigItem("Office.Common/View") + ,nDragMode ( DEFAULT_DRAGMODE ) + ,nSnapMode ( DEFAULT_SNAPMODE ) + ,nMiddleMouse ( MouseMiddleButtonAction::AutoScroll ) + ,nAAMinPixelHeight ( DEFAULT_AAMINHEIGHT ) + ,bFontAntialiasing ( true ) + ,bMenuMouseFollow ( false ) +{ + const Sequence<OUString>& rNames = GetPropertyNames(); + Sequence<Any> aValues = GetProperties(rNames); + const Any* pValues = aValues.getConstArray(); + DBG_ASSERT(aValues.getLength() == rNames.getLength(), "GetProperties failed"); + + if(aValues.getLength() != rNames.getLength()) + return; + + for(int nProp = 0; nProp < rNames.getLength(); ++nProp, ++pValues) + { + if(pValues->hasValue()) + { + switch(nProp) + { + case 0: //"Window/Drag" + { + short nTmp; + if (*pValues >>= nTmp) + nDragMode = static_cast<DragMode>(nTmp); + break; + } + case 1: bMenuMouseFollow = *o3tl::doAccess<bool>(*pValues); break; //"Menu/FollowMouse", + case 2: + { + short nTmp; + if (*pValues >>= nTmp) + nSnapMode = static_cast<SnapType>(nTmp); //"Dialog/MousePositioning", + break; + } + case 3: { short nTmp = 0; *pValues >>= nTmp; nMiddleMouse = static_cast<MouseMiddleButtonAction>(nTmp); break; } //"Dialog/MiddleMouseButton", + case 4: bFontAntialiasing = *o3tl::doAccess<bool>(*pValues); break; // "FontAntialising/Enabled", + case 5: *pValues >>= nAAMinPixelHeight; break; // "FontAntialising/MinPixelHeight", + } + } + } +} + +SvtTabAppearanceCfg::~SvtTabAppearanceCfg( ) +{ +} + +const Sequence<OUString>& SvtTabAppearanceCfg::GetPropertyNames() +{ + static Sequence<OUString> const aNames + { + "Window/Drag" // 0 + ,"Menu/FollowMouse" // 1 + ,"Dialog/MousePositioning" // 2 + ,"Dialog/MiddleMouseButton" // 3 + ,"FontAntiAliasing/Enabled" // 4 + ,"FontAntiAliasing/MinPixelHeight" // 5 + }; + return aNames; +} + +void SvtTabAppearanceCfg::ImplCommit() +{ + const Sequence<OUString>& rNames = GetPropertyNames(); + Sequence<Any> aValues(rNames.getLength()); + Any* pValues = aValues.getArray(); + + for(int nProp = 0; nProp < rNames.getLength(); nProp++) + { + switch(nProp) + { + case 0: pValues[nProp] <<= static_cast<short>(nDragMode); break; // "Window/Drag", + case 1: pValues[nProp] <<= bMenuMouseFollow; break; // "Menu/FollowMouse", + case 2: pValues[nProp] <<= static_cast<short>(nSnapMode); break; // "Dialog/MousePositioning", + case 3: pValues[nProp] <<= static_cast<short>(nMiddleMouse); break; // "Dialog/MiddleMouseButton", + case 4: pValues[nProp] <<= bFontAntialiasing; break; // "FontAntialising/Enabled", + case 5: pValues[nProp] <<= nAAMinPixelHeight; break; // "FontAntialising/MinPixelHeight", + } + } + PutProperties(rNames, aValues); +} + +void SvtTabAppearanceCfg::Notify( const css::uno::Sequence< OUString >& ) +{ +} + +void SvtTabAppearanceCfg::SetSnapMode ( SnapType nSet ) +{ + nSnapMode = nSet; + SetModified(); +} + +void SvtTabAppearanceCfg::SetMiddleMouseButton ( MouseMiddleButtonAction nSet ) +{ + nMiddleMouse = nSet; + SetModified(); +} + +void SvtTabAppearanceCfg::SetApplicationDefaults ( Application* pApp ) +{ + AllSettings hAppSettings = Application::GetSettings(); + StyleSettings hAppStyle = hAppSettings.GetStyleSettings(); + + // Look & Feel + + // SetStandard...Styles() resets the UseSystemUIFonts flag, + // but we don't want to change it now, so save the flag before ... + bool bUseSystemUIFonts = hAppStyle.GetUseSystemUIFonts(); + hAppStyle.SetStandardStyles(); + // and set it here + hAppStyle.SetUseSystemUIFonts( bUseSystemUIFonts ); + + // font anti aliasing + hAppStyle.SetAntialiasingMinPixelHeight( nAAMinPixelHeight ); + hAppStyle.SetDisplayOptions( bFontAntialiasing ? DisplayOptions::NONE : DisplayOptions::AADisable ); + + // Mouse Snap + + MouseSettings hMouseSettings = hAppSettings.GetMouseSettings(); + MouseSettingsOptions nMouseOptions = hMouseSettings.GetOptions(); + + nMouseOptions &= ~ MouseSettingsOptions(MouseSettingsOptions::AutoCenterPos | MouseSettingsOptions::AutoDefBtnPos); + + switch ( nSnapMode ) + { + case SnapType::ToButton: + nMouseOptions |= MouseSettingsOptions::AutoDefBtnPos; + break; + case SnapType::ToMiddle: + nMouseOptions |= MouseSettingsOptions::AutoCenterPos; + break; + case SnapType::NONE: + default: + break; + } + hMouseSettings.SetOptions(nMouseOptions); + hMouseSettings.SetMiddleButtonAction(nMiddleMouse); + + // Merge and Publish Settings + + MouseFollowFlags nFollow = hMouseSettings.GetFollow(); + if(bMenuMouseFollow) + nFollow |= MouseFollowFlags::Menu; + else + nFollow &= ~MouseFollowFlags::Menu; + hMouseSettings.SetFollow( nFollow ); + + hAppSettings.SetMouseSettings( hMouseSettings ); + + hAppSettings.SetStyleSettings( hAppStyle ); + Application::MergeSystemSettings ( hAppSettings ); // Allow system-settings to apply + pApp->OverrideSystemSettings ( hAppSettings ); + + Application::SetSettings ( hAppSettings ); +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/config/colorcfg.cxx b/svtools/source/config/colorcfg.cxx new file mode 100644 index 000000000..d2973a1d9 --- /dev/null +++ b/svtools/source/config/colorcfg.cxx @@ -0,0 +1,599 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <svtools/colorcfg.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> +#include <com/sun/star/beans/PropertyValue.hpp> +#include <comphelper/processfactory.hxx> +#include <unotools/configitem.hxx> +#include <unotools/confignode.hxx> +#include <unotools/configmgr.hxx> +#include <unotools/configpaths.hxx> +#include <com/sun/star/uno/Sequence.h> +#include <svl/poolitem.hxx> +#include <osl/mutex.hxx> + +#include "itemholder2.hxx" + +#include <vcl/svapp.hxx> +#include <vcl/event.hxx> +#include <vcl/settings.hxx> +#include <rtl/instance.hxx> + + +using namespace utl; +using namespace com::sun::star; + +static const char g_sIsVisible[] = "/IsVisible"; + + +namespace svtools +{ + +static sal_Int32 nColorRefCount_Impl = 0; +namespace +{ + struct ColorMutex_Impl + : public rtl::Static< ::osl::Mutex, ColorMutex_Impl > {}; +} + +ColorConfig_Impl* ColorConfig::m_pImpl = nullptr; + +class ColorConfig_Impl : public utl::ConfigItem +{ + ColorConfigValue m_aConfigValues[ColorConfigEntryCount]; + OUString m_sLoadedScheme; + bool m_bAutoDetectSystemHC; + + virtual void ImplCommit() override; + +public: + explicit ColorConfig_Impl(); + virtual ~ColorConfig_Impl() override; + + void Load(const OUString& rScheme); + void CommitCurrentSchemeName(); + //changes the name of the current scheme but doesn't load it! + void SetCurrentSchemeName(const OUString& rSchemeName) {m_sLoadedScheme = rSchemeName;} + virtual void Notify( const uno::Sequence<OUString>& aPropertyNames) override; + + const ColorConfigValue& GetColorConfigValue(ColorConfigEntry eValue) + {return m_aConfigValues[eValue];} + void SetColorConfigValue(ColorConfigEntry eValue, + const ColorConfigValue& rValue ); + + const OUString& GetLoadedScheme() const {return m_sLoadedScheme;} + + uno::Sequence< OUString> GetSchemeNames(); + + void AddScheme(const OUString& rNode); + void RemoveScheme(const OUString& rNode); + using ConfigItem::SetModified; + using ConfigItem::ClearModified; + void SettingsChanged(); + bool GetAutoDetectSystemHC() const {return m_bAutoDetectSystemHC;} + + DECL_LINK( DataChangedEventListener, VclSimpleEvent&, void ); + + void ImplUpdateApplicationSettings(); +}; + +namespace { + +uno::Sequence< OUString> GetPropertyNames(const OUString& rScheme) +{ + struct ColorConfigEntryData_Impl + { + OUStringLiteral cName; + bool bCanBeVisible; + }; + static const ColorConfigEntryData_Impl cNames[] = + { + { OUStringLiteral("/DocColor") ,false }, + { OUStringLiteral("/DocBoundaries") ,true }, + { OUStringLiteral("/AppBackground") ,false }, + { OUStringLiteral("/ObjectBoundaries"),true }, + { OUStringLiteral("/TableBoundaries") ,true }, + { OUStringLiteral("/FontColor") ,false }, + { OUStringLiteral("/Links") ,true }, + { OUStringLiteral("/LinksVisited") ,true }, + { OUStringLiteral("/Spell") ,false }, + { OUStringLiteral("/SmartTags") ,false }, + { OUStringLiteral("/Shadow") , true }, + { OUStringLiteral("/WriterTextGrid") ,false }, + { OUStringLiteral("/WriterFieldShadings"),true }, + { OUStringLiteral("/WriterIdxShadings") ,true }, + { OUStringLiteral("/WriterDirectCursor") ,true }, + { OUStringLiteral("/WriterScriptIndicator") ,false }, + { OUStringLiteral("/WriterSectionBoundaries") ,true }, + { OUStringLiteral("/WriterHeaderFooterMark") ,false }, + { OUStringLiteral("/WriterPageBreaks") ,false }, + { OUStringLiteral("/HTMLSGML") ,false }, + { OUStringLiteral("/HTMLComment") ,false }, + { OUStringLiteral("/HTMLKeyword") ,false }, + { OUStringLiteral("/HTMLUnknown") ,false }, + { OUStringLiteral("/CalcGrid") ,false }, + { OUStringLiteral("/CalcPageBreak"), false }, + { OUStringLiteral("/CalcPageBreakManual"), false }, + { OUStringLiteral("/CalcPageBreakAutomatic"), false }, + { OUStringLiteral("/CalcDetective") ,false }, + { OUStringLiteral("/CalcDetectiveError") ,false }, + { OUStringLiteral("/CalcReference") ,false }, + { OUStringLiteral("/CalcNotesBackground") ,false }, + { OUStringLiteral("/CalcValue") ,false }, + { OUStringLiteral("/CalcFormula") ,false }, + { OUStringLiteral("/CalcText") ,false }, + { OUStringLiteral("/CalcProtectedBackground") ,false }, + { OUStringLiteral("/DrawGrid") ,true }, + { OUStringLiteral("/BASICIdentifier"), false }, + { OUStringLiteral("/BASICComment") , false }, + { OUStringLiteral("/BASICNumber") , false }, + { OUStringLiteral("/BASICString") , false }, + { OUStringLiteral("/BASICOperator") , false }, + { OUStringLiteral("/BASICKeyword") , false }, + { OUStringLiteral("/BASICError"), false }, + { OUStringLiteral("/SQLIdentifier"), false }, + { OUStringLiteral("/SQLNumber"), false }, + { OUStringLiteral("/SQLString"), false }, + { OUStringLiteral("/SQLOperator"), false }, + { OUStringLiteral("/SQLKeyword"), false }, + { OUStringLiteral("/SQLParameter"), false }, + { OUStringLiteral("/SQLComment"), false } + }; + + uno::Sequence<OUString> aNames(2 * ColorConfigEntryCount); + OUString* pNames = aNames.getArray(); + int nIndex = 0; + OUString sBase = "ColorSchemes/" + + utl::wrapConfigurationElementName(rScheme); + for(sal_Int32 i = 0; i < ColorConfigEntryCount; ++i) + { + OUString sBaseName = sBase + cNames[i].cName; + pNames[nIndex++] = sBaseName + "/Color"; + if(cNames[i].bCanBeVisible) + { + pNames[nIndex++] = sBaseName + g_sIsVisible; + } + } + aNames.realloc(nIndex); + return aNames; +} + +} + +ColorConfig_Impl::ColorConfig_Impl() : + ConfigItem("Office.UI/ColorScheme"), + m_bAutoDetectSystemHC(true) +{ + //try to register on the root node - if possible + uno::Sequence < OUString > aNames(1); + EnableNotification( aNames ); + + if (!utl::ConfigManager::IsFuzzing()) + Load(OUString()); + + ImplUpdateApplicationSettings(); + + ::Application::AddEventListener( LINK(this, ColorConfig_Impl, DataChangedEventListener) ); + +} + +ColorConfig_Impl::~ColorConfig_Impl() +{ + ::Application::RemoveEventListener( LINK(this, ColorConfig_Impl, DataChangedEventListener) ); +} + +void ColorConfig_Impl::Load(const OUString& rScheme) +{ + OUString sScheme(rScheme); + if(sScheme.isEmpty()) + { + //detect current scheme name + uno::Sequence < OUString > aCurrent { "CurrentColorScheme" }; + uno::Sequence< uno::Any > aCurrentVal = GetProperties( aCurrent ); + aCurrentVal.getConstArray()[0] >>= sScheme; + } + m_sLoadedScheme = sScheme; + + uno::Sequence < OUString > aColorNames = GetPropertyNames(sScheme); + uno::Sequence< uno::Any > aColors = GetProperties( aColorNames ); + const uno::Any* pColors = aColors.getConstArray(); + const OUString* pColorNames = aColorNames.getConstArray(); + sal_Int32 nIndex = 0; + for(int i = 0; i < ColorConfigEntryCount && aColors.getLength() > nIndex; ++i) + { + if(pColors[nIndex].hasValue()) + { + sal_Int32 nTmp(0); + pColors[nIndex] >>= nTmp; + m_aConfigValues[i].nColor = Color(nTmp); + } + else + m_aConfigValues[i].nColor = COL_AUTO; + nIndex++; + if(nIndex >= aColors.getLength()) + break; + //test for visibility property + if(pColorNames[nIndex].endsWith(g_sIsVisible)) + m_aConfigValues[i].bIsVisible = Any2Bool(pColors[nIndex++]); + } + // fdo#71511: check if we are running in a11y autodetect + { + utl::OConfigurationNode aNode = utl::OConfigurationTreeRoot::tryCreateWithComponentContext(comphelper::getProcessComponentContext(),"org.openoffice.Office.Common/Accessibility" ); + if(aNode.isValid()) + { + uno::Any aValue = aNode.getNodeValue(OUString("AutoDetectSystemHC")); + aValue >>= m_bAutoDetectSystemHC; + } + } +} + +void ColorConfig_Impl::Notify( const uno::Sequence<OUString>& ) +{ + //loading via notification always uses the default setting + Load(OUString()); + NotifyListeners(ConfigurationHints::NONE); +} + +void ColorConfig_Impl::ImplCommit() +{ + uno::Sequence < OUString > aColorNames = GetPropertyNames(m_sLoadedScheme); + uno::Sequence < beans::PropertyValue > aPropValues(aColorNames.getLength()); + beans::PropertyValue* pPropValues = aPropValues.getArray(); + const OUString* pColorNames = aColorNames.getConstArray(); + sal_Int32 nIndex = 0; + for(int i = 0; i < ColorConfigEntryCount && aColorNames.getLength() > nIndex; ++i) + { + pPropValues[nIndex].Name = pColorNames[nIndex]; + //save automatic colors as void value + if(m_aConfigValues[i].nColor != COL_AUTO) + pPropValues[nIndex].Value <<= m_aConfigValues[i].nColor; + + nIndex++; + if(nIndex >= aColorNames.getLength()) + break; + //test for visibility property + if(pColorNames[nIndex].endsWith(g_sIsVisible)) + { + pPropValues[nIndex].Name = pColorNames[nIndex]; + pPropValues[nIndex].Value <<= m_aConfigValues[i].bIsVisible; + nIndex++; + } + } + SetSetProperties("ColorSchemes", aPropValues); + + CommitCurrentSchemeName(); +} + +void ColorConfig_Impl::CommitCurrentSchemeName() +{ + //save current scheme name + uno::Sequence < OUString > aCurrent { "CurrentColorScheme" }; + uno::Sequence< uno::Any > aCurrentVal(1); + aCurrentVal.getArray()[0] <<= m_sLoadedScheme; + PutProperties(aCurrent, aCurrentVal); +} + +void ColorConfig_Impl::SetColorConfigValue(ColorConfigEntry eValue, const ColorConfigValue& rValue ) +{ + if(rValue != m_aConfigValues[eValue]) + { + m_aConfigValues[eValue] = rValue; + SetModified(); + } +} + +uno::Sequence< OUString> ColorConfig_Impl::GetSchemeNames() +{ + return GetNodeNames("ColorSchemes"); +} + +void ColorConfig_Impl::AddScheme(const OUString& rScheme) +{ + if(ConfigItem::AddNode("ColorSchemes", rScheme)) + { + m_sLoadedScheme = rScheme; + Commit(); + } +} + +void ColorConfig_Impl::RemoveScheme(const OUString& rScheme) +{ + uno::Sequence< OUString > aElements { rScheme }; + ClearNodeElements("ColorSchemes", aElements); +} + +void ColorConfig_Impl::SettingsChanged() +{ + SolarMutexGuard aVclGuard; + + ImplUpdateApplicationSettings(); + + NotifyListeners(ConfigurationHints::NONE); +} + +IMPL_LINK( ColorConfig_Impl, DataChangedEventListener, VclSimpleEvent&, rEvent, void ) +{ + if ( rEvent.GetId() == VclEventId::ApplicationDataChanged ) + { + DataChangedEvent* pData = static_cast<DataChangedEvent*>(static_cast<VclWindowEvent&>(rEvent).GetData()); + if ( (pData->GetType() == DataChangedEventType::SETTINGS) && + (pData->GetFlags() & AllSettingsFlags::STYLE) ) + { + SettingsChanged(); + } + } +} + + +/** updates the font color in the vcl window settings */ +void ColorConfig_Impl::ImplUpdateApplicationSettings() +{ + Application* pApp = GetpApp(); + if( !pApp ) + return; + + AllSettings aSettings = Application::GetSettings(); + StyleSettings aStyleSettings( aSettings.GetStyleSettings() ); + + ColorConfigValue aRet = GetColorConfigValue(svtools::FONTCOLOR); + if(COL_AUTO == aRet.nColor) + aRet.nColor = ColorConfig::GetDefaultColor(svtools::FONTCOLOR); + + Color aFontColor(aRet.nColor); + + if( aStyleSettings.GetFontColor() != aFontColor ) + { + aStyleSettings.SetFontColor( aFontColor ); + + aSettings.SetStyleSettings( aStyleSettings ); + Application::SetSettings( aSettings ); + } +} + +ColorConfig::ColorConfig() +{ + if (utl::ConfigManager::IsFuzzing()) + return; + ::osl::MutexGuard aGuard( ColorMutex_Impl::get() ); + if ( !m_pImpl ) + { + m_pImpl = new ColorConfig_Impl; + svtools::ItemHolder2::holdConfigItem(EItem::ColorConfig); + } + ++nColorRefCount_Impl; + m_pImpl->AddListener(this); +} + +ColorConfig::~ColorConfig() +{ + if (utl::ConfigManager::IsFuzzing()) + return; + ::osl::MutexGuard aGuard( ColorMutex_Impl::get() ); + m_pImpl->RemoveListener(this); + if(!--nColorRefCount_Impl) + { + delete m_pImpl; + m_pImpl = nullptr; + } +} + +Color ColorConfig::GetDefaultColor(ColorConfigEntry eEntry) +{ + static const Color aAutoColors[] = + { + COL_WHITE, // DOCCOLOR + COL_LIGHTGRAY, // DOCBOUNDARIES + Color(0xDFDFDE), // APPBACKGROUND + COL_LIGHTGRAY, // OBJECTBOUNDARIES + COL_LIGHTGRAY, // TABLEBOUNDARIES + COL_BLACK, // FONTCOLOR + COL_BLUE, // LINKS + Color(0x0000cc), // LINKSVISITED + COL_LIGHTRED, // SPELL + COL_LIGHTMAGENTA, // SMARTTAGS + COL_GRAY, // SHADOWCOLOR + COL_LIGHTGRAY, // WRITERTEXTGRID + COL_LIGHTGRAY, // WRITERFIELDSHADIN + COL_LIGHTGRAY, // WRITERIDXSHADINGS + COL_BLACK, // WRITERDIRECTCURSOR + COL_GREEN, //WRITERSCRIPTINDICATOR + COL_LIGHTGRAY, //WRITERSECTIONBOUNDARIES + Color(0x0369a3), //WRITERHEADERFOOTERMARK, + COL_BLUE, //WRITERPAGEBREAKS, + COL_LIGHTBLUE, // HTMLSGML + COL_LIGHTGREEN, // HTMLCOMMENT + COL_LIGHTRED, // HTMLKEYWORD + COL_GRAY, // HTMLUNKNOWN + COL_GRAY3, // CALCGRID + COL_BLUE, //CALCPAGEBREAK + Color(0x2300dc), //CALCPAGEBREAKMANUAL + COL_GRAY7, //CALCPAGEBREAKAUTOMATIC + COL_LIGHTBLUE, // CALCDETECTIVE + COL_LIGHTRED, // CALCDETECTIVEERROR + Color(0xef0fff), // CALCREFERENCE + Color(0xffffc0), // CALCNOTESBACKGROUND + COL_LIGHTBLUE, // CALCVALUE + COL_GREEN, // CALCFORMULA + COL_BLACK, // CALCTEXT + COL_LIGHTGRAY, // CALCPROTECTEDBACKGROUND + COL_GRAY7, // DRAWGRID + COL_GREEN, // BASICIDENTIFIER, + COL_GRAY, // BASICCOMMENT, + COL_LIGHTRED, // BASICNUMBER, + COL_LIGHTRED, // BASICSTRING, + COL_BLUE, // BASICOPERATOR, + COL_BLUE, // BASICKEYWORD, + COL_RED, //BASICERROR + Color(0x009900), // SQLIDENTIFIER + COL_BLACK, // SQLNUMBER + Color(0xCE7B00), // SQLSTRING + COL_BLACK, // SQLOPERATOR + Color(0x0000E6), // SQLKEYWORD + Color(0x259D9D), // SQLPARAMETER + COL_GRAY, // SQLCOMMENT + }; + Color aRet; + switch(eEntry) + { + case APPBACKGROUND : + aRet = Application::GetSettings().GetStyleSettings().GetWorkspaceColor(); + break; + + case LINKS : + aRet = Application::GetSettings().GetStyleSettings().GetLinkColor(); + break; + + case LINKSVISITED : + aRet = Application::GetSettings().GetStyleSettings().GetVisitedLinkColor(); + break; + + default: + aRet = aAutoColors[eEntry]; + } + // fdo#71511: if in autodetected a11y HC mode, do pull background color from theme + if(m_pImpl && m_pImpl->GetAutoDetectSystemHC()) + { + switch(eEntry) + { + case DOCCOLOR : + aRet = Application::GetSettings().GetStyleSettings().GetWindowColor(); + break; + case FONTCOLOR : + aRet = Application::GetSettings().GetStyleSettings().GetWindowTextColor(); + break; + default: + break; + } + } + return aRet; +} + +ColorConfigValue ColorConfig::GetColorValue(ColorConfigEntry eEntry, bool bSmart) const +{ + ColorConfigValue aRet; + + if (m_pImpl) + aRet = m_pImpl->GetColorConfigValue(eEntry); + + if (bSmart && aRet.nColor == COL_AUTO) + aRet.nColor = ColorConfig::GetDefaultColor(eEntry); + + return aRet; +} + +EditableColorConfig::EditableColorConfig() : + m_pImpl(new ColorConfig_Impl), + m_bModified(false) +{ + m_pImpl->BlockBroadcasts(true); +} + +EditableColorConfig::~EditableColorConfig() +{ + m_pImpl->BlockBroadcasts(false); + if(m_bModified) + m_pImpl->SetModified(); + if(m_pImpl->IsModified()) + m_pImpl->Commit(); +} + +uno::Sequence< OUString > EditableColorConfig::GetSchemeNames() const +{ + return m_pImpl->GetSchemeNames(); +} + +void EditableColorConfig::DeleteScheme(const OUString& rScheme ) +{ + m_pImpl->RemoveScheme(rScheme); +} + +void EditableColorConfig::AddScheme(const OUString& rScheme ) +{ + m_pImpl->AddScheme(rScheme); +} + +void EditableColorConfig::LoadScheme(const OUString& rScheme ) +{ + if(m_bModified) + m_pImpl->SetModified(); + if(m_pImpl->IsModified()) + m_pImpl->Commit(); + m_bModified = false; + m_pImpl->Load(rScheme); + //the name of the loaded scheme has to be committed separately + m_pImpl->CommitCurrentSchemeName(); +} + +const OUString& EditableColorConfig::GetCurrentSchemeName()const +{ + return m_pImpl->GetLoadedScheme(); +} + +// Changes the name of the current scheme but doesn't load it! +void EditableColorConfig::SetCurrentSchemeName(const OUString& rScheme) +{ + m_pImpl->SetCurrentSchemeName(rScheme); + m_pImpl->CommitCurrentSchemeName(); +} + +const ColorConfigValue& EditableColorConfig::GetColorValue( + ColorConfigEntry eEntry)const +{ + return m_pImpl->GetColorConfigValue(eEntry); +} + +void EditableColorConfig::SetColorValue( + ColorConfigEntry eEntry, const ColorConfigValue& rValue) +{ + m_pImpl->SetColorConfigValue(eEntry, rValue); + m_pImpl->ClearModified(); + m_bModified = true; +} + +void EditableColorConfig::SetModified() +{ + m_bModified = true; +} + +void EditableColorConfig::Commit() +{ + if(m_bModified) + m_pImpl->SetModified(); + if(m_pImpl->IsModified()) + m_pImpl->Commit(); + m_bModified = false; +} + +void EditableColorConfig::DisableBroadcast() +{ + m_pImpl->BlockBroadcasts(true); +} + +void EditableColorConfig::EnableBroadcast() +{ + m_pImpl->BlockBroadcasts(false); +} + + +}//namespace svtools + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/config/extcolorcfg.cxx b/svtools/source/config/extcolorcfg.cxx new file mode 100644 index 000000000..e23a2000b --- /dev/null +++ b/svtools/source/config/extcolorcfg.cxx @@ -0,0 +1,664 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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/config.h> + +#include <map> + +#include <svtools/extcolorcfg.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> +#include <com/sun/star/beans/PropertyValue.hpp> +#include <tools/color.hxx> +#include <unotools/configitem.hxx> +#include <com/sun/star/uno/Sequence.h> +#include <comphelper/sequence.hxx> +#include <svl/hint.hxx> +#include <osl/mutex.hxx> +#include <sal/log.hxx> +#include <osl/diagnose.h> + +#include <vcl/svapp.hxx> +#include <vcl/settings.hxx> +#include <vcl/event.hxx> +#include <rtl/instance.hxx> + + +using namespace utl; +using namespace com::sun::star; + + +namespace svtools +{ + +static sal_Int32 nExtendedColorRefCount_Impl = 0; +namespace +{ + struct ColorMutex_Impl + : public rtl::Static< ::osl::Mutex, ColorMutex_Impl > {}; +} + +ExtendedColorConfig_Impl* ExtendedColorConfig::m_pImpl = nullptr; + +class ExtendedColorConfig_Impl : public utl::ConfigItem, public SfxBroadcaster +{ + typedef std::map<OUString, OUString> TDisplayNames; + typedef std::map<OUString, ExtendedColorConfigValue> TConfigValues; + typedef ::std::vector<TConfigValues::iterator> TMapPos; + typedef ::std::pair< TConfigValues, TMapPos > TComponentMapping; + typedef std::map<OUString, TComponentMapping> TComponents; + TComponents m_aConfigValues; + TDisplayNames m_aComponentDisplayNames; + ::std::vector<TComponents::iterator> m_aConfigValuesPos; + + OUString m_sLoadedScheme; + bool m_bIsBroadcastEnabled; + static bool m_bLockBroadcast; + static bool m_bBroadcastWhenUnlocked; + + uno::Sequence< OUString> GetPropertyNames(const OUString& rScheme); + void FillComponentColors(const uno::Sequence < OUString >& _rComponents,const TDisplayNames& _rDisplayNames); + + virtual void ImplCommit() override; + +public: + explicit ExtendedColorConfig_Impl(); + virtual ~ExtendedColorConfig_Impl() override; + + void Load(const OUString& rScheme); + void CommitCurrentSchemeName(); + //changes the name of the current scheme but doesn't load it! + void SetCurrentSchemeName(const OUString& rSchemeName) {m_sLoadedScheme = rSchemeName;} + bool ExistsScheme(const OUString& _sSchemeName); + virtual void Notify( const uno::Sequence<OUString>& aPropertyNames) override; + + 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& _sName,sal_uInt32 _nPos) const; + + ExtendedColorConfigValue GetColorConfigValue(const OUString& _sComponentName,const OUString& _sName) + { + TComponents::iterator aFind = m_aConfigValues.find(_sComponentName); + if ( aFind != m_aConfigValues.end() ) + { + TConfigValues::iterator aFind2 = aFind->second.first.find(_sName); + if ( aFind2 != aFind->second.first.end() ) + return aFind2->second; + } +#if OSL_DEBUG_LEVEL > 0 + SAL_WARN( "svtools", "Could find the required config:\n" + "component: " << _sComponentName + << "\nname: " << _sName ); +#endif + return ExtendedColorConfigValue(); + } + void SetColorConfigValue(const OUString& _sName, + const ExtendedColorConfigValue& rValue ); + + void AddScheme(const OUString& rNode); + void RemoveScheme(const OUString& rNode); + using ConfigItem::SetModified; + using ConfigItem::ClearModified; + void SettingsChanged(); + + static void DisableBroadcast(); + static void EnableBroadcast(); + + static void LockBroadcast(); + static void UnlockBroadcast(); + + DECL_LINK( DataChangedEventListener, VclSimpleEvent&, void ); +}; + +uno::Sequence< OUString> ExtendedColorConfig_Impl::GetPropertyNames(const OUString& rScheme) +{ + uno::Sequence< OUString> aNames(GetNodeNames(rScheme)); + for(OUString & i : aNames) + { + i = rScheme + "/" + i; + } + return aNames; +} + +sal_Int32 ExtendedColorConfig_Impl::GetComponentCount() const +{ + return m_aConfigValues.size(); +} + +sal_Int32 ExtendedColorConfig_Impl::GetComponentColorCount(const OUString& _sName) const +{ + sal_Int32 nSize = 0; + TComponents::const_iterator aFind = m_aConfigValues.find(_sName); + if ( aFind != m_aConfigValues.end() ) + { + nSize = aFind->second.first.size(); + } + return nSize; +} + +ExtendedColorConfigValue ExtendedColorConfig_Impl::GetComponentColorConfigValue(const OUString& _sName,sal_uInt32 _nPos) const +{ + TComponents::const_iterator aFind = m_aConfigValues.find(_sName); + if ( aFind != m_aConfigValues.end() ) + { + if ( _nPos < aFind->second.second.size() ) + { + return aFind->second.second[_nPos]->second; + } + } + return ExtendedColorConfigValue(); +} + +OUString ExtendedColorConfig_Impl::GetComponentDisplayName(const OUString& _sComponentName) const +{ + OUString sRet; + TDisplayNames::const_iterator aFind = m_aComponentDisplayNames.find(_sComponentName); + if ( aFind != m_aComponentDisplayNames.end() ) + sRet = aFind->second; + return sRet; +} + +OUString ExtendedColorConfig_Impl::GetComponentName(sal_uInt32 _nPos) const +{ + OUString sRet; + if ( _nPos < m_aConfigValuesPos.size() ) + sRet = m_aConfigValuesPos[_nPos]->first; + return sRet; +} + +bool ExtendedColorConfig_Impl::m_bLockBroadcast = false; +bool ExtendedColorConfig_Impl::m_bBroadcastWhenUnlocked = false; +ExtendedColorConfig_Impl::ExtendedColorConfig_Impl() : + ConfigItem("Office.ExtendedColorScheme"), + m_bIsBroadcastEnabled(true) +{ + //try to register on the root node - if possible + uno::Sequence < OUString > aNames(1); + EnableNotification( aNames ); + Load(OUString()); + + ::Application::AddEventListener( LINK(this, ExtendedColorConfig_Impl, DataChangedEventListener) ); + +} + +ExtendedColorConfig_Impl::~ExtendedColorConfig_Impl() +{ + ::Application::RemoveEventListener( LINK(this, ExtendedColorConfig_Impl, DataChangedEventListener) ); +} + +void ExtendedColorConfig_Impl::DisableBroadcast() +{ + if ( ExtendedColorConfig::m_pImpl ) + ExtendedColorConfig::m_pImpl->m_bIsBroadcastEnabled = false; +} + +void ExtendedColorConfig_Impl::EnableBroadcast() +{ + if ( ExtendedColorConfig::m_pImpl ) + ExtendedColorConfig::m_pImpl->m_bIsBroadcastEnabled = true; +} + +static void lcl_addString(uno::Sequence < OUString >& _rSeq,const OUString& _sAdd) +{ + for(OUString & i : _rSeq) + i += _sAdd; +} + +void ExtendedColorConfig_Impl::Load(const OUString& rScheme) +{ + m_aComponentDisplayNames.clear(); + m_aConfigValuesPos.clear(); + m_aConfigValues.clear(); + + // fill display names + TDisplayNames aDisplayNameMap; + uno::Sequence < OUString > aComponentNames = GetPropertyNames("EntryNames"); + OUString sDisplayName("/DisplayName"); + for(OUString & componentName : aComponentNames) + { + uno::Sequence < OUString > aComponentDisplayNames(1); + aComponentDisplayNames[0] = componentName + sDisplayName; + uno::Sequence< uno::Any > aComponentDisplayNamesValue = GetProperties( aComponentDisplayNames ); + OUString sComponentDisplayName; + if ( aComponentDisplayNamesValue.hasElements() && (aComponentDisplayNamesValue[0] >>= sComponentDisplayName) ) + { + m_aComponentDisplayNames.emplace(componentName.getToken(1, '/'),sComponentDisplayName); + } + + componentName += "/Entries"; + uno::Sequence < OUString > aDisplayNames = GetPropertyNames(componentName); + lcl_addString(aDisplayNames,sDisplayName); + + uno::Sequence< uno::Any > aDisplayNamesValue = GetProperties( aDisplayNames ); + + const OUString* pDispIter = aDisplayNames.getConstArray(); + const OUString* pDispEnd = pDispIter + aDisplayNames.getLength(); + for(sal_Int32 j = 0;pDispIter != pDispEnd;++pDispIter,++j) + { + sal_Int32 nIndex = 0; + pDispIter->getToken(0,'/',nIndex); + OUString sName = pDispIter->copy(nIndex); + sName = sName.copy(0,sName.lastIndexOf(sDisplayName)); + OUString sCurrentDisplayName; + aDisplayNamesValue[j] >>= sCurrentDisplayName; + aDisplayNameMap.emplace(sName,sCurrentDisplayName); + } + } + + // load color settings + OUString sScheme(rScheme); + + if(sScheme.isEmpty()) + { + //detect current scheme name + uno::Sequence < OUString > aCurrent { "ExtendedColorScheme/CurrentColorScheme" }; + uno::Sequence< uno::Any > aCurrentVal = GetProperties( aCurrent ); + aCurrentVal.getConstArray()[0] >>= sScheme; + } // if(!sScheme.getLength()) + + m_sLoadedScheme = sScheme; + OUString sBase = "ExtendedColorScheme/ColorSchemes/" + + sScheme; + + bool bFound = ExistsScheme(sScheme); + if ( bFound ) + { + aComponentNames = GetPropertyNames(sBase); + FillComponentColors(aComponentNames,aDisplayNameMap); + } + + if ( m_sLoadedScheme.isEmpty() ) + m_sLoadedScheme = "default"; + + if ( sScheme != "default" ) + { + if ( ExistsScheme("default") ) + { + aComponentNames = GetPropertyNames("ExtendedColorScheme/ColorSchemes/default"); + FillComponentColors(aComponentNames,aDisplayNameMap); + } + } + if ( !bFound && !sScheme.isEmpty() ) + { + AddScheme(sScheme); + CommitCurrentSchemeName(); + } +} + +void ExtendedColorConfig_Impl::FillComponentColors(const uno::Sequence < OUString >& _rComponents,const TDisplayNames& _rDisplayNames) +{ + const OUString sColorEntries("/Entries"); + for(OUString const & component : _rComponents) + { + OUString sComponentName = component.copy(component.lastIndexOf('/')+1); + if ( m_aConfigValues.find(sComponentName) == m_aConfigValues.end() ) + { + OUString sEntry = component + sColorEntries; + + uno::Sequence < OUString > aColorNames = GetPropertyNames(sEntry); + uno::Sequence < OUString > aDefaultColorNames = aColorNames; + + const OUString sColor("/Color"); + const OUString sDefaultColor("/DefaultColor"); + lcl_addString(aColorNames,sColor); + lcl_addString(aDefaultColorNames,sDefaultColor); + uno::Sequence< uno::Any > aColors = GetProperties( aColorNames ); + const uno::Any* pColors = aColors.getConstArray(); + + uno::Sequence< uno::Any > aDefaultColors = GetProperties( aDefaultColorNames ); + bool bDefaultColorFound = aDefaultColors.hasElements(); + const uno::Any* pDefaultColors = aDefaultColors.getConstArray(); + + OUString* pColorIter = aColorNames.getArray(); + OUString* pColorEnd = pColorIter + aColorNames.getLength(); + + m_aConfigValuesPos.push_back(m_aConfigValues.emplace(sComponentName,TComponentMapping(TConfigValues(),TMapPos())).first); + TConfigValues& aConfigValues = (*m_aConfigValuesPos.rbegin())->second.first; + TMapPos& aConfigValuesPos = (*m_aConfigValuesPos.rbegin())->second.second; + for(int i = 0; pColorIter != pColorEnd; ++pColorIter ,++i) + { + if ( aConfigValues.find(*pColorIter) == aConfigValues.end() ) + { + sal_Int32 nIndex = 0; + pColorIter->getToken(2,'/',nIndex); + OUString sName(pColorIter->copy(nIndex)),sDisplayName; + OUString sTemp = sName.copy(0,sName.lastIndexOf(sColor)); + + TDisplayNames::const_iterator aFind = _rDisplayNames.find(sTemp); + sName = sName.getToken(2, '/'); + OSL_ENSURE(aFind != _rDisplayNames.end(),"DisplayName is not in EntryNames config list!"); + if ( aFind != _rDisplayNames.end() ) + sDisplayName = aFind->second; + + OSL_ENSURE(pColors[i].hasValue(),"Color config entry has NIL as color value set!"); + OSL_ENSURE(pDefaultColors[i].hasValue(),"Color config entry has NIL as color value set!"); + Color nColor, nDefaultColor; + pColors[i] >>= nColor; + if ( bDefaultColorFound ) + pDefaultColors[i] >>= nDefaultColor; + else + nDefaultColor = nColor; + ExtendedColorConfigValue aValue(sName,sDisplayName,nColor,nDefaultColor); + aConfigValuesPos.push_back(aConfigValues.emplace(sName,aValue).first); + } + } // for(int i = 0; pColorIter != pColorEnd; ++pColorIter ,++i) + } + } +} + +void ExtendedColorConfig_Impl::Notify( const uno::Sequence<OUString>& /*rPropertyNames*/) +{ + //loading via notification always uses the default setting + Load(OUString()); + + SolarMutexGuard aVclGuard; + + if(m_bLockBroadcast) + { + m_bBroadcastWhenUnlocked = true; + } + else + Broadcast(SfxHint(SfxHintId::ColorsChanged)); +} + +void ExtendedColorConfig_Impl::ImplCommit() +{ + if ( m_sLoadedScheme.isEmpty() ) + return; + const OUString sColorEntries("Entries"); + const OUString sColor("/Color"); + OUString sBase = "ExtendedColorScheme/ColorSchemes/" + + m_sLoadedScheme; + const OUString s_sSep("/"); + + for (auto const& configValue : m_aConfigValues) + { + if ( ConfigItem::AddNode(sBase, configValue.first) ) + { + OUString sNode = sBase + + s_sSep + + configValue.first + //ConfigItem::AddNode(sNode, sColorEntries); + + s_sSep + + sColorEntries; + + uno::Sequence < beans::PropertyValue > aPropValues(configValue.second.first.size()); + beans::PropertyValue* pPropValues = aPropValues.getArray(); + for (auto const& elem : configValue.second.first) + { + pPropValues->Name = sNode + s_sSep + elem.first; + ConfigItem::AddNode(sNode, elem.first); + pPropValues->Name += sColor; + pPropValues->Value <<= elem.second.getColor(); + // the default color will never be changed + ++pPropValues; + } + SetSetProperties("ExtendedColorScheme/ColorSchemes", aPropValues); + } + } + + CommitCurrentSchemeName(); +} + +void ExtendedColorConfig_Impl::CommitCurrentSchemeName() +{ + //save current scheme name + uno::Sequence < OUString > aCurrent { "ExtendedColorScheme/CurrentColorScheme" }; + uno::Sequence< uno::Any > aCurrentVal(1); + aCurrentVal.getArray()[0] <<= m_sLoadedScheme; + PutProperties(aCurrent, aCurrentVal); +} + +bool ExtendedColorConfig_Impl::ExistsScheme(const OUString& _sSchemeName) +{ + OUString sBase("ExtendedColorScheme/ColorSchemes"); + + uno::Sequence < OUString > aComponentNames = GetPropertyNames(sBase); + sBase += "/" + _sSchemeName; + return comphelper::findValue(aComponentNames, sBase) != -1; +} + +void ExtendedColorConfig_Impl::SetColorConfigValue(const OUString& _sName, const ExtendedColorConfigValue& rValue ) +{ + TComponents::iterator aFind = m_aConfigValues.find(_sName); + if ( aFind != m_aConfigValues.end() ) + { + TConfigValues::iterator aFind2 = aFind->second.first.find(rValue.getName()); + if ( aFind2 != aFind->second.first.end() ) + aFind2->second = rValue; + SetModified(); + } +} + +void ExtendedColorConfig_Impl::AddScheme(const OUString& rScheme) +{ + if(ConfigItem::AddNode("ExtendedColorScheme/ColorSchemes", rScheme)) + { + m_sLoadedScheme = rScheme; + Commit(); + } +} + +void ExtendedColorConfig_Impl::RemoveScheme(const OUString& rScheme) +{ + uno::Sequence< OUString > aElements { rScheme }; + ClearNodeElements("ExtendedColorScheme/ColorSchemes", aElements); +} + +void ExtendedColorConfig_Impl::SettingsChanged() +{ + SolarMutexGuard aVclGuard; + + Broadcast( SfxHint( SfxHintId::ColorsChanged ) ); +} + +void ExtendedColorConfig_Impl::LockBroadcast() +{ + m_bLockBroadcast = true; +} + +void ExtendedColorConfig_Impl::UnlockBroadcast() +{ + if ( m_bBroadcastWhenUnlocked ) + { + m_bBroadcastWhenUnlocked = ExtendedColorConfig::m_pImpl != nullptr; + if ( m_bBroadcastWhenUnlocked ) + { + if (ExtendedColorConfig::m_pImpl->m_bIsBroadcastEnabled) + { + m_bBroadcastWhenUnlocked = false; + ExtendedColorConfig::m_pImpl->Broadcast(SfxHint(SfxHintId::ColorsChanged)); + } + } + } + m_bLockBroadcast = false; +} + +IMPL_LINK( ExtendedColorConfig_Impl, DataChangedEventListener, VclSimpleEvent&, rEvent, void ) +{ + if ( rEvent.GetId() == VclEventId::ApplicationDataChanged ) + { + DataChangedEvent* pData = static_cast<DataChangedEvent*>(static_cast<VclWindowEvent&>(rEvent).GetData()); + if ( (pData->GetType() == DataChangedEventType::SETTINGS) && + (pData->GetFlags() & AllSettingsFlags::STYLE) ) + { + SettingsChanged(); + } + } +} + + +ExtendedColorConfig::ExtendedColorConfig() +{ + ::osl::MutexGuard aGuard( ColorMutex_Impl::get() ); + if ( !m_pImpl ) + m_pImpl = new ExtendedColorConfig_Impl; + ++nExtendedColorRefCount_Impl; + StartListening( *m_pImpl); +} + +ExtendedColorConfig::~ExtendedColorConfig() +{ + ::osl::MutexGuard aGuard( ColorMutex_Impl::get() ); + EndListening( *m_pImpl); + if(!--nExtendedColorRefCount_Impl) + { + delete m_pImpl; + m_pImpl = nullptr; + } +} + +ExtendedColorConfigValue ExtendedColorConfig::GetColorValue(const OUString& _sComponentName,const OUString& _sName)const +{ + return m_pImpl->GetColorConfigValue(_sComponentName,_sName); +} + +sal_Int32 ExtendedColorConfig::GetComponentCount() const +{ + return m_pImpl->GetComponentCount(); +} + +sal_Int32 ExtendedColorConfig::GetComponentColorCount(const OUString& _sName) const +{ + return m_pImpl->GetComponentColorCount(_sName); +} + +ExtendedColorConfigValue ExtendedColorConfig::GetComponentColorConfigValue(const OUString& _sName,sal_uInt32 _nPos) const +{ + return m_pImpl->GetComponentColorConfigValue(_sName,_nPos); +} + +OUString ExtendedColorConfig::GetComponentName(sal_uInt32 _nPos) const +{ + return m_pImpl->GetComponentName(_nPos); +} + +OUString ExtendedColorConfig::GetComponentDisplayName(const OUString& _sComponentName) const +{ + return m_pImpl->GetComponentDisplayName(_sComponentName); +} + +void ExtendedColorConfig::Notify( SfxBroadcaster& /*rBC*/, const SfxHint& rHint ) +{ + SolarMutexGuard aVclGuard; + + Broadcast( rHint ); +} + +EditableExtendedColorConfig::EditableExtendedColorConfig() : + m_pImpl(new ExtendedColorConfig_Impl), + m_bModified(false) +{ + ExtendedColorConfig_Impl::LockBroadcast(); +} + +EditableExtendedColorConfig::~EditableExtendedColorConfig() +{ + ExtendedColorConfig_Impl::UnlockBroadcast(); + if(m_bModified) + m_pImpl->SetModified(); + if(m_pImpl->IsModified()) + m_pImpl->Commit(); +} + +void EditableExtendedColorConfig::DeleteScheme(const OUString& rScheme ) +{ + m_pImpl->RemoveScheme(rScheme); +} + +void EditableExtendedColorConfig::AddScheme(const OUString& rScheme ) +{ + m_pImpl->AddScheme(rScheme); +} + +void EditableExtendedColorConfig::LoadScheme(const OUString& rScheme ) +{ + if(m_bModified) + m_pImpl->SetModified(); + if(m_pImpl->IsModified()) + m_pImpl->Commit(); + m_bModified = false; + m_pImpl->Load(rScheme); + //the name of the loaded scheme has to be committed separately + m_pImpl->CommitCurrentSchemeName(); +} + +// Changes the name of the current scheme but doesn't load it! +void EditableExtendedColorConfig::SetCurrentSchemeName(const OUString& rScheme) +{ + m_pImpl->SetCurrentSchemeName(rScheme); + m_pImpl->CommitCurrentSchemeName(); +} + +void EditableExtendedColorConfig::SetColorValue( + const OUString& _sName, const ExtendedColorConfigValue& rValue) +{ + m_pImpl->SetColorConfigValue(_sName, rValue); + m_pImpl->ClearModified(); + m_bModified = true; +} + +void EditableExtendedColorConfig::SetModified() +{ + m_bModified = true; +} + +void EditableExtendedColorConfig::Commit() +{ + if(m_bModified) + m_pImpl->SetModified(); + if(m_pImpl->IsModified()) + m_pImpl->Commit(); + m_bModified = false; +} + +void EditableExtendedColorConfig::DisableBroadcast() +{ + ExtendedColorConfig_Impl::DisableBroadcast(); +} + +void EditableExtendedColorConfig::EnableBroadcast() +{ + ExtendedColorConfig_Impl::EnableBroadcast(); +} + +sal_Int32 EditableExtendedColorConfig::GetComponentCount() const +{ + return m_pImpl->GetComponentCount(); +} + +sal_Int32 EditableExtendedColorConfig::GetComponentColorCount(const OUString& _sName) const +{ + return m_pImpl->GetComponentColorCount(_sName); +} + +ExtendedColorConfigValue EditableExtendedColorConfig::GetComponentColorConfigValue(const OUString& _sName,sal_uInt32 _nPos) const +{ + return m_pImpl->GetComponentColorConfigValue(_sName,_nPos); +} + +OUString EditableExtendedColorConfig::GetComponentName(sal_uInt32 _nPos) const +{ + return m_pImpl->GetComponentName(_nPos); +} +}//namespace svtools + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/config/fontsubstconfig.cxx b/svtools/source/config/fontsubstconfig.cxx new file mode 100644 index 000000000..e0fb350d8 --- /dev/null +++ b/svtools/source/config/fontsubstconfig.cxx @@ -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 . + */ + +#include <svtools/fontsubstconfig.hxx> +#include <com/sun/star/beans/PropertyValue.hpp> +#include <com/sun/star/uno/Sequence.hxx> +#include <o3tl/any.hxx> +#include <tools/debug.hxx> +#include <vcl/outdev.hxx> + +#include <vector> + +using namespace utl; +using namespace com::sun::star; +using namespace com::sun::star::uno; +using namespace com::sun::star::beans; + + +const char cReplacement[] = "Replacement"; +const char cFontPairs[] = "FontPairs"; + +const char cReplaceFont[] = "ReplaceFont"; +const char cSubstituteFont[]= "SubstituteFont"; +const char cOnScreenOnly[] = "OnScreenOnly"; +const char cAlways[] = "Always"; + +typedef std::vector<SubstitutionStruct> SubstitutionStructArr; + +struct SvtFontSubstConfig_Impl +{ + SubstitutionStructArr aSubstArr; +}; + +SvtFontSubstConfig::SvtFontSubstConfig() : + ConfigItem("Office.Common/Font/Substitution"), + bIsEnabled(false), + pImpl(new SvtFontSubstConfig_Impl) +{ + Sequence<OUString> aNames { cReplacement }; + Sequence<Any> aValues = GetProperties(aNames); + DBG_ASSERT(aValues.getConstArray()[0].hasValue(), "no value available"); + if(aValues.getConstArray()[0].hasValue()) + bIsEnabled = *o3tl::doAccess<bool>(aValues.getConstArray()[0]); + + OUString sPropPrefix(cFontPairs); + const Sequence<OUString> aNodeNames = GetNodeNames(sPropPrefix, ConfigNameFormat::LocalPath); + Sequence<OUString> aPropNames(aNodeNames.getLength() * 4); + OUString* pNames = aPropNames.getArray(); + sal_Int32 nName = 0; + sPropPrefix += "/"; + for(const OUString& rNodeName : aNodeNames) + { + OUString sStart = sPropPrefix + rNodeName + "/"; + pNames[nName++] = sStart + cReplaceFont; + pNames[nName++] = sStart + cSubstituteFont; + pNames[nName++] = sStart + cAlways; + pNames[nName++] = sStart + cOnScreenOnly; + } + Sequence<Any> aNodeValues = GetProperties(aPropNames); + const Any* pNodeValues = aNodeValues.getConstArray(); + nName = 0; + for(sal_Int32 nNode = 0; nNode < aNodeNames.getLength(); nNode++) + { + SubstitutionStruct aInsert; + pNodeValues[nName++] >>= aInsert.sFont; + pNodeValues[nName++] >>= aInsert.sReplaceBy; + aInsert.bReplaceAlways = *o3tl::doAccess<bool>(pNodeValues[nName++]); + aInsert.bReplaceOnScreenOnly = *o3tl::doAccess<bool>(pNodeValues[nName++]); + pImpl->aSubstArr.push_back(aInsert); + } +} + +SvtFontSubstConfig::~SvtFontSubstConfig() +{ +} + +void SvtFontSubstConfig::Notify( const css::uno::Sequence< OUString >& ) +{ +} + +void SvtFontSubstConfig::ImplCommit() +{ + PutProperties({cReplacement}, {css::uno::Any(bIsEnabled)}); + + OUString sNode(cFontPairs); + if(pImpl->aSubstArr.empty()) + ClearNodeSet(sNode); + else + { + Sequence<PropertyValue> aSetValues(4 * pImpl->aSubstArr.size()); + PropertyValue* pSetValues = aSetValues.getArray(); + sal_Int32 nSetValue = 0; + + const OUString sReplaceFont(cReplaceFont); + const OUString sSubstituteFont(cSubstituteFont); + const OUString sAlways(cAlways); + const OUString sOnScreenOnly(cOnScreenOnly); + + for(size_t i = 0; i < pImpl->aSubstArr.size(); i++) + { + OUString sPrefix = sNode + "/_" + OUString::number(i) + "/"; + + SubstitutionStruct& rSubst = pImpl->aSubstArr[i]; + pSetValues[nSetValue].Name = sPrefix; pSetValues[nSetValue].Name += sReplaceFont; + pSetValues[nSetValue++].Value <<= rSubst.sFont; + pSetValues[nSetValue].Name = sPrefix; pSetValues[nSetValue].Name += sSubstituteFont; + pSetValues[nSetValue++].Value <<= rSubst.sReplaceBy; + pSetValues[nSetValue].Name = sPrefix; pSetValues[nSetValue].Name += sAlways; + pSetValues[nSetValue++].Value <<= rSubst.bReplaceAlways; + pSetValues[nSetValue].Name = sPrefix; pSetValues[nSetValue].Name += sOnScreenOnly; + pSetValues[nSetValue++].Value <<= rSubst.bReplaceOnScreenOnly; + } + ReplaceSetProperties(sNode, aSetValues); + } +} + +sal_Int32 SvtFontSubstConfig::SubstitutionCount() const +{ + return pImpl->aSubstArr.size(); +} + +void SvtFontSubstConfig::ClearSubstitutions() +{ + pImpl->aSubstArr.clear(); +} + +const SubstitutionStruct* SvtFontSubstConfig::GetSubstitution(sal_Int32 nPos) +{ + sal_Int32 nCount = static_cast<sal_Int32>(pImpl->aSubstArr.size()); + DBG_ASSERT(nPos >= 0 && nPos < nCount, "illegal array index"); + if(nPos >= 0 && nPos < nCount) + return &pImpl->aSubstArr[nPos]; + return nullptr; +} + +void SvtFontSubstConfig::AddSubstitution(const SubstitutionStruct& rToAdd) +{ + pImpl->aSubstArr.push_back(rToAdd); +} + +void SvtFontSubstConfig::Apply() +{ + OutputDevice::BeginFontSubstitution(); + + // remove old substitutions + OutputDevice::RemoveFontsSubstitute(); + + // read new substitutions + sal_Int32 nCount = IsEnabled() ? SubstitutionCount() : 0; + + for (sal_Int32 i = 0; i < nCount; i++) + { + AddFontSubstituteFlags nFlags = AddFontSubstituteFlags::NONE; + const SubstitutionStruct* pSubs = GetSubstitution(i); + if(pSubs->bReplaceAlways) + nFlags |= AddFontSubstituteFlags::ALWAYS; + if(pSubs->bReplaceOnScreenOnly) + nFlags |= AddFontSubstituteFlags::ScreenOnly; + OutputDevice::AddFontSubstitute( pSubs->sFont, pSubs->sReplaceBy, nFlags ); + } + + OutputDevice::EndFontSubstitution(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/config/helpopt.cxx b/svtools/source/config/helpopt.cxx new file mode 100644 index 000000000..1137caaef --- /dev/null +++ b/svtools/source/config/helpopt.cxx @@ -0,0 +1,305 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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/config.h> + +#include <svtools/helpopt.hxx> +#include <unotools/configitem.hxx> +#include <tools/debug.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> +#include <comphelper/sequence.hxx> +#include <vcl/help.hxx> +#include <osl/mutex.hxx> +#include <sal/log.hxx> + +#include "itemholder2.hxx" + +using namespace utl; +using namespace com::sun::star::uno; +using namespace com::sun::star; + +namespace { + //global + std::weak_ptr<SvtHelpOptions_Impl> g_pHelpOptions; + +enum class HelpProperty +{ + ExtendedHelp = 0, + HelpTips = 1, + Locale = 2, + System = 3, + StyleSheet = 4, + OfflineHelpPopUp = 5 +}; + +} + +class SvtHelpOptions_Impl : public utl::ConfigItem +{ + bool bExtendedHelp; + bool bHelpTips; + bool bOfflineHelpPopUp; + OUString aLocale; + OUString aSystem; + OUString sHelpStyleSheet; + + static Sequence< OUString > const & GetPropertyNames(); + + virtual void ImplCommit() final override; + +public: + SvtHelpOptions_Impl(); + ~SvtHelpOptions_Impl() override; + + virtual void Notify( const css::uno::Sequence< OUString >& aPropertyNames ) override; + void Load( const css::uno::Sequence< OUString>& aPropertyNames); + + void SetExtendedHelp( bool b ) { bExtendedHelp= b; SetModified(); } + bool IsExtendedHelp() const { return bExtendedHelp; } + void SetHelpTips( bool b ) { bHelpTips = b; SetModified(); } + bool IsHelpTips() const { return bHelpTips; } + void SetOfflineHelpPopUp(bool b) { bOfflineHelpPopUp = b; SetModified();} + bool IsOfflineHelpPopUp() const { return bOfflineHelpPopUp;} + const OUString& GetSystem() const { return aSystem; } + + const OUString& GetHelpStyleSheet()const{return sHelpStyleSheet;} + void SetHelpStyleSheet(const OUString& rStyleSheet){sHelpStyleSheet = rStyleSheet; SetModified();} + + static ::osl::Mutex & getInitMutex(); +}; + +Sequence< OUString > const & SvtHelpOptions_Impl::GetPropertyNames() +{ + static Sequence<OUString> const aNames + { + "ExtendedTip", + "Tip", + "Locale", + "System", + "HelpStyleSheet", + "BuiltInHelpNotInstalledPopUp" + }; + + return aNames; +} + +::osl::Mutex & SvtHelpOptions_Impl::getInitMutex() +{ + static ::osl::Mutex ourMutex; + + return ourMutex; +} + +SvtHelpOptions_Impl::SvtHelpOptions_Impl() + : ConfigItem( "Office.Common/Help" ) + , bExtendedHelp( false ) + , bHelpTips( true ) + , bOfflineHelpPopUp( true) +{ + Sequence< OUString > aNames = GetPropertyNames(); + Load( aNames ); + EnableNotification( aNames ); +} + +SvtHelpOptions_Impl::~SvtHelpOptions_Impl() +{ + if ( IsModified() ) + Commit(); +} + +void SvtHelpOptions_Impl::Load(const uno::Sequence< OUString>& rPropertyNames) +{ + const uno::Sequence< OUString> aInternalPropertyNames( GetPropertyNames()); + Sequence< Any > aValues = GetProperties( rPropertyNames ); + const Any* pValues = aValues.getConstArray(); + DBG_ASSERT( aValues.getLength() == rPropertyNames.getLength(), "GetProperties failed" ); + if ( aValues.getLength() != rPropertyNames.getLength() ) + return; + + for ( int nProp = 0; nProp < rPropertyNames.getLength(); nProp++ ) + { + assert(pValues[nProp].hasValue() && "property value missing"); + if ( pValues[nProp].hasValue() ) + { + bool bTmp; + OUString aTmpStr; + sal_Int32 nTmpInt = 0; + if ( pValues[nProp] >>= bTmp ) + { + switch ( static_cast< HelpProperty >( + comphelper::findValue(aInternalPropertyNames, rPropertyNames[nProp]) ) ) + { + case HelpProperty::ExtendedHelp: + bExtendedHelp = bTmp; + break; + case HelpProperty::HelpTips: + bHelpTips = bTmp; + break; + case HelpProperty::OfflineHelpPopUp: + bOfflineHelpPopUp = bTmp; + break; + default: + SAL_WARN( "svtools.config", "Wrong Member!" ); + break; + } + } + else if ( pValues[nProp] >>= aTmpStr ) + { + switch ( static_cast< HelpProperty >(nProp) ) + { + case HelpProperty::Locale: + aLocale = aTmpStr; + break; + + case HelpProperty::System: + aSystem = aTmpStr; + break; + case HelpProperty::StyleSheet: + sHelpStyleSheet = aTmpStr; + break; + default: + SAL_WARN( "svtools.config", "Wrong Member!" ); + break; + } + } + else if ( pValues[nProp] >>= nTmpInt ) + { + SAL_WARN( "svtools.config", "Wrong Member!" ); + } + else + { + SAL_WARN( "svtools.config", "Wrong Type!" ); + } + } + } + if ( IsHelpTips() != Help::IsQuickHelpEnabled() ) + IsHelpTips() ? Help::EnableQuickHelp() : Help::DisableQuickHelp(); + if ( IsExtendedHelp() != Help::IsBalloonHelpEnabled() ) + IsExtendedHelp() ? Help::EnableBalloonHelp() : Help::DisableBalloonHelp(); +} + +void SvtHelpOptions_Impl::ImplCommit() +{ + Sequence< OUString > aNames = GetPropertyNames(); + Sequence< Any > aValues( aNames.getLength() ); + Any* pValues = aValues.getArray(); + for ( int nProp = 0; nProp < aNames.getLength(); nProp++ ) + { + switch ( static_cast< HelpProperty >(nProp) ) + { + case HelpProperty::ExtendedHelp: + pValues[nProp] <<= bExtendedHelp; + break; + + case HelpProperty::HelpTips: + pValues[nProp] <<= bHelpTips; + break; + + case HelpProperty::Locale: + pValues[nProp] <<= aLocale; + break; + + case HelpProperty::System: + pValues[nProp] <<= aSystem; + break; + case HelpProperty::StyleSheet: + pValues[nProp] <<= sHelpStyleSheet; + break; + case HelpProperty::OfflineHelpPopUp: + pValues[nProp] <<= bOfflineHelpPopUp; + break; + + } + } + + PutProperties( aNames, aValues ); +} + +void SvtHelpOptions_Impl::Notify( const Sequence<OUString>& aPropertyNames ) +{ + Load( aPropertyNames ); +} + +SvtHelpOptions::SvtHelpOptions() +{ + // Global access, must be guarded (multithreading) + ::osl::MutexGuard aGuard( SvtHelpOptions_Impl::getInitMutex() ); + + pImpl = g_pHelpOptions.lock(); + if ( !pImpl ) + { + pImpl = std::make_shared<SvtHelpOptions_Impl>(); + g_pHelpOptions = pImpl; + svtools::ItemHolder2::holdConfigItem(EItem::HelpOptions); + } +} + +SvtHelpOptions::~SvtHelpOptions() +{ + // Global access, must be guarded (multithreading) + ::osl::MutexGuard aGuard( SvtHelpOptions_Impl::getInitMutex() ); + + pImpl.reset(); +} + +void SvtHelpOptions::SetExtendedHelp( bool b ) +{ + pImpl->SetExtendedHelp( b ); +} + +bool SvtHelpOptions::IsExtendedHelp() const +{ + return pImpl->IsExtendedHelp(); +} +void SvtHelpOptions::SetOfflineHelpPopUp (bool b ) +{ + pImpl->SetOfflineHelpPopUp( b ); +} + +bool SvtHelpOptions::IsOfflineHelpPopUp() const +{ + return pImpl->IsOfflineHelpPopUp(); +} +void SvtHelpOptions::SetHelpTips( bool b ) +{ + pImpl->SetHelpTips( b ); +} + +bool SvtHelpOptions::IsHelpTips() const +{ + return pImpl->IsHelpTips(); +} + +OUString const & SvtHelpOptions::GetSystem() const +{ + return pImpl->GetSystem(); +} + +const OUString& SvtHelpOptions::GetHelpStyleSheet()const +{ + return pImpl->GetHelpStyleSheet(); +} + +void SvtHelpOptions::SetHelpStyleSheet(const OUString& rStyleSheet) +{ + pImpl->SetHelpStyleSheet(rStyleSheet); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/config/htmlcfg.cxx b/svtools/source/config/htmlcfg.cxx new file mode 100644 index 000000000..fbd7f57e2 --- /dev/null +++ b/svtools/source/config/htmlcfg.cxx @@ -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 . + */ + +#include <sal/config.h> + +#include <o3tl/any.hxx> +#include <osl/thread.h> +#include <svtools/htmlcfg.hxx> +#include <svtools/parhtml.hxx> +#include <unotools/syslocale.hxx> +#include <tools/debug.hxx> +#include <rtl/instance.hxx> +#include <o3tl/typed_flags_set.hxx> +#include <com/sun/star/uno/Sequence.hxx> + +namespace { + +enum class HtmlCfgFlags { + NONE = 0x000, + UnknownTags = 0x001, + StarBasic = 0x008, + LocalGrf = 0x010, + PrintLayoutExtension = 0x020, + IgnoreFontFamily = 0x040, + IsBasicWarning = 0x080, + NumbersEnglishUS = 0x100, +}; + +} + +namespace o3tl { + template<> struct typed_flags<HtmlCfgFlags> : is_typed_flags<HtmlCfgFlags, 0x1f9> {}; +} + +using namespace utl; +using namespace com::sun::star::uno; + + +struct HtmlOptions_Impl +{ + HtmlCfgFlags nFlags; + sal_Int32 nExportMode; + sal_Int32 aFontSizeArr[HTML_FONT_COUNT]; + sal_Int32 eEncoding; + bool bIsEncodingDefault; + + HtmlOptions_Impl() : + nFlags(HtmlCfgFlags::LocalGrf|HtmlCfgFlags::IsBasicWarning), + nExportMode(HTML_CFG_NS40), + eEncoding( osl_getThreadTextEncoding() ), + bIsEncodingDefault(true) + { + aFontSizeArr[0] = HTMLFONTSZ1_DFLT; + aFontSizeArr[1] = HTMLFONTSZ2_DFLT; + aFontSizeArr[2] = HTMLFONTSZ3_DFLT; + aFontSizeArr[3] = HTMLFONTSZ4_DFLT; + aFontSizeArr[4] = HTMLFONTSZ5_DFLT; + aFontSizeArr[5] = HTMLFONTSZ6_DFLT; + aFontSizeArr[6] = HTMLFONTSZ7_DFLT; + } +}; + +const Sequence<OUString>& SvxHtmlOptions::GetPropertyNames() +{ + static Sequence<OUString> const aNames + { + "Import/UnknownTag", // 0 + "Import/FontSetting", // 1 + "Import/FontSize/Size_1", // 2 + "Import/FontSize/Size_2", // 3 + "Import/FontSize/Size_3", // 4 + "Import/FontSize/Size_4", // 5 + "Import/FontSize/Size_5", // 6 + "Import/FontSize/Size_6", // 7 + "Import/FontSize/Size_7", // 8 + "Export/Browser", // 9 + "Export/Basic", // 0 + "Export/PrintLayout", // 11 + "Export/LocalGraphic", // 12 + "Export/Warning", // 13 + "Export/Encoding", // 14 + "Import/NumbersEnglishUS" // 15 + }; + return aNames; +} + +SvxHtmlOptions::SvxHtmlOptions() : + ConfigItem("Office.Common/Filter/HTML"), + pImpl( new HtmlOptions_Impl ) +{ + Load( GetPropertyNames() ); +} + + +SvxHtmlOptions::~SvxHtmlOptions() +{ +} + +void SvxHtmlOptions::Load( const Sequence< OUString >& aNames ) +{ + Sequence<Any> aValues = GetProperties(aNames); + const Any* pValues = aValues.getConstArray(); + DBG_ASSERT(aValues.getLength() == aNames.getLength(), "GetProperties failed"); + if(aValues.getLength() != aNames.getLength()) + return; + + pImpl->nFlags = HtmlCfgFlags::NONE; + for(int nProp = 0; nProp < aNames.getLength(); nProp++) + { + if(pValues[nProp].hasValue()) + { + switch(nProp) + { + case 0: + if(*o3tl::doAccess<bool>(pValues[nProp])) + pImpl->nFlags |= HtmlCfgFlags::UnknownTags; + break;//"Import/UnknownTag", + case 1: + if(*o3tl::doAccess<bool>(pValues[nProp])) + pImpl->nFlags |= HtmlCfgFlags::IgnoreFontFamily; + break;//"Import/FontSetting", + case 2: pValues[nProp] >>= pImpl->aFontSizeArr[0]; break;//"Import/FontSize/Size_1", + case 3: pValues[nProp] >>= pImpl->aFontSizeArr[1]; break;//"Import/FontSize/Size_2", + case 4: pValues[nProp] >>= pImpl->aFontSizeArr[2]; break;//"Import/FontSize/Size_3", + case 5: pValues[nProp] >>= pImpl->aFontSizeArr[3]; break;//"Import/FontSize/Size_4", + case 6: pValues[nProp] >>= pImpl->aFontSizeArr[4]; break;//"Import/FontSize/Size_5", + case 7: pValues[nProp] >>= pImpl->aFontSizeArr[5]; break;//"Import/FontSize/Size_6", + case 8: pValues[nProp] >>= pImpl->aFontSizeArr[6]; break;//"Import/FontSize/Size_7", + case 9://"Export/Browser", + { + sal_Int32 nExpMode = 0; + pValues[nProp] >>= nExpMode; + switch( nExpMode ) + { + case 1: nExpMode = HTML_CFG_MSIE; break; + case 3: nExpMode = HTML_CFG_WRITER; break; + case 4: nExpMode = HTML_CFG_NS40; break; + default: nExpMode = HTML_CFG_NS40; break; + } + + pImpl->nExportMode = nExpMode; + } + break; + case 10: + if(*o3tl::doAccess<bool>(pValues[nProp])) + pImpl->nFlags |= HtmlCfgFlags::StarBasic; + break;//"Export/Basic", + case 11: + if(*o3tl::doAccess<bool>(pValues[nProp])) + pImpl->nFlags |= HtmlCfgFlags::PrintLayoutExtension; + break;//"Export/PrintLayout", + case 12: + if(*o3tl::doAccess<bool>(pValues[nProp])) + pImpl->nFlags |= HtmlCfgFlags::LocalGrf; + break;//"Export/LocalGraphic", + case 13: + if(*o3tl::doAccess<bool>(pValues[nProp])) + pImpl->nFlags |= HtmlCfgFlags::IsBasicWarning; + break;//"Export/Warning" + + case 14: pValues[nProp] >>= pImpl->eEncoding; + pImpl->bIsEncodingDefault = false; + break;//"Export/Encoding" + + case 15: + if(*o3tl::doAccess<bool>(pValues[nProp])) + pImpl->nFlags |= HtmlCfgFlags::NumbersEnglishUS; + break;//"Import/NumbersEnglishUS" + } + } + } +} + + +void SvxHtmlOptions::ImplCommit() +{ + const Sequence<OUString>& aNames = GetPropertyNames(); + + Sequence<Any> aValues(aNames.getLength()); + Any* pValues = aValues.getArray(); + + for(int nProp = 0; nProp < aNames.getLength(); nProp++) + { + bool bSet = false; + switch(nProp) + { + case 0: bSet = bool(pImpl->nFlags & HtmlCfgFlags::UnknownTags);break;//"Import/UnknownTag", + case 1: bSet = bool(pImpl->nFlags & HtmlCfgFlags::IgnoreFontFamily);break;//"Import/FontSetting", + case 2: pValues[nProp] <<= pImpl->aFontSizeArr[0];break;//"Import/FontSize/Size_1", + case 3: pValues[nProp] <<= pImpl->aFontSizeArr[1];break;//"Import/FontSize/Size_2", + case 4: pValues[nProp] <<= pImpl->aFontSizeArr[2];break;//"Import/FontSize/Size_3", + case 5: pValues[nProp] <<= pImpl->aFontSizeArr[3];break;//"Import/FontSize/Size_4", + case 6: pValues[nProp] <<= pImpl->aFontSizeArr[4];break;//"Import/FontSize/Size_5", + case 7: pValues[nProp] <<= pImpl->aFontSizeArr[5];break;//"Import/FontSize/Size_6", + case 8: pValues[nProp] <<= pImpl->aFontSizeArr[6];break;//"Import/FontSize/Size_7", + case 9: //"Export/Browser", + { + sal_Int32 nExpMode = pImpl->nExportMode; + + switch( nExpMode ) + { + case HTML_CFG_MSIE: nExpMode = 1; break; + case HTML_CFG_WRITER: nExpMode = 3; break; + case HTML_CFG_NS40: nExpMode = 4; break; + default: nExpMode = 4; break; // NS40 + } + + pValues[nProp] <<= nExpMode; + break; + } + case 10: bSet = bool(pImpl->nFlags & HtmlCfgFlags::StarBasic);break;//"Export/Basic", + case 11: bSet = bool(pImpl->nFlags & HtmlCfgFlags::PrintLayoutExtension);break;//"Export/PrintLayout", + case 12: bSet = bool(pImpl->nFlags & HtmlCfgFlags::LocalGrf);break;//"Export/LocalGraphic", + case 13: bSet = bool(pImpl->nFlags & HtmlCfgFlags::IsBasicWarning);break;//"Export/Warning" + case 14: + if(!pImpl->bIsEncodingDefault) + pValues[nProp] <<= pImpl->eEncoding; + break;//"Export/Encoding", + case 15: bSet = bool(pImpl->nFlags & HtmlCfgFlags::NumbersEnglishUS);break;//"Import/NumbersEnglishUS" + } + if(nProp < 2 || ( nProp > 9 && nProp < 14 ) || nProp == 15) + pValues[nProp] <<= bSet; + } + PutProperties(aNames, aValues); +} + +void SvxHtmlOptions::Notify( const css::uno::Sequence< OUString >& ) +{ + Load( GetPropertyNames() ); +} + + +sal_uInt16 SvxHtmlOptions::GetFontSize(sal_uInt16 nPos) const +{ + if(nPos < HTML_FONT_COUNT) + return static_cast<sal_uInt16>(pImpl->aFontSizeArr[nPos]); + return 0; +} + +void SvxHtmlOptions::SetFontSize(sal_uInt16 nPos, sal_uInt16 nSize) +{ + if(nPos < HTML_FONT_COUNT) + { + pImpl->aFontSizeArr[nPos] = nSize; + SetModified(); + } +} + + +bool SvxHtmlOptions::IsImportUnknown() const +{ + return bool(pImpl->nFlags & HtmlCfgFlags::UnknownTags) ; +} + + +void SvxHtmlOptions::SetImportUnknown(bool bSet) +{ + if(bSet) + pImpl->nFlags |= HtmlCfgFlags::UnknownTags; + else + pImpl->nFlags &= ~HtmlCfgFlags::UnknownTags; + SetModified(); +} + + +sal_uInt16 SvxHtmlOptions::GetExportMode() const +{ + return static_cast<sal_uInt16>(pImpl->nExportMode); +} + + +bool SvxHtmlOptions::IsStarBasic() const +{ + return bool(pImpl->nFlags & HtmlCfgFlags::StarBasic) ; +} + + +void SvxHtmlOptions::SetStarBasic(bool bSet) +{ + if(bSet) + pImpl->nFlags |= HtmlCfgFlags::StarBasic; + else + pImpl->nFlags &= ~HtmlCfgFlags::StarBasic; + SetModified(); +} + +bool SvxHtmlOptions::IsSaveGraphicsLocal() const +{ + return bool(pImpl->nFlags & HtmlCfgFlags::LocalGrf) ; +} + +void SvxHtmlOptions::SetSaveGraphicsLocal(bool bSet) +{ + if(bSet) + pImpl->nFlags |= HtmlCfgFlags::LocalGrf; + else + pImpl->nFlags &= ~HtmlCfgFlags::LocalGrf; + SetModified(); +} + +bool SvxHtmlOptions::IsPrintLayoutExtension() const +{ + bool bRet(pImpl->nFlags & HtmlCfgFlags::PrintLayoutExtension); + switch( pImpl->nExportMode ) + { + case HTML_CFG_MSIE: + case HTML_CFG_NS40 : + case HTML_CFG_WRITER : + break; + default: + bRet = false; + } + return bRet; +} + +void SvxHtmlOptions::SetPrintLayoutExtension(bool bSet) +{ + if(bSet) + pImpl->nFlags |= HtmlCfgFlags::PrintLayoutExtension; + else + pImpl->nFlags &= ~HtmlCfgFlags::PrintLayoutExtension; + SetModified(); +} + +bool SvxHtmlOptions::IsIgnoreFontFamily() const +{ + return bool(pImpl->nFlags & HtmlCfgFlags::IgnoreFontFamily) ; +} + +void SvxHtmlOptions::SetIgnoreFontFamily(bool bSet) +{ + if(bSet) + pImpl->nFlags |= HtmlCfgFlags::IgnoreFontFamily; + else + pImpl->nFlags &= ~HtmlCfgFlags::IgnoreFontFamily; + SetModified(); +} + +bool SvxHtmlOptions::IsStarBasicWarning() const +{ + return bool(pImpl->nFlags & HtmlCfgFlags::IsBasicWarning) ; +} + +void SvxHtmlOptions::SetStarBasicWarning(bool bSet) +{ + if(bSet) + pImpl->nFlags |= HtmlCfgFlags::IsBasicWarning; + else + pImpl->nFlags &= ~HtmlCfgFlags::IsBasicWarning; + SetModified(); +} + +rtl_TextEncoding SvxHtmlOptions::GetTextEncoding() const +{ + rtl_TextEncoding eRet; + if(pImpl->bIsEncodingDefault) + eRet = SvtSysLocale::GetBestMimeEncoding(); + else + eRet = static_cast<rtl_TextEncoding>(pImpl->eEncoding); + return eRet; +} + +void SvxHtmlOptions::SetTextEncoding( rtl_TextEncoding eEnc ) +{ + pImpl->eEncoding = eEnc; + pImpl->bIsEncodingDefault = false; + SetModified(); +} + +bool SvxHtmlOptions::IsDefaultTextEncoding() const +{ + return pImpl->bIsEncodingDefault; +} + +namespace +{ + class theSvxHtmlOptions : public rtl::Static<SvxHtmlOptions, theSvxHtmlOptions> {}; +} + +SvxHtmlOptions& SvxHtmlOptions::Get() +{ + return theSvxHtmlOptions::get(); +} + +bool SvxHtmlOptions::IsNumbersEnglishUS() const +{ + return bool(pImpl->nFlags & HtmlCfgFlags::NumbersEnglishUS) ; +} + +void SvxHtmlOptions::SetNumbersEnglishUS(bool bSet) +{ + if(bSet) + pImpl->nFlags |= HtmlCfgFlags::NumbersEnglishUS; + else + pImpl->nFlags &= ~HtmlCfgFlags::NumbersEnglishUS; + SetModified(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/config/itemholder2.cxx b/svtools/source/config/itemholder2.cxx new file mode 100644 index 000000000..692f182a0 --- /dev/null +++ b/svtools/source/config/itemholder2.cxx @@ -0,0 +1,159 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 "itemholder2.hxx" + +#include <osl/diagnose.h> +#include <comphelper/processfactory.hxx> +#include <com/sun/star/lang/XComponent.hpp> +#include <com/sun/star/configuration/theDefaultProvider.hpp> + +#include <svtools/accessibilityoptions.hxx> +#include <svtools/menuoptions.hxx> +#include <svtools/colorcfg.hxx> +#include <svtools/helpopt.hxx> +#include <svtools/printoptions.hxx> +#include <unotools/options.hxx> +#include <svtools/miscopt.hxx> +#include <tools/diagnose_ex.h> + +namespace svtools { + +ItemHolder2::ItemHolder2() + : ItemHolderMutexBase() +{ + try + { + css::uno::Reference< css::uno::XComponentContext > xContext = ::comphelper::getProcessComponentContext(); + css::uno::Reference< css::lang::XComponent > xCfg( + css::configuration::theDefaultProvider::get( xContext ), + css::uno::UNO_QUERY_THROW ); + xCfg->addEventListener(static_cast< css::lang::XEventListener* >(this)); + } + catch(const css::uno::RuntimeException&) + { + throw; + } +#ifdef DBG_UTIL + catch(const css::uno::Exception&) + { + static bool bMessage = true; + if(bMessage) + { + bMessage = false; + TOOLS_WARN_EXCEPTION( "svtools", "CreateInstance with arguments" ); + } + } +#else + catch(css::uno::Exception&){} +#endif +} + + +ItemHolder2::~ItemHolder2() +{ + impl_releaseAllItems(); +} + + +void ItemHolder2::holdConfigItem(EItem eItem) +{ + static ItemHolder2* pHolder = new ItemHolder2(); + pHolder->impl_addItem(eItem); +} + + +void SAL_CALL ItemHolder2::disposing(const css::lang::EventObject&) +{ + impl_releaseAllItems(); +} + + +void ItemHolder2::impl_addItem(EItem eItem) +{ + osl::MutexGuard aLock(m_aLock); + + for ( auto const & rInfo : m_lItems ) + { + if (rInfo.eItem == eItem) + return; + } + + TItemInfo aNewItem; + aNewItem.eItem = eItem; + impl_newItem(aNewItem); + if (aNewItem.pItem) + m_lItems.emplace_back(std::move(aNewItem)); +} + + +void ItemHolder2::impl_releaseAllItems() +{ + std::vector<TItemInfo> items; + { + osl::MutexGuard aLock(m_aLock); + items.swap(m_lItems); + } + + // items will be freed when the block exits +} + + +void ItemHolder2::impl_newItem(TItemInfo& rItem) +{ + switch(rItem.eItem) + { + case EItem::AccessibilityOptions : + rItem.pItem.reset( new SvtAccessibilityOptions() ); + break; + + case EItem::ColorConfig : + rItem.pItem.reset( new ::svtools::ColorConfig() ); + break; + + case EItem::HelpOptions : + rItem.pItem.reset( new SvtHelpOptions() ); + break; + + case EItem::MenuOptions : + rItem.pItem.reset( new SvtMenuOptions() ); + break; + + case EItem::PrintOptions : + rItem.pItem.reset( new SvtPrinterOptions() ); + break; + + case EItem::PrintFileOptions : + rItem.pItem.reset( new SvtPrintFileOptions() ); + break; + + case EItem::MiscOptions : + rItem.pItem.reset( new SvtMiscOptions() ); + break; + + default: + OSL_ASSERT(false); + break; + } +} + +} // namespace svtools + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/config/itemholder2.hxx b/svtools/source/config/itemholder2.hxx new file mode 100644 index 000000000..c4fd540cf --- /dev/null +++ b/svtools/source/config/itemholder2.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 . + */ + +#pragma once + +#include <unotools/itemholderbase.hxx> +#include <cppuhelper/implbase.hxx> +#include <com/sun/star/lang/XEventListener.hpp> + +namespace svtools { + + +class ItemHolder2 : private ItemHolderMutexBase + , public ::cppu::WeakImplHelper< css::lang::XEventListener > +{ + + // member + private: + + std::vector<TItemInfo> m_lItems; + + + // c++ interface + public: + + ItemHolder2(); + virtual ~ItemHolder2() override; + static void holdConfigItem(EItem eItem); + + + // uno interface + public: + + virtual void SAL_CALL disposing(const css::lang::EventObject& aEvent) override; + + + // helper + private: + + void impl_addItem(EItem eItem); + void impl_releaseAllItems(); + static void impl_newItem(TItemInfo& rItem); +}; + +} // namespace svtools + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/config/menuoptions.cxx b/svtools/source/config/menuoptions.cxx new file mode 100644 index 000000000..a86bdc6e3 --- /dev/null +++ b/svtools/source/config/menuoptions.cxx @@ -0,0 +1,413 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <svtools/menuoptions.hxx> +#include <unotools/configitem.hxx> +#include <tools/debug.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> +#include <vcl/svapp.hxx> +#include <vcl/settings.hxx> + +#include "itemholder2.hxx" + +// namespaces + +using namespace ::utl ; +using namespace ::osl ; +using namespace ::com::sun::star::uno ; + +#define ROOTNODE_MENU "Office.Common/View/Menu" +#define DEFAULT_DONTHIDEDISABLEDENTRIES false +#define DEFAULT_FOLLOWMOUSE true +#define DEFAULT_MENUICONS TRISTATE_INDET +#define DEFAULT_CONTEXTMENUSHORTCUTS TRISTATE_INDET + +#define PROPERTYNAME_DONTHIDEDISABLEDENTRIES "DontHideDisabledEntry" +#define PROPERTYNAME_FOLLOWMOUSE "FollowMouse" +#define PROPERTYNAME_SHOWICONSINMENUES "ShowIconsInMenues" +#define PROPERTYNAME_SYSTEMICONSINMENUES "IsSystemIconsInMenus" +#define PROPERTYNAME_SHORTCUTSINCONTEXMENU "ShortcutsInContextMenus" + +#define PROPERTYHANDLE_DONTHIDEDISABLEDENTRIES 0 +#define PROPERTYHANDLE_FOLLOWMOUSE 1 +#define PROPERTYHANDLE_SHOWICONSINMENUES 2 +#define PROPERTYHANDLE_SYSTEMICONSINMENUES 3 +#define PROPERTYHANDLE_SHORTCUTSINCONTEXMENU 4 + +// private declarations! + +class SvtMenuOptions_Impl : public ConfigItem +{ + + // private member + + private: + bool m_bDontHideDisabledEntries ; /// cache "DontHideDisabledEntries" of Menu section + bool m_bFollowMouse ; /// cache "FollowMouse" of Menu section + TriState m_eMenuIcons ; /// cache "MenuIcons" of Menu section + TriState m_eContextMenuShortcuts ; /// cache "ShortcutsInContextMenus" of Menu section + + // public methods + + public: + + // constructor / destructor + + SvtMenuOptions_Impl(); + virtual ~SvtMenuOptions_Impl() override; + + // override methods of baseclass + + /*-**************************************************************************************************** + @short called for notify of configmanager + @descr This method is called from the ConfigManager before application ends or from the + PropertyChangeListener if the sub tree broadcasts changes. You must update your + internal values. + + @seealso baseclass ConfigItem + + @param "seqPropertyNames" is the list of properties which should be updated. + *//*-*****************************************************************************************************/ + + virtual void Notify( const Sequence< OUString >& seqPropertyNames ) override; + + // public interface + + /*-**************************************************************************************************** + @short access method to get internal values + @descr These methods give us a chance to regulate access to our internal values. + It's not used at the moment - but it's possible for the future! + *//*-*****************************************************************************************************/ + + bool IsEntryHidingEnabled() const + { return m_bDontHideDisabledEntries; } + + TriState GetMenuIconsState() const + { return m_eMenuIcons; } + + void SetMenuIconsState(TriState eState) + { + m_eMenuIcons = eState; + SetModified(); + // tdf#93451: don't Commit() here, it's too early + } + + TriState GetContextMenuShortcuts() const + { return m_eContextMenuShortcuts; } + + void SetContextMenuShortcuts(TriState eState) + { + m_eContextMenuShortcuts = eState; + SetModified(); + Commit(); + } + + // private methods + + private: + + virtual void ImplCommit() override; + + /*-**************************************************************************************************** + @short return list of fix key names of our configuration management which represent our module tree + @descr This method returns a static const list of key names. We need it to get needed values from our + configuration management. + @return A list of needed configuration keys is returned. + *//*-*****************************************************************************************************/ + + static Sequence< OUString > const & impl_GetPropertyNames(); +}; + +// constructor + +SvtMenuOptions_Impl::SvtMenuOptions_Impl() + // Init baseclasses first + : ConfigItem ( ROOTNODE_MENU ) + // Init member then. + , m_bDontHideDisabledEntries ( DEFAULT_DONTHIDEDISABLEDENTRIES ) + , m_bFollowMouse ( DEFAULT_FOLLOWMOUSE ) + , m_eMenuIcons ( DEFAULT_MENUICONS ) + , m_eContextMenuShortcuts ( DEFAULT_CONTEXTMENUSHORTCUTS ) +{ + // Use our static list of configuration keys to get his values. + Sequence< OUString > seqNames = impl_GetPropertyNames(); + Sequence< Any > seqValues = GetProperties( seqNames ) ; + + // Safe impossible cases. + // We need values from ALL configuration keys. + // Follow assignment use order of values in relation to our list of key names! + DBG_ASSERT( !(seqNames.getLength()!=seqValues.getLength()), "SvtMenuOptions_Impl::SvtMenuOptions_Impl()\nI miss some values of configuration keys!\n" ); + + bool bMenuIcons = true; + bool bSystemMenuIcons = true; + if (m_eMenuIcons == TRISTATE_INDET) + bMenuIcons = Application::GetSettings().GetStyleSettings().GetPreferredUseImagesInMenus(); + else + { + bSystemMenuIcons = false; + bMenuIcons = m_eMenuIcons != TRISTATE_FALSE; + } + + // Copy values from list in right order to our internal member. + sal_Int32 nPropertyCount = seqValues.getLength() ; + sal_Int32 nProperty = 0 ; + for( nProperty=0; nProperty<nPropertyCount; ++nProperty ) + { + // Safe impossible cases. + // Check any for valid value. + DBG_ASSERT( seqValues[nProperty].hasValue(), "SvtMenuOptions_Impl::SvtMenuOptions_Impl()\nInvalid property value for property detected!\n" ); + + if (!seqValues[nProperty].hasValue()) + continue; + + switch( nProperty ) + { + case PROPERTYHANDLE_DONTHIDEDISABLEDENTRIES : { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtMenuOptions_Impl::SvtMenuOptions_Impl()\nWho has changed the value type of \"Office.Common\\View\\Menu\\DontHideDisabledEntry\"?" ); + seqValues[nProperty] >>= m_bDontHideDisabledEntries; + } + break; + + case PROPERTYHANDLE_FOLLOWMOUSE : { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtMenuOptions_Impl::SvtMenuOptions_Impl()\nWho has changed the value type of \"Office.Common\\View\\Menu\\FollowMouse\"?" ); + seqValues[nProperty] >>= m_bFollowMouse; + } + break; + case PROPERTYHANDLE_SHOWICONSINMENUES : { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtMenuOptions_Impl::SvtMenuOptions_Impl()\nWho has changed the value type of \"Office.Common\\View\\Menu\\ShowIconsInMenues\"?" ); + seqValues[nProperty] >>= bMenuIcons; + } + break; + case PROPERTYHANDLE_SYSTEMICONSINMENUES : { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtMenuOptions_Impl::SvtMenuOptions_Impl()\nWho has changed the value type of \"Office.Common\\View\\Menu\\IsSystemIconsInMenus\"?" ); + seqValues[nProperty] >>= bSystemMenuIcons; + } + break; + case PROPERTYHANDLE_SHORTCUTSINCONTEXMENU : { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_SHORT), "SvtMenuOptions_Impl::SvtMenuOptions_Impl()\nWho has changed the value type of \"Office.Common\\View\\Menu\\ShortcutsInContextMenus\"?" ); + sal_Int16 nContextMenuShortcuts; + if ( seqValues[nProperty] >>= nContextMenuShortcuts ) + m_eContextMenuShortcuts = static_cast<TriState>(nContextMenuShortcuts); + } + break; + } + } + + m_eMenuIcons = bSystemMenuIcons ? TRISTATE_INDET : static_cast<TriState>(bMenuIcons); + + EnableNotification( seqNames ); +} + +// destructor + +SvtMenuOptions_Impl::~SvtMenuOptions_Impl() +{ + assert(!IsModified()); // should have been committed +} + +// public method + +void SvtMenuOptions_Impl::Notify( const Sequence< OUString >& seqPropertyNames ) +{ + // Use given list of updated properties to get his values from configuration directly! + Sequence< Any > seqValues = GetProperties( seqPropertyNames ); + // Safe impossible cases. + // We need values from ALL notified configuration keys. + DBG_ASSERT( !(seqPropertyNames.getLength()!=seqValues.getLength()), "SvtMenuOptions_Impl::Notify()\nI miss some values of configuration keys!\n" ); + + bool bMenuSettingsChanged = false; + bool bMenuIcons = true; + bool bSystemMenuIcons = true; + if (m_eMenuIcons == TRISTATE_INDET) + bMenuIcons = Application::GetSettings().GetStyleSettings().GetUseImagesInMenus(); + else + { + bSystemMenuIcons = false; + bMenuIcons = m_eMenuIcons != TRISTATE_FALSE; + } + + // Step over list of property names and get right value from coreesponding value list to set it on internal members! + sal_Int32 nCount = seqPropertyNames.getLength(); + for( sal_Int32 nProperty=0; nProperty<nCount; ++nProperty ) + { + if( seqPropertyNames[nProperty] == PROPERTYNAME_DONTHIDEDISABLEDENTRIES ) + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtMenuOptions_Impl::Notify()\nWho has changed the value type of \"Office.Common\\View\\Menu\\DontHideDisabledEntry\"?" ); + seqValues[nProperty] >>= m_bDontHideDisabledEntries; + } + else if( seqPropertyNames[nProperty] == PROPERTYNAME_FOLLOWMOUSE ) + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtMenuOptions_Impl::Notify()\nWho has changed the value type of \"Office.Common\\View\\Menu\\FollowMouse\"?" ); + seqValues[nProperty] >>= m_bFollowMouse; + } + else if( seqPropertyNames[nProperty] == PROPERTYNAME_SHOWICONSINMENUES ) + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtMenuOptions_Impl::SvtMenuOptions_Impl()\nWho has changed the value type of \"Office.Common\\View\\Menu\\ShowIconsInMenues\"?" ); + bMenuSettingsChanged |= seqValues[nProperty] >>= bMenuIcons; + } + else if( seqPropertyNames[nProperty] == PROPERTYNAME_SYSTEMICONSINMENUES ) + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtMenuOptions_Impl::SvtMenuOptions_Impl()\nWho has changed the value type of \"Office.Common\\View\\Menu\\IsSystemIconsInMenus\"?" ); + bMenuSettingsChanged |= seqValues[nProperty] >>= bSystemMenuIcons; + } + else if( seqPropertyNames[nProperty] == PROPERTYNAME_SHORTCUTSINCONTEXMENU ) + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_SHORT), "SvtMenuOptions_Impl::SvtMenuOptions_Impl()\nWho has changed the value type of \"Office.Common\\View\\Menu\\ShortcutsInContextMenus\"?" ); + sal_Int16 nContextMenuShortcuts; + if ( seqValues[nProperty] >>= nContextMenuShortcuts ) + m_eContextMenuShortcuts = static_cast<TriState>(nContextMenuShortcuts); + } + else assert( false && "SvtMenuOptions_Impl::Notify()\nUnknown property detected ... I can't handle these!" ); + } + + if ( bMenuSettingsChanged ) + m_eMenuIcons = bSystemMenuIcons ? TRISTATE_INDET : static_cast<TriState>(bMenuIcons); +} + +// public method + +void SvtMenuOptions_Impl::ImplCommit() +{ + // Get names of supported properties, create a list for values and copy current values to it. + Sequence< OUString > seqNames = impl_GetPropertyNames(); + sal_Int32 nCount = seqNames.getLength(); + Sequence< Any > seqValues ( nCount ); + for( sal_Int32 nProperty=0; nProperty<nCount; ++nProperty ) + { + switch( nProperty ) + { + case PROPERTYHANDLE_DONTHIDEDISABLEDENTRIES : { + seqValues[nProperty] <<= m_bDontHideDisabledEntries; + } + break; + + case PROPERTYHANDLE_FOLLOWMOUSE : { + seqValues[nProperty] <<= m_bFollowMouse; + } + break; + //Output cache of current setting as possibly modified by System Theme for older version + case PROPERTYHANDLE_SHOWICONSINMENUES : { + bool bValue = Application::GetSettings().GetStyleSettings().GetUseImagesInMenus(); + seqValues[nProperty] <<= bValue; + } + break; + case PROPERTYHANDLE_SYSTEMICONSINMENUES : { + bool bValue = m_eMenuIcons == TRISTATE_INDET; + seqValues[nProperty] <<= bValue; + } + break; + case PROPERTYHANDLE_SHORTCUTSINCONTEXMENU : { + seqValues[nProperty] <<= static_cast<sal_Int16>(m_eContextMenuShortcuts); + } + break; + } + } + // Set properties in configuration. + PutProperties( seqNames, seqValues ); +} + +// private method + +Sequence< OUString > const & SvtMenuOptions_Impl::impl_GetPropertyNames() +{ + static const Sequence<OUString> seqPropertyNames { + OUString(PROPERTYNAME_DONTHIDEDISABLEDENTRIES) , + OUString(PROPERTYNAME_FOLLOWMOUSE) , + OUString(PROPERTYNAME_SHOWICONSINMENUES) , + OUString(PROPERTYNAME_SYSTEMICONSINMENUES) , + OUString(PROPERTYNAME_SHORTCUTSINCONTEXMENU) + }; + return seqPropertyNames; +} + +namespace { + +std::weak_ptr<SvtMenuOptions_Impl> g_pMenuOptions; + +} + +SvtMenuOptions::SvtMenuOptions() +{ + // Global access, must be guarded (multithreading!). + MutexGuard aGuard( GetOwnStaticMutex() ); + + m_pImpl = g_pMenuOptions.lock(); + if( !m_pImpl ) + { + m_pImpl = std::make_shared<SvtMenuOptions_Impl>(); + g_pMenuOptions = m_pImpl; + svtools::ItemHolder2::holdConfigItem(EItem::MenuOptions); + } +} + +SvtMenuOptions::~SvtMenuOptions() +{ + // Global access, must be guarded (multithreading!) + MutexGuard aGuard( GetOwnStaticMutex() ); + + m_pImpl.reset(); +} + +// public method + +bool SvtMenuOptions::IsEntryHidingEnabled() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->IsEntryHidingEnabled(); +} + +// public method + +TriState SvtMenuOptions::GetMenuIconsState() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->GetMenuIconsState(); +} + +// public method + +void SvtMenuOptions::SetMenuIconsState(TriState eState) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pImpl->SetMenuIconsState(eState); +} + +TriState SvtMenuOptions::GetContextMenuShortcuts() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->GetContextMenuShortcuts(); +} + +void SvtMenuOptions::SetContextMenuShortcuts(TriState eState) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pImpl->SetContextMenuShortcuts(eState); +} + +// private method + +Mutex& SvtMenuOptions::GetOwnStaticMutex() +{ + static Mutex ourMutex; + + return ourMutex; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/config/miscopt.cxx b/svtools/source/config/miscopt.cxx new file mode 100644 index 000000000..7e39fa901 --- /dev/null +++ b/svtools/source/config/miscopt.cxx @@ -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 . + */ + +#include <svtools/miscopt.hxx> +#include <unotools/configitem.hxx> +#include <tools/debug.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> +#include <comphelper/sequence.hxx> +#include <tools/link.hxx> +#include <osl/diagnose.h> + +#include <rtl/instance.hxx> +#include "itemholder2.hxx" + +#include <svtools/imgdef.hxx> +#include <vcl/svapp.hxx> +#include <vcl/settings.hxx> +#include <vcl/toolbox.hxx> + +#include <vector> + +using namespace ::utl ; +using namespace ::osl ; +using namespace ::com::sun::star::uno ; +using namespace ::com::sun::star; + +#define ROOTNODE_MISC "Office.Common/Misc" + +// PROPERTYHANDLE defines must be sequential from zero for Commit/Load +#define PROPERTYNAME_PLUGINSENABLED "PluginsEnabled" +#define PROPERTYHANDLE_PLUGINSENABLED 0 +#define PROPERTYNAME_SYMBOLSET "SymbolSet" +#define PROPERTYHANDLE_SYMBOLSET 1 +#define PROPERTYNAME_TOOLBOXSTYLE "ToolboxStyle" +#define PROPERTYHANDLE_TOOLBOXSTYLE 2 +#define PROPERTYNAME_USESYSTEMFILEDIALOG "UseSystemFileDialog" +#define PROPERTYHANDLE_USESYSTEMFILEDIALOG 3 +#define PROPERTYNAME_ICONTHEME "SymbolStyle" +#define PROPERTYHANDLE_SYMBOLSTYLE 4 +#define PROPERTYNAME_USESYSTEMPRINTDIALOG "UseSystemPrintDialog" +#define PROPERTYHANDLE_USESYSTEMPRINTDIALOG 5 +#define PROPERTYNAME_SHOWLINKWARNINGDIALOG "ShowLinkWarningDialog" +#define PROPERTYHANDLE_SHOWLINKWARNINGDIALOG 6 +#define PROPERTYNAME_DISABLEUICUSTOMIZATION "DisableUICustomization" +#define PROPERTYHANDLE_DISABLEUICUSTOMIZATION 7 +#define PROPERTYNAME_EXPERIMENTALMODE "ExperimentalMode" +#define PROPERTYHANDLE_EXPERIMENTALMODE 8 +#define PROPERTYNAME_MACRORECORDERMODE "MacroRecorderMode" +#define PROPERTYHANDLE_MACRORECORDERMODE 9 +#define PROPERTYNAME_SIDEBARICONSIZE "SidebarIconSize" +#define PROPERTYHANDLE_SIDEBARICONSIZE 10 +#define PROPERTYNAME_NOTEBOOKBARICONSIZE "NotebookbarIconSize" +#define PROPERTYHANDLE_NOTEBOOKBARICONSIZE 11 + +#define VCL_TOOLBOX_STYLE_FLAT (sal_uInt16(0x0004)) // from <vcl/toolbox.hxx> + +class SvtMiscOptions_Impl : public ConfigItem +{ +private: + ::std::vector<Link<LinkParamNone*,void>> aList; + bool m_bUseSystemFileDialog; + bool m_bIsUseSystemFileDialogRO; + bool m_bPluginsEnabled; + bool m_bIsPluginsEnabledRO; + sal_Int16 m_nSymbolsSize; + bool m_bIsSymbolsSizeRO; + ToolBoxButtonSize m_nSidebarIconSize; + bool m_bIsSidebarIconSizeRO; + ToolBoxButtonSize m_nNotebookbarIconSize; + bool m_bIsNotebookbarIconSizeRO; + bool m_bIsSymbolsStyleRO; + sal_Int16 m_nToolboxStyle; + bool m_bIsToolboxStyleRO; + bool m_bUseSystemPrintDialog; + bool m_bIsUseSystemPrintDialogRO; + bool m_bShowLinkWarningDialog; + bool m_bIsShowLinkWarningDialogRO; + bool m_bDisableUICustomization; + bool m_bExperimentalMode; + bool m_bMacroRecorderMode; + bool m_bIconThemeWasSetAutomatically; + + virtual void ImplCommit() override; + +public: + + SvtMiscOptions_Impl(); + virtual ~SvtMiscOptions_Impl() override; + + /*-**************************************************************************************************** + @short called for notify of configmanager + @descr This method is called from the ConfigManager before the application ends or from the + PropertyChangeListener if the sub tree broadcasts changes. You must update your + internal values. + + @seealso baseclass ConfigItem + + @param "seqPropertyNames" is the list of properties which should be updated. + *//*-*****************************************************************************************************/ + + virtual void Notify( const Sequence< OUString >& seqPropertyNames ) override; + + /** loads required data from the configuration. It's called in the constructor to + read all entries and form ::Notify to re-read changed settings + + */ + void Load( const Sequence< OUString >& rPropertyNames ); + + // public interface + + + bool UseSystemFileDialog() const + { return m_bUseSystemFileDialog; } + + void SetUseSystemFileDialog( bool bSet ) + { m_bUseSystemFileDialog = bSet; SetModified(); } + + bool IsUseSystemFileDialogReadOnly() const + { return m_bIsUseSystemFileDialogRO; } + + bool DisableUICustomization() const + { return m_bDisableUICustomization; } + + void SetExperimentalMode( bool bSet ) + { m_bExperimentalMode = bSet; SetModified(); } + + bool IsExperimentalMode() const + { return m_bExperimentalMode; } + + void SetMacroRecorderMode( bool bSet ) + { m_bMacroRecorderMode = bSet; SetModified(); } + + bool IsMacroRecorderMode() const + { return m_bMacroRecorderMode; } + + bool IsPluginsEnabled() const + { return m_bPluginsEnabled; } + + sal_Int16 GetSymbolsSize() const + { return m_nSymbolsSize; } + + ToolBoxButtonSize GetSidebarIconSize() const + { return m_nSidebarIconSize; } + + ToolBoxButtonSize GetNotebookbarIconSize() const + { return m_nNotebookbarIconSize; } + + void SetSymbolsSize( sal_Int16 nSet ); + + void SetSidebarIconSize( ToolBoxButtonSize nSet ); + + void SetNotebookbarIconSize( ToolBoxButtonSize nSet ); + + static OUString GetIconTheme(); + + enum class SetModifiedFlag { SET, DONT_SET }; + + /** Set the icon theme + * + * @param theme + * The name of the icon theme to use. + * + * @param setModified + * Whether to call SetModified() and CallListeners(). + * + * @internal + * The @p setModified flag was introduced because the unittests fail if we call SetModified() + * during initialization in the constructor. + */ + void + SetIconTheme(const OUString &theme, SetModifiedFlag setModified ); + + bool IconThemeWasSetAutomatically() + {return m_bIconThemeWasSetAutomatically;} + + // translate to VCL settings ( "0" = 3D, "1" = FLAT ) + sal_Int16 GetToolboxStyle() const + { return m_nToolboxStyle ? VCL_TOOLBOX_STYLE_FLAT : 0; } + + // translate from VCL settings + void SetToolboxStyle( sal_Int16 nStyle ); + + bool UseSystemPrintDialog() const + { return m_bUseSystemPrintDialog; } + + void SetUseSystemPrintDialog( bool bSet ) + { m_bUseSystemPrintDialog = bSet; SetModified(); } + + bool ShowLinkWarningDialog() const + { return m_bShowLinkWarningDialog; } + + void SetShowLinkWarningDialog( bool bSet ) + { m_bShowLinkWarningDialog = bSet; SetModified(); } + + bool IsShowLinkWarningDialogReadOnly() const + { return m_bIsShowLinkWarningDialogRO; } + + void AddListenerLink( const Link<LinkParamNone*,void>& rLink ); + void RemoveListenerLink( const Link<LinkParamNone*,void>& rLink ); + void CallListeners(); + + + // private methods + + +private: + + /*-**************************************************************************************************** + @short return list of key names of our configuration management which represent our module tree + @descr These methods return a static const list of key names. We need it to get needed values from our + configuration management. + @return A list of needed configuration keys is returned. + *//*-*****************************************************************************************************/ + + static Sequence< OUString > GetPropertyNames(); +}; + + +// constructor + +SvtMiscOptions_Impl::SvtMiscOptions_Impl() + // Init baseclasses first + : ConfigItem( ROOTNODE_MISC ) + + , m_bUseSystemFileDialog( false ) + , m_bIsUseSystemFileDialogRO( false ) + , m_bPluginsEnabled( false ) + , m_bIsPluginsEnabledRO( false ) + , m_nSymbolsSize( 0 ) + , m_bIsSymbolsSizeRO( false ) + , m_nSidebarIconSize( ToolBoxButtonSize::DontCare ) + , m_bIsSidebarIconSizeRO( false ) + , m_nNotebookbarIconSize( ToolBoxButtonSize::DontCare ) + , m_bIsNotebookbarIconSizeRO( false ) + , m_bIsSymbolsStyleRO( false ) + , m_nToolboxStyle( 1 ) + , m_bIsToolboxStyleRO( false ) + , m_bUseSystemPrintDialog( false ) + , m_bIsUseSystemPrintDialogRO( false ) + , m_bShowLinkWarningDialog( true ) + , m_bIsShowLinkWarningDialogRO( false ) + , m_bExperimentalMode( false ) + , m_bMacroRecorderMode( false ) + , m_bIconThemeWasSetAutomatically( false ) +{ + // Use our static list of configuration keys to get his values. + Sequence< OUString > seqNames = GetPropertyNames ( ); + Load( seqNames ); + Sequence< Any > seqValues = GetProperties ( seqNames ); + Sequence< sal_Bool > seqRO = GetReadOnlyStates ( seqNames ); + + // Safe impossible cases. + // We need values from ALL configuration keys. + // Follow assignment use order of values in relation to our list of key names! + DBG_ASSERT( !(seqNames.getLength()!=seqValues.getLength()), "SvtMiscOptions_Impl::SvtMiscOptions_Impl()\nI miss some values of configuration keys!\n" ); + + // Copy values from list in right order to our internal member. + sal_Int32 nPropertyCount = seqValues.getLength(); + for( sal_Int32 nProperty=0; nProperty<nPropertyCount; ++nProperty ) + { + if (!seqValues[nProperty].hasValue()) + continue; + switch( nProperty ) + { + case PROPERTYHANDLE_PLUGINSENABLED : + { + if( !(seqValues[nProperty] >>= m_bPluginsEnabled) ) + { + OSL_FAIL("Wrong type of \"Misc\\PluginsEnabled\"!" ); + } + m_bIsPluginsEnabledRO = seqRO[nProperty]; + break; + } + + case PROPERTYHANDLE_SYMBOLSET : + { + if( !(seqValues[nProperty] >>= m_nSymbolsSize) ) + { + OSL_FAIL("Wrong type of \"Misc\\SymbolSet\"!" ); + } + m_bIsSymbolsSizeRO = seqRO[nProperty]; + break; + } + + case PROPERTYHANDLE_SIDEBARICONSIZE : + { + sal_uInt16 nTmp; + if( !(seqValues[nProperty] >>= nTmp) ) + { + OSL_FAIL("Wrong type of \"Misc\\SidebarIconSize\"!" ); + } else + m_nSidebarIconSize = static_cast<ToolBoxButtonSize>(nTmp); + m_bIsSidebarIconSizeRO = seqRO[nProperty]; + break; + } + + case PROPERTYHANDLE_NOTEBOOKBARICONSIZE : + { + sal_uInt16 nTmp; + if( !(seqValues[nProperty] >>= nTmp) ) + { + OSL_FAIL("Wrong type of \"Misc\\NotebookbarIconSize\"!" ); + } else + m_nNotebookbarIconSize = static_cast<ToolBoxButtonSize>(nTmp); + m_bIsNotebookbarIconSizeRO = seqRO[nProperty]; + break; + } + + case PROPERTYHANDLE_TOOLBOXSTYLE : + { + if( !(seqValues[nProperty] >>= m_nToolboxStyle) ) + { + OSL_FAIL("Wrong type of \"Misc\\ToolboxStyle\"!" ); + } + m_bIsToolboxStyleRO = seqRO[nProperty]; + break; + } + + case PROPERTYHANDLE_USESYSTEMFILEDIALOG : + { + if( !(seqValues[nProperty] >>= m_bUseSystemFileDialog) ) + { + OSL_FAIL("Wrong type of \"Misc\\UseSystemFileDialog\"!" ); + } + m_bIsUseSystemFileDialogRO = seqRO[nProperty]; + break; + } + + case PROPERTYHANDLE_USESYSTEMPRINTDIALOG : + { + if( !(seqValues[nProperty] >>= m_bUseSystemPrintDialog) ) + { + OSL_FAIL("Wrong type of \"Misc\\UseSystemPrintDialog\"!" ); + } + m_bIsUseSystemPrintDialogRO = seqRO[nProperty]; + break; + } + + case PROPERTYHANDLE_SHOWLINKWARNINGDIALOG : + { + if( !(seqValues[nProperty] >>= m_bShowLinkWarningDialog) ) + { + OSL_FAIL("Wrong type of \"Misc\\ShowLinkWarningDialog\"!" ); + } + m_bIsShowLinkWarningDialogRO = seqRO[nProperty]; + break; + } + + case PROPERTYHANDLE_SYMBOLSTYLE : + { + OUString aIconTheme; + if (seqValues[nProperty] >>= aIconTheme) + SetIconTheme(aIconTheme, SetModifiedFlag::DONT_SET); + else + OSL_FAIL("Wrong type of \"Misc\\SymbolStyle\"!" ); + + m_bIsSymbolsStyleRO = seqRO[nProperty]; + break; + } + + case PROPERTYHANDLE_DISABLEUICUSTOMIZATION : + { + if( !(seqValues[nProperty] >>= m_bDisableUICustomization) ) + OSL_FAIL("Wrong type of \"Misc\\DisableUICustomization\"!" ); + break; + } + case PROPERTYHANDLE_EXPERIMENTALMODE : + { + if( !(seqValues[nProperty] >>= m_bExperimentalMode) ) + OSL_FAIL("Wrong type of \"Misc\\ExperimentalMode\"!" ); + break; + } + case PROPERTYHANDLE_MACRORECORDERMODE : + { + if( !(seqValues[nProperty] >>= m_bMacroRecorderMode) ) + OSL_FAIL("Wrong type of \"Misc\\MacroRecorderMode\"!" ); + break; + } + } + } + + // Enable notification mechanism of our baseclass. + // We need it to get information about changes outside these class on our used configuration keys! + EnableNotification( seqNames ); +} + + +// destructor + +SvtMiscOptions_Impl::~SvtMiscOptions_Impl() +{ + assert(!IsModified()); // should have been committed +} + +void SvtMiscOptions_Impl::Load( const Sequence< OUString >& rPropertyNames ) +{ + const uno::Sequence< OUString> aInternalPropertyNames( GetPropertyNames()); + Sequence< Any > seqValues = GetProperties( rPropertyNames ); + + // Safe impossible cases. + // We need values from ALL configuration keys. + // Follow assignment use order of values in relation to our list of key names! + DBG_ASSERT( !(rPropertyNames.getLength()!=seqValues.getLength()), "SvtSecurityOptions_Impl::SvtSecurityOptions_Impl()\nI miss some values of configuration keys!\n" ); + + // Copy values from list in right order to our internal member. + sal_Int32 nPropertyCount = seqValues.getLength(); + for( sal_Int32 nProperty=0; nProperty<nPropertyCount; ++nProperty ) + { + if (!seqValues[nProperty].hasValue()) + continue; + switch( comphelper::findValue(aInternalPropertyNames, rPropertyNames[nProperty]) ) + { + case PROPERTYHANDLE_PLUGINSENABLED : { + if( !(seqValues[nProperty] >>= m_bPluginsEnabled) ) + { + OSL_FAIL("Wrong type of \"Misc\\PluginsEnabled\"!" ); + } + } + break; + case PROPERTYHANDLE_SYMBOLSET : { + if( !(seqValues[nProperty] >>= m_nSymbolsSize) ) + { + OSL_FAIL("Wrong type of \"Misc\\SymbolSet\"!" ); + } + } + break; + case PROPERTYHANDLE_SIDEBARICONSIZE : { + sal_uInt16 nTmp; + if( !(seqValues[nProperty] >>= nTmp) ) + { + OSL_FAIL("Wrong type of \"Misc\\SidebarIconSize\"!" ); + } else + m_nSidebarIconSize = static_cast<ToolBoxButtonSize>(nTmp); + } + break; + case PROPERTYHANDLE_NOTEBOOKBARICONSIZE : { + sal_uInt16 nTmp; + if( !(seqValues[nProperty] >>= nTmp ) ) + { + OSL_FAIL("Wrong type of \"Misc\\NotebookbarIconSize\"!" ); + } else + m_nNotebookbarIconSize = static_cast<ToolBoxButtonSize>(nTmp); + } + break; + case PROPERTYHANDLE_TOOLBOXSTYLE : { + if( !(seqValues[nProperty] >>= m_nToolboxStyle) ) + { + OSL_FAIL("Wrong type of \"Misc\\ToolboxStyle\"!" ); + } + } + break; + case PROPERTYHANDLE_USESYSTEMFILEDIALOG : { + if( !(seqValues[nProperty] >>= m_bUseSystemFileDialog) ) + { + OSL_FAIL("Wrong type of \"Misc\\UseSystemFileDialog\"!" ); + } + } + break; + case PROPERTYHANDLE_USESYSTEMPRINTDIALOG : { + if( !(seqValues[nProperty] >>= m_bUseSystemPrintDialog) ) + { + OSL_FAIL("Wrong type of \"Misc\\UseSystemPrintDialog\"!" ); + } + } + break; + case PROPERTYHANDLE_SHOWLINKWARNINGDIALOG : { + if( !(seqValues[nProperty] >>= m_bShowLinkWarningDialog) ) + { + OSL_FAIL("Wrong type of \"Misc\\ShowLinkWarningDialog\"!" ); + } + } + break; + case PROPERTYHANDLE_SYMBOLSTYLE : { + OUString aIconTheme; + if (seqValues[nProperty] >>= aIconTheme) + SetIconTheme(aIconTheme, SetModifiedFlag::DONT_SET); + else + OSL_FAIL("Wrong type of \"Misc\\SymbolStyle\"!" ); + } + break; + case PROPERTYHANDLE_DISABLEUICUSTOMIZATION : { + if( !(seqValues[nProperty] >>= m_bDisableUICustomization) ) + OSL_FAIL("Wrong type of \"Misc\\DisableUICustomization\"!" ); + } + break; + } + } +} + +void SvtMiscOptions_Impl::AddListenerLink( const Link<LinkParamNone*,void>& rLink ) +{ + aList.push_back( rLink ); +} + +void SvtMiscOptions_Impl::RemoveListenerLink( const Link<LinkParamNone*,void>& rLink ) +{ + aList.erase(std::remove(aList.begin(), aList.end(), rLink), aList.end()); +} + +void SvtMiscOptions_Impl::CallListeners() +{ + for (auto const& elem : aList) + elem.Call( nullptr ); +} + +void SvtMiscOptions_Impl::SetToolboxStyle( sal_Int16 nStyle ) +{ + m_nToolboxStyle = nStyle ? 1 : 0; + SetModified(); + CallListeners(); +} + +void SvtMiscOptions_Impl::SetSymbolsSize( sal_Int16 nSet ) +{ + m_nSymbolsSize = nSet; + SetModified(); + CallListeners(); +} + +void SvtMiscOptions_Impl::SetSidebarIconSize( ToolBoxButtonSize nSet ) +{ + m_nSidebarIconSize = nSet; + SetModified(); + CallListeners(); +} + +void SvtMiscOptions_Impl::SetNotebookbarIconSize( ToolBoxButtonSize nSet ) +{ + m_nNotebookbarIconSize = nSet; + SetModified(); + CallListeners(); +} + +OUString SvtMiscOptions_Impl::GetIconTheme() +{ + return Application::GetSettings().GetStyleSettings().DetermineIconTheme(); +} + +void +SvtMiscOptions_Impl::SetIconTheme(const OUString &rName, SetModifiedFlag setModified) +{ + OUString aTheme(rName); + if (aTheme.isEmpty() || aTheme == "auto") + { + aTheme = Application::GetSettings().GetStyleSettings().GetAutomaticallyChosenIconTheme(); + m_bIconThemeWasSetAutomatically = true; + } + else + m_bIconThemeWasSetAutomatically = false; + + AllSettings aAllSettings = Application::GetSettings(); + StyleSettings aStyleSettings = aAllSettings.GetStyleSettings(); + aStyleSettings.SetIconTheme(aTheme); + + aAllSettings.SetStyleSettings(aStyleSettings); + Application::MergeSystemSettings( aAllSettings ); + Application::SetSettings(aAllSettings); + + if (setModified == SetModifiedFlag::SET) { + SetModified(); + } + CallListeners(); +} + + +// public method + +void SvtMiscOptions_Impl::Notify( const Sequence< OUString >& rPropertyNames ) +{ + Load( rPropertyNames ); + CallListeners(); +} + + +// public method + +void SvtMiscOptions_Impl::ImplCommit() +{ + // Get names of supported properties, create a list for values and copy current values to it. + Sequence< OUString > seqNames = GetPropertyNames (); + sal_Int32 nCount = seqNames.getLength(); + Sequence< Any > seqValues ( nCount ); + for( sal_Int32 nProperty=0; nProperty<nCount; ++nProperty ) + { + switch( nProperty ) + { + case PROPERTYHANDLE_PLUGINSENABLED : + { + if ( !m_bIsPluginsEnabledRO ) + seqValues[nProperty] <<= m_bPluginsEnabled; + break; + } + + case PROPERTYHANDLE_SYMBOLSET : + { + if ( !m_bIsSymbolsSizeRO ) + seqValues[nProperty] <<= m_nSymbolsSize; + break; + } + + case PROPERTYHANDLE_SIDEBARICONSIZE : + { + if ( !m_bIsSidebarIconSizeRO ) + seqValues[nProperty] <<= static_cast<sal_uInt16>(m_nSidebarIconSize); + break; + } + + case PROPERTYHANDLE_NOTEBOOKBARICONSIZE : + { + if ( !m_bIsNotebookbarIconSizeRO ) + seqValues[nProperty] <<= static_cast<sal_uInt16>(m_nNotebookbarIconSize); + break; + } + + case PROPERTYHANDLE_TOOLBOXSTYLE : + { + if ( !m_bIsToolboxStyleRO ) + seqValues[nProperty] <<= m_nToolboxStyle; + break; + } + + case PROPERTYHANDLE_USESYSTEMFILEDIALOG : + { + if ( !m_bIsUseSystemFileDialogRO ) + seqValues[nProperty] <<= m_bUseSystemFileDialog; + break; + } + + case PROPERTYHANDLE_SYMBOLSTYLE : + { + if ( !m_bIsSymbolsStyleRO ) { + OUString value; + if (m_bIconThemeWasSetAutomatically) { + value = "auto"; + } + else { + value = GetIconTheme(); + } + seqValues[nProperty] <<= value; + } + break; + } + + case PROPERTYHANDLE_USESYSTEMPRINTDIALOG : + { + if ( !m_bIsUseSystemPrintDialogRO ) + seqValues[nProperty] <<= m_bUseSystemPrintDialog; + break; + } + + case PROPERTYHANDLE_SHOWLINKWARNINGDIALOG : + { + if ( !m_bIsShowLinkWarningDialogRO ) + seqValues[nProperty] <<= m_bShowLinkWarningDialog; + break; + } + + case PROPERTYHANDLE_DISABLEUICUSTOMIZATION : + { + seqValues[nProperty] <<= m_bDisableUICustomization; + break; + } + case PROPERTYHANDLE_EXPERIMENTALMODE : + { + seqValues[nProperty] <<= m_bExperimentalMode; + break; + } + case PROPERTYHANDLE_MACRORECORDERMODE : + { + seqValues[nProperty] <<= m_bMacroRecorderMode; + break; + } + } + } + // Set properties in configuration. + PutProperties( seqNames, seqValues ); +} + + +// private method + +Sequence< OUString > SvtMiscOptions_Impl::GetPropertyNames() +{ + return Sequence<OUString> + { + PROPERTYNAME_PLUGINSENABLED, + PROPERTYNAME_SYMBOLSET, + PROPERTYNAME_TOOLBOXSTYLE, + PROPERTYNAME_USESYSTEMFILEDIALOG, + PROPERTYNAME_ICONTHEME, + PROPERTYNAME_USESYSTEMPRINTDIALOG, + PROPERTYNAME_SHOWLINKWARNINGDIALOG, + PROPERTYNAME_DISABLEUICUSTOMIZATION, + PROPERTYNAME_EXPERIMENTALMODE, + PROPERTYNAME_MACRORECORDERMODE, + PROPERTYNAME_SIDEBARICONSIZE, + PROPERTYNAME_NOTEBOOKBARICONSIZE + }; +} + +namespace { + +std::weak_ptr<SvtMiscOptions_Impl> g_pMiscOptions; + +} + +SvtMiscOptions::SvtMiscOptions() +{ + // Global access, must be guarded (multithreading!). + MutexGuard aGuard( GetInitMutex() ); + + m_pImpl = g_pMiscOptions.lock(); + if( !m_pImpl ) + { + m_pImpl = std::make_shared<SvtMiscOptions_Impl>(); + g_pMiscOptions = m_pImpl; + svtools::ItemHolder2::holdConfigItem(EItem::MiscOptions); + } +} + +SvtMiscOptions::~SvtMiscOptions() +{ + // Global access, must be guarded (multithreading!) + MutexGuard aGuard( GetInitMutex() ); + + m_pImpl.reset(); +} + +bool SvtMiscOptions::UseSystemFileDialog() const +{ + return m_pImpl->UseSystemFileDialog(); +} + +void SvtMiscOptions::SetUseSystemFileDialog( bool bEnable ) +{ + m_pImpl->SetUseSystemFileDialog( bEnable ); +} + +bool SvtMiscOptions::IsUseSystemFileDialogReadOnly() const +{ + return m_pImpl->IsUseSystemFileDialogReadOnly(); +} + +bool SvtMiscOptions::IsPluginsEnabled() const +{ + return m_pImpl->IsPluginsEnabled(); +} + +sal_Int16 SvtMiscOptions::GetSymbolsSize() const +{ + return m_pImpl->GetSymbolsSize(); +} + +void SvtMiscOptions::SetSymbolsSize( sal_Int16 nSet ) +{ + m_pImpl->SetSymbolsSize( nSet ); +} + +ToolBoxButtonSize SvtMiscOptions::GetSidebarIconSize() const +{ + return m_pImpl->GetSidebarIconSize(); +} + +ToolBoxButtonSize SvtMiscOptions::GetNotebookbarIconSize() const +{ + return m_pImpl->GetNotebookbarIconSize(); +} + +void SvtMiscOptions::SetSidebarIconSize( ToolBoxButtonSize nSet ) +{ + m_pImpl->SetSidebarIconSize( nSet ); +} + +void SvtMiscOptions::SetNotebookbarIconSize( ToolBoxButtonSize nSet ) +{ + m_pImpl->SetNotebookbarIconSize( nSet ); +} + +sal_Int16 SvtMiscOptions::GetCurrentSymbolsSize() const +{ + sal_Int16 eOptSymbolsSize = m_pImpl->GetSymbolsSize(); + + if ( eOptSymbolsSize == SFX_SYMBOLS_SIZE_AUTO ) + { + // Use system settings, we have to retrieve the toolbar icon size from the + // Application class + ToolbarIconSize nStyleIconSize = Application::GetSettings().GetStyleSettings().GetToolbarIconSize(); + if (nStyleIconSize == ToolbarIconSize::Size32) + eOptSymbolsSize = SFX_SYMBOLS_SIZE_32; + else if (nStyleIconSize == ToolbarIconSize::Large) + eOptSymbolsSize = SFX_SYMBOLS_SIZE_LARGE; + else + eOptSymbolsSize = SFX_SYMBOLS_SIZE_SMALL; + } + + return eOptSymbolsSize; +} + +bool SvtMiscOptions::AreCurrentSymbolsLarge() const +{ + return ( GetCurrentSymbolsSize() == SFX_SYMBOLS_SIZE_LARGE || GetCurrentSymbolsSize() == SFX_SYMBOLS_SIZE_32); +} + +OUString SvtMiscOptions::GetIconTheme() const +{ + return SvtMiscOptions_Impl::GetIconTheme(); +} + +void SvtMiscOptions::SetIconTheme(const OUString& iconTheme) +{ + m_pImpl->SetIconTheme(iconTheme, SvtMiscOptions_Impl::SetModifiedFlag::SET); +} + +bool SvtMiscOptions::DisableUICustomization() const +{ + return m_pImpl->DisableUICustomization(); +} + +sal_Int16 SvtMiscOptions::GetToolboxStyle() const +{ + return m_pImpl->GetToolboxStyle(); +} + +void SvtMiscOptions::SetToolboxStyle( sal_Int16 nStyle ) +{ + m_pImpl->SetToolboxStyle( nStyle ); +} + +bool SvtMiscOptions::UseSystemPrintDialog() const +{ + return m_pImpl->UseSystemPrintDialog(); +} + +void SvtMiscOptions::SetUseSystemPrintDialog( bool bEnable ) +{ + m_pImpl->SetUseSystemPrintDialog( bEnable ); +} + +bool SvtMiscOptions::ShowLinkWarningDialog() const +{ + return m_pImpl->ShowLinkWarningDialog(); +} + +void SvtMiscOptions::SetShowLinkWarningDialog( bool bSet ) +{ + m_pImpl->SetShowLinkWarningDialog( bSet ); +} + +bool SvtMiscOptions::IsShowLinkWarningDialogReadOnly() const +{ + return m_pImpl->IsShowLinkWarningDialogReadOnly(); +} + +void SvtMiscOptions::SetExperimentalMode( bool bSet ) +{ + m_pImpl->SetExperimentalMode( bSet ); +} + +bool SvtMiscOptions::IsExperimentalMode() const +{ + return m_pImpl->IsExperimentalMode(); +} + +void SvtMiscOptions::SetMacroRecorderMode( bool bSet ) +{ + m_pImpl->SetMacroRecorderMode( bSet ); +} + +bool SvtMiscOptions::IsMacroRecorderMode() const +{ + return m_pImpl->IsMacroRecorderMode(); +} + +namespace +{ + class theSvtMiscOptionsMutex : + public rtl::Static< osl::Mutex, theSvtMiscOptionsMutex > {}; +} + +Mutex & SvtMiscOptions::GetInitMutex() +{ + return theSvtMiscOptionsMutex::get(); +} + +void SvtMiscOptions::AddListenerLink( const Link<LinkParamNone*,void>& rLink ) +{ + m_pImpl->AddListenerLink( rLink ); +} + +void SvtMiscOptions::RemoveListenerLink( const Link<LinkParamNone*,void>& rLink ) +{ + m_pImpl->RemoveListenerLink( rLink ); +} + +bool +SvtMiscOptions::IconThemeWasSetAutomatically() +{ + return m_pImpl->IconThemeWasSetAutomatically(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/config/optionsdrawinglayer.cxx b/svtools/source/config/optionsdrawinglayer.cxx new file mode 100644 index 000000000..18a2ab4a0 --- /dev/null +++ b/svtools/source/config/optionsdrawinglayer.cxx @@ -0,0 +1,1020 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <svtools/optionsdrawinglayer.hxx> +#include <unotools/configmgr.hxx> +#include <unotools/configitem.hxx> +#include <tools/debug.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> +#include <vcl/svapp.hxx> +#include <vcl/outdev.hxx> +#include <vcl/settings.hxx> +#include <rtl/instance.hxx> + +// namespaces + +using namespace ::utl ; +using namespace ::osl ; +using namespace ::com::sun::star::uno ; + +#define ROOTNODE_START "Office.Common/Drawinglayer" +#define DEFAULT_OVERLAYBUFFER true +#define DEFAULT_PAINTBUFFER true +#define DEFAULT_STRIPE_COLOR_A Color(0) +#define DEFAULT_STRIPE_COLOR_B Color(16581375) +#define DEFAULT_STRIPE_LENGTH 4 + +// #i73602# +// #i74769#, #i75172# : Change default for Calc and Writer to True +#define DEFAULT_OVERLAYBUFFER_CALC true +#define DEFAULT_OVERLAYBUFFER_WRITER true +#define DEFAULT_OVERLAYBUFFER_DRAWIMPRESS true + +// #i74769#, #i75172# +#define DEFAULT_PAINTBUFFER_CALC true +#define DEFAULT_PAINTBUFFER_WRITER true +#define DEFAULT_PAINTBUFFER_DRAWIMPRESS true + +// #i4219# +#define DEFAULT_MAXIMUMPAPERWIDTH 600 +#define DEFAULT_MAXIMUMPAPERHEIGHT 600 +#define DEFAULT_MAXIMUMPAPERLEFTMARGIN 9999 +#define DEFAULT_MAXIMUMPAPERRIGHTMARGIN 9999 +#define DEFAULT_MAXIMUMPAPERTOPMARGIN 9999 +#define DEFAULT_MAXIMUMPAPERBOTTOMMARGIN 9999 + +// primitives +#define DEFAULT_ANTIALIASING true +#define DEFAULT_SNAPHORVERLINESTODISCRETE true +#define DEFAULT_SOLIDDRAGCREATE true +#define DEFAULT_RENDERDECORATEDTEXTDIRECT true +#define DEFAULT_RENDERSIMPLETEXTDIRECT true +#define DEFAULT_QUADRATIC3DRENDERLIMIT 1000000 +#define DEFAULT_QUADRATICFORMCONTROLRENDERLIMIT 45000 + +// #i97672# selection settings +#define DEFAULT_TRANSPARENTSELECTION true +#define DEFAULT_TRANSPARENTSELECTIONPERCENT 75 +#define DEFAULT_SELECTIONMAXIMUMLUMINANCEPERCENT 70 + +#define PROPERTYNAME_OVERLAYBUFFER OUString("OverlayBuffer" ) +#define PROPERTYNAME_PAINTBUFFER OUString("PaintBuffer" ) +#define PROPERTYNAME_STRIPE_COLOR_A OUString("StripeColorA" ) +#define PROPERTYNAME_STRIPE_COLOR_B OUString("StripeColorB" ) +#define PROPERTYNAME_STRIPE_LENGTH OUString("StripeLength" ) + +// #i73602# +#define PROPERTYNAME_OVERLAYBUFFER_CALC OUString("OverlayBuffer_Calc") +#define PROPERTYNAME_OVERLAYBUFFER_WRITER OUString("OverlayBuffer_Writer") +#define PROPERTYNAME_OVERLAYBUFFER_DRAWIMPRESS OUString("OverlayBuffer_DrawImpress") + +// #i74769#, #i75172# +#define PROPERTYNAME_PAINTBUFFER_CALC OUString("PaintBuffer_Calc") +#define PROPERTYNAME_PAINTBUFFER_WRITER OUString("PaintBuffer_Writer") +#define PROPERTYNAME_PAINTBUFFER_DRAWIMPRESS OUString("PaintBuffer_DrawImpress") + +// #i4219# +#define PROPERTYNAME_MAXIMUMPAPERWIDTH OUString("MaximumPaperWidth") +#define PROPERTYNAME_MAXIMUMPAPERHEIGHT OUString("MaximumPaperHeight") +#define PROPERTYNAME_MAXIMUMPAPERLEFTMARGIN OUString("MaximumPaperLeftMargin") +#define PROPERTYNAME_MAXIMUMPAPERRIGHTMARGIN OUString("MaximumPaperRightMargin") +#define PROPERTYNAME_MAXIMUMPAPERTOPMARGIN OUString("MaximumPaperTopMargin") +#define PROPERTYNAME_MAXIMUMPAPERBOTTOMMARGIN OUString("MaximumPaperBottomMargin") + +// primitives +#define PROPERTYNAME_ANTIALIASING OUString("AntiAliasing") +#define PROPERTYNAME_SNAPHORVERLINESTODISCRETE OUString("SnapHorVerLinesToDiscrete") +#define PROPERTYNAME_SOLIDDRAGCREATE OUString("SolidDragCreate") +#define PROPERTYNAME_RENDERDECORATEDTEXTDIRECT OUString("RenderDecoratedTextDirect") +#define PROPERTYNAME_RENDERSIMPLETEXTDIRECT OUString("RenderSimpleTextDirect") +#define PROPERTYNAME_QUADRATIC3DRENDERLIMIT OUString("Quadratic3DRenderLimit") +#define PROPERTYNAME_QUADRATICFORMCONTROLRENDERLIMIT OUString("QuadraticFormControlRenderLimit") + +// #i97672# selection settings +#define PROPERTYNAME_TRANSPARENTSELECTION OUString("TransparentSelection") +#define PROPERTYNAME_TRANSPARENTSELECTIONPERCENT OUString("TransparentSelectionPercent") +#define PROPERTYNAME_SELECTIONMAXIMUMLUMINANCEPERCENT OUString("SelectionMaximumLuminancePercent") + +#define PROPERTYHANDLE_OVERLAYBUFFER 0 +#define PROPERTYHANDLE_PAINTBUFFER 1 +#define PROPERTYHANDLE_STRIPE_COLOR_A 2 +#define PROPERTYHANDLE_STRIPE_COLOR_B 3 +#define PROPERTYHANDLE_STRIPE_LENGTH 4 + +// #i73602# +#define PROPERTYHANDLE_OVERLAYBUFFER_CALC 5 +#define PROPERTYHANDLE_OVERLAYBUFFER_WRITER 6 +#define PROPERTYHANDLE_OVERLAYBUFFER_DRAWIMPRESS 7 + +// #i74769#, #i75172# +#define PROPERTYHANDLE_PAINTBUFFER_CALC 8 +#define PROPERTYHANDLE_PAINTBUFFER_WRITER 9 +#define PROPERTYHANDLE_PAINTBUFFER_DRAWIMPRESS 10 + +// #i4219# +#define PROPERTYHANDLE_MAXIMUMPAPERWIDTH 11 +#define PROPERTYHANDLE_MAXIMUMPAPERHEIGHT 12 +#define PROPERTYHANDLE_MAXIMUMPAPERLEFTMARGIN 13 +#define PROPERTYHANDLE_MAXIMUMPAPERRIGHTMARGIN 14 +#define PROPERTYHANDLE_MAXIMUMPAPERTOPMARGIN 15 +#define PROPERTYHANDLE_MAXIMUMPAPERBOTTOMMARGIN 16 + +// primitives +#define PROPERTYHANDLE_ANTIALIASING 17 +#define PROPERTYHANDLE_SNAPHORVERLINESTODISCRETE 18 +#define PROPERTYHANDLE_SOLIDDRAGCREATE 19 +#define PROPERTYHANDLE_RENDERDECORATEDTEXTDIRECT 20 +#define PROPERTYHANDLE_RENDERSIMPLETEXTDIRECT 21 +#define PROPERTYHANDLE_QUADRATIC3DRENDERLIMIT 22 +#define PROPERTYHANDLE_QUADRATICFORMCONTROLRENDERLIMIT 23 + +// #i97672# selection settings +#define PROPERTYHANDLE_TRANSPARENTSELECTION 24 +#define PROPERTYHANDLE_TRANSPARENTSELECTIONPERCENT 25 +#define PROPERTYHANDLE_SELECTIONMAXIMUMLUMINANCEPERCENT 26 + +#define PROPERTYCOUNT 27 + +class SvtOptionsDrawinglayer_Impl : public ConfigItem +{ +public: + SvtOptionsDrawinglayer_Impl(); + ~SvtOptionsDrawinglayer_Impl() override; + + virtual void Notify( const css::uno::Sequence<OUString>& aPropertyNames) override; + + bool IsOverlayBuffer() const { return m_bOverlayBuffer;} + bool IsPaintBuffer() const { return m_bPaintBuffer;} + const Color& GetStripeColorA() const { return m_bStripeColorA;} + const Color& GetStripeColorB() const { return m_bStripeColorB;} + sal_uInt16 GetStripeLength() const { return m_nStripeLength;} + + // #i73602# + bool IsOverlayBuffer_Calc() const { return m_bOverlayBuffer_Calc;} + bool IsOverlayBuffer_Writer() const { return m_bOverlayBuffer_Writer;} + bool IsOverlayBuffer_DrawImpress() const { return m_bOverlayBuffer_DrawImpress;} + + // #i74769#, #i75172# + bool IsPaintBuffer_Calc() const { return m_bPaintBuffer_Calc;} + bool IsPaintBuffer_Writer() const { return m_bPaintBuffer_Writer;} + bool IsPaintBuffer_DrawImpress() const { return m_bPaintBuffer_DrawImpress;} + + // #i4219# + sal_uInt32 GetMaximumPaperWidth() const { return m_nMaximumPaperWidth;} + sal_uInt32 GetMaximumPaperHeight() const { return m_nMaximumPaperHeight;} + sal_uInt32 GetMaximumPaperLeftMargin() const { return m_nMaximumPaperLeftMargin;} + sal_uInt32 GetMaximumPaperRightMargin() const { return m_nMaximumPaperRightMargin;} + sal_uInt32 GetMaximumPaperTopMargin() const { return m_nMaximumPaperTopMargin;} + sal_uInt32 GetMaximumPaperBottomMargin() const { return m_nMaximumPaperBottomMargin;} + + // helper + bool IsAAPossibleOnThisSystem() const; + + // primitives + bool IsAntiAliasing() const { return m_bAntiAliasing;} + bool IsSnapHorVerLinesToDiscrete() const { return m_bSnapHorVerLinesToDiscrete;} + bool IsSolidDragCreate() const { return m_bSolidDragCreate;} + bool IsRenderDecoratedTextDirect() const { return m_bRenderDecoratedTextDirect;} + bool IsRenderSimpleTextDirect() const { return m_bRenderSimpleTextDirect;} + sal_uInt32 GetQuadratic3DRenderLimit() const { return m_nQuadratic3DRenderLimit;} + sal_uInt32 GetQuadraticFormControlRenderLimit() const { return m_nQuadraticFormControlRenderLimit;} + + void SetAntiAliasing( bool bState ); + + // #i97672# selection settings + bool IsTransparentSelection() const { return m_bTransparentSelection;} + sal_uInt16 GetTransparentSelectionPercent() const { return m_nTransparentSelectionPercent;} + sal_uInt16 GetSelectionMaximumLuminancePercent() const { return m_nSelectionMaximumLuminancePercent;} + +// private methods + +private: + virtual void ImplCommit() final override; + + static Sequence< OUString > impl_GetPropertyNames(); + +// private member + +private: + + bool m_bOverlayBuffer; + bool m_bPaintBuffer; + Color m_bStripeColorA; + Color m_bStripeColorB; + sal_uInt16 m_nStripeLength; + + // #i73602# + bool m_bOverlayBuffer_Calc; + bool m_bOverlayBuffer_Writer; + bool m_bOverlayBuffer_DrawImpress; + + // #i74769#, #i75172# + bool m_bPaintBuffer_Calc; + bool m_bPaintBuffer_Writer; + bool m_bPaintBuffer_DrawImpress; + + // #i4219# + sal_uInt32 m_nMaximumPaperWidth; + sal_uInt32 m_nMaximumPaperHeight; + sal_uInt32 m_nMaximumPaperLeftMargin; + sal_uInt32 m_nMaximumPaperRightMargin; + sal_uInt32 m_nMaximumPaperTopMargin; + sal_uInt32 m_nMaximumPaperBottomMargin; + + // primitives + bool m_bAntiAliasing; + bool m_bSnapHorVerLinesToDiscrete; + bool m_bSolidDragCreate; + bool m_bRenderDecoratedTextDirect; + bool m_bRenderSimpleTextDirect; + sal_uInt32 m_nQuadratic3DRenderLimit; + sal_uInt32 m_nQuadraticFormControlRenderLimit; + + // #i97672# selection settings + sal_uInt16 m_nTransparentSelectionPercent; + sal_uInt16 m_nSelectionMaximumLuminancePercent; + bool m_bTransparentSelection; + + // local values + bool m_bAllowAA : 1; + bool m_bAllowAAChecked : 1; +}; + +SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl() : + ConfigItem( ROOTNODE_START ), + m_bOverlayBuffer( DEFAULT_OVERLAYBUFFER ), + m_bPaintBuffer( DEFAULT_PAINTBUFFER ), + m_bStripeColorA(DEFAULT_STRIPE_COLOR_A), + m_bStripeColorB(DEFAULT_STRIPE_COLOR_B), + m_nStripeLength(DEFAULT_STRIPE_LENGTH), + + // #i73602# + m_bOverlayBuffer_Calc( DEFAULT_OVERLAYBUFFER_CALC ), + m_bOverlayBuffer_Writer( DEFAULT_OVERLAYBUFFER_WRITER ), + m_bOverlayBuffer_DrawImpress( DEFAULT_OVERLAYBUFFER_DRAWIMPRESS ), + + // #i74769#, #i75172# + m_bPaintBuffer_Calc( DEFAULT_PAINTBUFFER_CALC ), + m_bPaintBuffer_Writer( DEFAULT_PAINTBUFFER_WRITER ), + m_bPaintBuffer_DrawImpress( DEFAULT_PAINTBUFFER_DRAWIMPRESS ), + + // #i4219# + m_nMaximumPaperWidth(DEFAULT_MAXIMUMPAPERWIDTH), + m_nMaximumPaperHeight(DEFAULT_MAXIMUMPAPERHEIGHT), + m_nMaximumPaperLeftMargin(DEFAULT_MAXIMUMPAPERLEFTMARGIN), + m_nMaximumPaperRightMargin(DEFAULT_MAXIMUMPAPERRIGHTMARGIN), + m_nMaximumPaperTopMargin(DEFAULT_MAXIMUMPAPERTOPMARGIN), + m_nMaximumPaperBottomMargin(DEFAULT_MAXIMUMPAPERBOTTOMMARGIN), + + // primitives + m_bAntiAliasing(DEFAULT_ANTIALIASING), + m_bSnapHorVerLinesToDiscrete(DEFAULT_SNAPHORVERLINESTODISCRETE), + m_bSolidDragCreate(DEFAULT_SOLIDDRAGCREATE), + m_bRenderDecoratedTextDirect(DEFAULT_RENDERDECORATEDTEXTDIRECT), + m_bRenderSimpleTextDirect(DEFAULT_RENDERSIMPLETEXTDIRECT), + m_nQuadratic3DRenderLimit(DEFAULT_QUADRATIC3DRENDERLIMIT), + m_nQuadraticFormControlRenderLimit(DEFAULT_QUADRATICFORMCONTROLRENDERLIMIT), + + // #i97672# selection settings + m_nTransparentSelectionPercent(DEFAULT_TRANSPARENTSELECTIONPERCENT), + m_nSelectionMaximumLuminancePercent(DEFAULT_SELECTIONMAXIMUMLUMINANCEPERCENT), + m_bTransparentSelection(DEFAULT_TRANSPARENTSELECTION), + + // local values + m_bAllowAA(true), + m_bAllowAAChecked(false) +{ + Sequence< OUString > seqNames( impl_GetPropertyNames() ); + Sequence< Any > seqValues = GetProperties( seqNames ) ; + + DBG_ASSERT( !(seqNames.getLength()!=seqValues.getLength()), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nI miss some values of configuration keys!\n" ); + + // Copy values from list in right order to our internal member. + sal_Int32 nPropertyCount = seqValues.getLength(); + for(sal_Int32 nProperty=0; nProperty<nPropertyCount; ++nProperty ) + { + if (!seqValues[nProperty].hasValue()) + continue; + + switch( nProperty ) + { + case PROPERTYHANDLE_OVERLAYBUFFER: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\OverlayBuffer\"?" ); + seqValues[nProperty] >>= m_bOverlayBuffer; + } + break; + + case PROPERTYHANDLE_PAINTBUFFER: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\PaintBuffer\"?" ); + seqValues[nProperty] >>= m_bPaintBuffer; + } + break; + + case PROPERTYHANDLE_STRIPE_COLOR_A: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_LONG), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\StripeColorA\"?" ); + sal_Int32 nValue = 0; + seqValues[nProperty] >>= nValue; + m_bStripeColorA = Color(nValue); + } + break; + + case PROPERTYHANDLE_STRIPE_COLOR_B: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_LONG), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\StripeColorB\"?" ); + sal_Int32 nValue = 0; + seqValues[nProperty] >>= nValue; + m_bStripeColorB = Color(nValue); + } + break; + + case PROPERTYHANDLE_STRIPE_LENGTH: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_SHORT), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\StripeLength\"?" ); + seqValues[nProperty] >>= m_nStripeLength; + } + break; + + // #i73602# + case PROPERTYHANDLE_OVERLAYBUFFER_CALC: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\OverlayBuffer_Calc\"?" ); + seqValues[nProperty] >>= m_bOverlayBuffer_Calc; + } + break; + + case PROPERTYHANDLE_OVERLAYBUFFER_WRITER: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\OverlayBuffer_Writer\"?" ); + seqValues[nProperty] >>= m_bOverlayBuffer_Writer; + } + break; + + case PROPERTYHANDLE_OVERLAYBUFFER_DRAWIMPRESS: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\OverlayBuffer_DrawImpress\"?" ); + seqValues[nProperty] >>= m_bOverlayBuffer_DrawImpress; + } + break; + + // #i74769#, #i75172# + case PROPERTYHANDLE_PAINTBUFFER_CALC: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\PaintBuffer_Calc\"?" ); + seqValues[nProperty] >>= m_bPaintBuffer_Calc; + } + break; + + case PROPERTYHANDLE_PAINTBUFFER_WRITER: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\PaintBuffer_Writer\"?" ); + seqValues[nProperty] >>= m_bPaintBuffer_Writer; + } + break; + + case PROPERTYHANDLE_PAINTBUFFER_DRAWIMPRESS: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\PaintBuffer_DrawImpress\"?" ); + seqValues[nProperty] >>= m_bPaintBuffer_DrawImpress; + } + break; + + // #i4219# + case PROPERTYHANDLE_MAXIMUMPAPERWIDTH: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_LONG), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\MaximumPaperWidth\"?" ); + seqValues[nProperty] >>= m_nMaximumPaperWidth; + } + break; + + case PROPERTYHANDLE_MAXIMUMPAPERHEIGHT: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_LONG), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\MaximumPaperHeight\"?" ); + seqValues[nProperty] >>= m_nMaximumPaperHeight; + } + break; + + case PROPERTYHANDLE_MAXIMUMPAPERLEFTMARGIN: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_LONG), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\MaximumPaperLeftMargin\"?" ); + seqValues[nProperty] >>= m_nMaximumPaperLeftMargin; + } + break; + + case PROPERTYHANDLE_MAXIMUMPAPERRIGHTMARGIN: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_LONG), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\MaximumPaperRightMargin\"?" ); + seqValues[nProperty] >>= m_nMaximumPaperRightMargin; + } + break; + + case PROPERTYHANDLE_MAXIMUMPAPERTOPMARGIN: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_LONG), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\MaximumPaperTopMargin\"?" ); + seqValues[nProperty] >>= m_nMaximumPaperTopMargin; + } + break; + + case PROPERTYHANDLE_MAXIMUMPAPERBOTTOMMARGIN: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_LONG), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\MaximumPaperBottomMargin\"?" ); + seqValues[nProperty] >>= m_nMaximumPaperBottomMargin; + } + break; + + // primitives + case PROPERTYHANDLE_ANTIALIASING: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\AntiAliasing\"?" ); + seqValues[nProperty] >>= m_bAntiAliasing; + } + break; + + // primitives + case PROPERTYHANDLE_SNAPHORVERLINESTODISCRETE: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\SnapHorVerLinesToDiscrete\"?" ); + seqValues[nProperty] >>= m_bSnapHorVerLinesToDiscrete; + } + break; + + case PROPERTYHANDLE_SOLIDDRAGCREATE: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\SolidDragCreate\"?" ); + seqValues[nProperty] >>= m_bSolidDragCreate; + } + break; + + case PROPERTYHANDLE_RENDERDECORATEDTEXTDIRECT: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\RenderDecoratedTextDirect\"?" ); + seqValues[nProperty] >>= m_bRenderDecoratedTextDirect; + } + break; + + case PROPERTYHANDLE_RENDERSIMPLETEXTDIRECT: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\RenderSimpleTextDirect\"?" ); + seqValues[nProperty] >>= m_bRenderSimpleTextDirect; + } + break; + + case PROPERTYHANDLE_QUADRATIC3DRENDERLIMIT: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_LONG), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\Quadratic3DRenderLimit\"?" ); + seqValues[nProperty] >>= m_nQuadratic3DRenderLimit; + } + break; + + case PROPERTYHANDLE_QUADRATICFORMCONTROLRENDERLIMIT: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_LONG), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\QuadraticFormControlRenderLimit\"?" ); + seqValues[nProperty] >>= m_nQuadraticFormControlRenderLimit; + } + break; + + // #i97672# selection settings + case PROPERTYHANDLE_TRANSPARENTSELECTION: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\TransparentSelection\"?" ); + seqValues[nProperty] >>= m_bTransparentSelection; + } + break; + + case PROPERTYHANDLE_TRANSPARENTSELECTIONPERCENT: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_SHORT), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\TransparentSelectionPercent\"?" ); + seqValues[nProperty] >>= m_nTransparentSelectionPercent; + } + break; + + case PROPERTYHANDLE_SELECTIONMAXIMUMLUMINANCEPERCENT: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_SHORT), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\SelectionMaximumLuminancePercent\"?" ); + seqValues[nProperty] >>= m_nSelectionMaximumLuminancePercent; + } + break; + } + } +} + +SvtOptionsDrawinglayer_Impl::~SvtOptionsDrawinglayer_Impl() +{ + if (IsModified()) + Commit(); +} + +// Commit + +void SvtOptionsDrawinglayer_Impl::ImplCommit() +{ + Sequence< OUString > aSeqNames( impl_GetPropertyNames() ); + Sequence< Any > aSeqValues( aSeqNames.getLength() ); + + for( sal_Int32 nProperty = 0, nCount = aSeqNames.getLength(); nProperty < nCount; ++nProperty ) + { + switch( nProperty ) + { + case PROPERTYHANDLE_OVERLAYBUFFER: + aSeqValues[nProperty] <<= m_bOverlayBuffer; + break; + + case PROPERTYHANDLE_PAINTBUFFER: + aSeqValues[nProperty] <<= m_bPaintBuffer; + break; + + case PROPERTYHANDLE_STRIPE_COLOR_A: + aSeqValues[nProperty] <<= m_bStripeColorA; + break; + + case PROPERTYHANDLE_STRIPE_COLOR_B: + aSeqValues[nProperty] <<= m_bStripeColorB; + break; + + case PROPERTYHANDLE_STRIPE_LENGTH: + aSeqValues[nProperty] <<= m_nStripeLength; + break; + + // #i73602# + case PROPERTYHANDLE_OVERLAYBUFFER_CALC: + aSeqValues[nProperty] <<= m_bOverlayBuffer_Calc; + break; + + case PROPERTYHANDLE_OVERLAYBUFFER_WRITER: + aSeqValues[nProperty] <<= m_bOverlayBuffer_Writer; + break; + + case PROPERTYHANDLE_OVERLAYBUFFER_DRAWIMPRESS: + aSeqValues[nProperty] <<= m_bOverlayBuffer_DrawImpress; + break; + + // #i74769#, #i75172# + case PROPERTYHANDLE_PAINTBUFFER_CALC: + aSeqValues[nProperty] <<= m_bPaintBuffer_Calc; + break; + + case PROPERTYHANDLE_PAINTBUFFER_WRITER: + aSeqValues[nProperty] <<= m_bPaintBuffer_Writer; + break; + + case PROPERTYHANDLE_PAINTBUFFER_DRAWIMPRESS: + aSeqValues[nProperty] <<= m_bPaintBuffer_DrawImpress; + break; + + // #i4219# + case PROPERTYHANDLE_MAXIMUMPAPERWIDTH: + aSeqValues[nProperty] <<= m_nMaximumPaperWidth; + break; + + case PROPERTYHANDLE_MAXIMUMPAPERHEIGHT: + aSeqValues[nProperty] <<= m_nMaximumPaperHeight; + break; + + case PROPERTYHANDLE_MAXIMUMPAPERLEFTMARGIN: + aSeqValues[nProperty] <<= m_nMaximumPaperLeftMargin; + break; + + case PROPERTYHANDLE_MAXIMUMPAPERRIGHTMARGIN: + aSeqValues[nProperty] <<= m_nMaximumPaperRightMargin; + break; + + case PROPERTYHANDLE_MAXIMUMPAPERTOPMARGIN: + aSeqValues[nProperty] <<= m_nMaximumPaperTopMargin; + break; + + case PROPERTYHANDLE_MAXIMUMPAPERBOTTOMMARGIN: + aSeqValues[nProperty] <<= m_nMaximumPaperBottomMargin; + break; + + // primitives + case PROPERTYHANDLE_ANTIALIASING: + aSeqValues[nProperty] <<= m_bAntiAliasing; + break; + + case PROPERTYHANDLE_SNAPHORVERLINESTODISCRETE: + aSeqValues[nProperty] <<= m_bSnapHorVerLinesToDiscrete; + break; + + case PROPERTYHANDLE_SOLIDDRAGCREATE: + aSeqValues[nProperty] <<= m_bSolidDragCreate; + break; + + case PROPERTYHANDLE_RENDERDECORATEDTEXTDIRECT: + aSeqValues[nProperty] <<= m_bRenderDecoratedTextDirect; + break; + + case PROPERTYHANDLE_RENDERSIMPLETEXTDIRECT: + aSeqValues[nProperty] <<= m_bRenderSimpleTextDirect; + break; + + case PROPERTYHANDLE_QUADRATIC3DRENDERLIMIT: + aSeqValues[nProperty] <<= m_nQuadratic3DRenderLimit; + break; + + case PROPERTYHANDLE_QUADRATICFORMCONTROLRENDERLIMIT: + aSeqValues[nProperty] <<= m_nQuadraticFormControlRenderLimit; + break; + + // #i97672# selection settings + case PROPERTYHANDLE_TRANSPARENTSELECTION: + aSeqValues[nProperty] <<= m_bTransparentSelection; + break; + + case PROPERTYHANDLE_TRANSPARENTSELECTIONPERCENT: + aSeqValues[nProperty] <<= m_nTransparentSelectionPercent; + break; + + case PROPERTYHANDLE_SELECTIONMAXIMUMLUMINANCEPERCENT: + aSeqValues[nProperty] <<= m_nSelectionMaximumLuminancePercent; + break; + } + } + + PutProperties( aSeqNames, aSeqValues ); +} + +void SvtOptionsDrawinglayer_Impl::Notify( const css::uno::Sequence<OUString>& ) +{ +} +// #i73602# + +// #i74769#, #i75172# + +// #i4219# + +// helper +bool SvtOptionsDrawinglayer_Impl::IsAAPossibleOnThisSystem() const +{ + if(!m_bAllowAAChecked) + { + SvtOptionsDrawinglayer_Impl* pThat = const_cast< SvtOptionsDrawinglayer_Impl* >(this); + pThat->m_bAllowAAChecked = true; + +#ifdef _WIN32 + // WIN32 uses GDIPlus with VCL for the first incarnation; this will be enhanced + // in the future to use canvases and the canvas renderer, thus an AA-abled + // canvas needs to be checked here in the future. + // Currently, just allow AA for WIN32 +#endif + + // check XRenderExtension + if(m_bAllowAA && !Application::GetDefaultDevice()->SupportsOperation( OutDevSupportType::TransparentRect )) + { + pThat->m_bAllowAA = false; + } + } + + return m_bAllowAA; +} + +// primitives + +void SvtOptionsDrawinglayer_Impl::SetAntiAliasing( bool bState ) +{ + if(m_bAntiAliasing != bState) + { + m_bAntiAliasing = bState; + SetModified(); + } +} + +// private method + +Sequence< OUString > SvtOptionsDrawinglayer_Impl::impl_GetPropertyNames() +{ + // Build list of configuration key names. + const OUString pProperties[] = + { + PROPERTYNAME_OVERLAYBUFFER , + PROPERTYNAME_PAINTBUFFER , + PROPERTYNAME_STRIPE_COLOR_A , + PROPERTYNAME_STRIPE_COLOR_B , + PROPERTYNAME_STRIPE_LENGTH , + + // #i73602# + PROPERTYNAME_OVERLAYBUFFER_CALC, + PROPERTYNAME_OVERLAYBUFFER_WRITER, + PROPERTYNAME_OVERLAYBUFFER_DRAWIMPRESS, + + // #i74769#, #i75172# + PROPERTYNAME_PAINTBUFFER_CALC, + PROPERTYNAME_PAINTBUFFER_WRITER, + PROPERTYNAME_PAINTBUFFER_DRAWIMPRESS, + + // #i4219# + PROPERTYNAME_MAXIMUMPAPERWIDTH, + PROPERTYNAME_MAXIMUMPAPERHEIGHT, + PROPERTYNAME_MAXIMUMPAPERLEFTMARGIN, + PROPERTYNAME_MAXIMUMPAPERRIGHTMARGIN, + PROPERTYNAME_MAXIMUMPAPERTOPMARGIN, + PROPERTYNAME_MAXIMUMPAPERBOTTOMMARGIN, + + // primitives + PROPERTYNAME_ANTIALIASING, + PROPERTYNAME_SNAPHORVERLINESTODISCRETE, + PROPERTYNAME_SOLIDDRAGCREATE, + PROPERTYNAME_RENDERDECORATEDTEXTDIRECT, + PROPERTYNAME_RENDERSIMPLETEXTDIRECT, + PROPERTYNAME_QUADRATIC3DRENDERLIMIT, + PROPERTYNAME_QUADRATICFORMCONTROLRENDERLIMIT, + + // #i97672# selection settings + PROPERTYNAME_TRANSPARENTSELECTION, + PROPERTYNAME_TRANSPARENTSELECTIONPERCENT, + PROPERTYNAME_SELECTIONMAXIMUMLUMINANCEPERCENT + }; + + // Initialize return sequence with these list ... + const Sequence< OUString > seqPropertyNames( pProperties, PROPERTYCOUNT ); + // ... and return it. + return seqPropertyNames; +} + +namespace { + //global + std::weak_ptr<SvtOptionsDrawinglayer_Impl> g_pOptionsDrawinglayer; +} + +SvtOptionsDrawinglayer::SvtOptionsDrawinglayer() +{ + // Global access, must be guarded (multithreading!). + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pImpl = g_pOptionsDrawinglayer.lock(); + if( !m_pImpl ) + { + m_pImpl = std::make_shared<SvtOptionsDrawinglayer_Impl>(); + g_pOptionsDrawinglayer = m_pImpl; + } +} + +SvtOptionsDrawinglayer::~SvtOptionsDrawinglayer() +{ + // Global access, must be guarded (multithreading!) + MutexGuard aGuard( GetOwnStaticMutex() ); + + m_pImpl.reset(); +} + +// public method + +bool SvtOptionsDrawinglayer::IsOverlayBuffer() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->IsOverlayBuffer(); +} + +// public method + +bool SvtOptionsDrawinglayer::IsPaintBuffer() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->IsPaintBuffer(); +} + +// public method + +Color SvtOptionsDrawinglayer::GetStripeColorA() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->GetStripeColorA(); +} + +// public method + +Color SvtOptionsDrawinglayer::GetStripeColorB() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->GetStripeColorB(); +} + +// public method + +sal_uInt16 SvtOptionsDrawinglayer::GetStripeLength() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->GetStripeLength(); +} + +// #i73602# +bool SvtOptionsDrawinglayer::IsOverlayBuffer_Calc() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->IsOverlayBuffer_Calc(); +} + +bool SvtOptionsDrawinglayer::IsOverlayBuffer_Writer() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->IsOverlayBuffer_Writer(); +} + +bool SvtOptionsDrawinglayer::IsOverlayBuffer_DrawImpress() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->IsOverlayBuffer_DrawImpress(); +} + +// #i74769#, #i75172# +bool SvtOptionsDrawinglayer::IsPaintBuffer_Calc() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->IsPaintBuffer_Calc(); +} + +bool SvtOptionsDrawinglayer::IsPaintBuffer_Writer() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->IsPaintBuffer_Writer(); +} + +bool SvtOptionsDrawinglayer::IsPaintBuffer_DrawImpress() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->IsPaintBuffer_DrawImpress(); +} + +// #i4219# +sal_uInt32 SvtOptionsDrawinglayer::GetMaximumPaperWidth() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->GetMaximumPaperWidth(); +} + +sal_uInt32 SvtOptionsDrawinglayer::GetMaximumPaperHeight() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->GetMaximumPaperHeight(); +} + +sal_uInt32 SvtOptionsDrawinglayer::GetMaximumPaperLeftMargin() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->GetMaximumPaperLeftMargin(); +} + +sal_uInt32 SvtOptionsDrawinglayer::GetMaximumPaperRightMargin() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->GetMaximumPaperRightMargin(); +} + +sal_uInt32 SvtOptionsDrawinglayer::GetMaximumPaperTopMargin() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->GetMaximumPaperTopMargin(); +} + +sal_uInt32 SvtOptionsDrawinglayer::GetMaximumPaperBottomMargin() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->GetMaximumPaperBottomMargin(); +} + +// helper +bool SvtOptionsDrawinglayer::IsAAPossibleOnThisSystem() const +{ + return m_pImpl->IsAAPossibleOnThisSystem(); +} + +// primitives +bool SvtOptionsDrawinglayer::IsAntiAliasing() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->IsAntiAliasing() && IsAAPossibleOnThisSystem(); +} + +bool SvtOptionsDrawinglayer::IsSnapHorVerLinesToDiscrete() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->IsAntiAliasing() && m_pImpl->IsSnapHorVerLinesToDiscrete(); +} + +bool SvtOptionsDrawinglayer::IsSolidDragCreate() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->IsSolidDragCreate(); +} + +bool SvtOptionsDrawinglayer::IsRenderDecoratedTextDirect() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->IsRenderDecoratedTextDirect(); +} + +bool SvtOptionsDrawinglayer::IsRenderSimpleTextDirect() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->IsRenderSimpleTextDirect(); +} + +sal_uInt32 SvtOptionsDrawinglayer::GetQuadratic3DRenderLimit() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->GetQuadratic3DRenderLimit(); +} + +sal_uInt32 SvtOptionsDrawinglayer::GetQuadraticFormControlRenderLimit() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->GetQuadraticFormControlRenderLimit(); +} + +void SvtOptionsDrawinglayer::SetAntiAliasing( bool bState ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pImpl->SetAntiAliasing( bState ); +} + +// #i97672# selection settings +bool SvtOptionsDrawinglayer::IsTransparentSelection() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->IsTransparentSelection(); +} + +sal_uInt16 SvtOptionsDrawinglayer::GetTransparentSelectionPercent() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + sal_uInt16 aRetval(m_pImpl->GetTransparentSelectionPercent()); + + // crop to range [10% .. 90%] + if(aRetval < 10) + { + aRetval = 10; + } + + if(aRetval > 90) + { + aRetval = 90; + } + + return aRetval; +} + +sal_uInt16 SvtOptionsDrawinglayer::GetSelectionMaximumLuminancePercent() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + sal_uInt16 aRetval(m_pImpl->GetSelectionMaximumLuminancePercent()); + + // crop to range [0% .. 100%] + if(aRetval > 90) + { + aRetval = 90; + } + + return aRetval; +} + +Color SvtOptionsDrawinglayer::getHilightColor() const +{ + Color aRetval(Application::GetSettings().GetStyleSettings().GetHighlightColor()); + const basegfx::BColor aSelection(aRetval.getBColor()); + const double fLuminance(aSelection.luminance()); + const double fMaxLum(GetSelectionMaximumLuminancePercent() / 100.0); + + if(fLuminance > fMaxLum) + { + const double fFactor(fMaxLum / fLuminance); + const basegfx::BColor aNewSelection( + aSelection.getRed() * fFactor, + aSelection.getGreen() * fFactor, + aSelection.getBlue() * fFactor); + + aRetval = Color(aNewSelection); + } + + return aRetval; +} + +namespace +{ + class theOptionsDrawinglayerMutex : public rtl::Static<osl::Mutex, theOptionsDrawinglayerMutex>{}; +} + +// private method + +Mutex& SvtOptionsDrawinglayer::GetOwnStaticMutex() +{ + return theOptionsDrawinglayerMutex::get(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/config/printoptions.cxx b/svtools/source/config/printoptions.cxx new file mode 100644 index 000000000..4a783863e --- /dev/null +++ b/svtools/source/config/printoptions.cxx @@ -0,0 +1,510 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <svtools/printoptions.hxx> +#include <vcl/print.hxx> +#include <com/sun/star/uno/Any.hxx> + +#include <com/sun/star/beans/XPropertySet.hpp> +#include <com/sun/star/container/XNameAccess.hpp> + +#include <comphelper/configurationhelper.hxx> +#include <comphelper/processfactory.hxx> + +#include <officecfg/Office/Common.hxx> + +#include "itemholder2.hxx" + +#include <sal/macros.h> +#include <tools/diagnose_ex.h> + +static const sal_uInt16 aDPIArray[] = { 72, 96, 150, 200, 300, 600 }; + +#define DPI_COUNT (SAL_N_ELEMENTS(aDPIArray)) + +#define ROOTNODE_START "Office.Common/Print/Option" +#define ROOTNODE_PRINTOPTION "org.openoffice.Office.Common/Print/Option" + +#define PROPERTYNAME_REDUCETRANSPARENCY "ReduceTransparency" +#define PROPERTYNAME_REDUCEDTRANSPARENCYMODE "ReducedTransparencyMode" +#define PROPERTYNAME_REDUCEGRADIENTS "ReduceGradients" +#define PROPERTYNAME_REDUCEDGRADIENTMODE "ReducedGradientMode" +#define PROPERTYNAME_REDUCEDGRADIENTSTEPCOUNT "ReducedGradientStepCount" +#define PROPERTYNAME_REDUCEBITMAPS "ReduceBitmaps" +#define PROPERTYNAME_REDUCEDBITMAPMODE "ReducedBitmapMode" +#define PROPERTYNAME_REDUCEDBITMAPRESOLUTION "ReducedBitmapResolution" +#define PROPERTYNAME_REDUCEDBITMAPINCLUDESTRANSPARENCY "ReducedBitmapIncludesTransparency" +#define PROPERTYNAME_CONVERTTOGREYSCALES "ConvertToGreyscales" +#define PROPERTYNAME_PDFASSTANDARDPRINTJOBFORMAT "PDFAsStandardPrintJobFormat" + +using namespace ::utl; +using namespace ::osl; +using namespace ::com::sun::star::uno; + +static SvtPrintOptions_Impl* pPrinterOptionsDataContainer = nullptr; +static SvtPrintOptions_Impl* pPrintFileOptionsDataContainer = nullptr; + +SvtPrintOptions_Impl* SvtPrinterOptions::m_pStaticDataContainer = nullptr; +sal_Int32 SvtPrinterOptions::m_nRefCount = 0; + +SvtPrintOptions_Impl* SvtPrintFileOptions::m_pStaticDataContainer = nullptr; +sal_Int32 SvtPrintFileOptions::m_nRefCount = 0; + +class SvtPrintOptions_Impl +{ +public: + explicit SvtPrintOptions_Impl( const OUString& rConfigRoot ); + ~SvtPrintOptions_Impl(); + + void SetReduceTransparency( bool bState ) ; + void SetReducedTransparencyMode( sal_Int16 nMode ) ; + void SetReduceGradients( bool bState ) ; + void SetReducedGradientMode( sal_Int16 nMode ) ; + void SetReducedGradientStepCount( sal_Int16 nStepCount ) ; + void SetReduceBitmaps( bool bState ) ; + void SetReducedBitmapMode( sal_Int16 nMode ) ; + void SetReducedBitmapResolution( sal_Int16 nResolution ) ; + void SetReducedBitmapIncludesTransparency( bool bState ) ; + void SetConvertToGreyscales( bool bState ) ; + void SetPDFAsStandardPrintJobFormat( bool bState ) ; + + +// private API + + +private: + void impl_setValue (const OUString& sProp, bool bNew ); + void impl_setValue (const OUString& sProp, sal_Int16 nNew ); + + +// private member + + +private: + css::uno::Reference< css::container::XNameAccess > m_xCfg; + css::uno::Reference< css::container::XNameAccess > m_xNode; +}; + +SvtPrintOptions_Impl::SvtPrintOptions_Impl(const OUString& rConfigRoot) +{ + try + { + m_xCfg.set( + ::comphelper::ConfigurationHelper::openConfig( + comphelper::getProcessComponentContext(), + ROOTNODE_PRINTOPTION, + ::comphelper::EConfigurationModes::Standard), + css::uno::UNO_QUERY); + + if (m_xCfg.is()) + { + m_xCfg->getByName(rConfigRoot.copy(rConfigRoot.lastIndexOf('/')+1)) >>= m_xNode; + } + } + catch (const css::uno::Exception&) + { + DBG_UNHANDLED_EXCEPTION("svtools.config"); + m_xNode.clear(); + m_xCfg.clear(); + } +} + +void SvtPrintOptions_Impl::SetReduceTransparency(bool bState) +{ + impl_setValue(PROPERTYNAME_REDUCETRANSPARENCY, bState); +} + +void SvtPrintOptions_Impl::SetReducedTransparencyMode(sal_Int16 nMode) +{ + impl_setValue(PROPERTYNAME_REDUCEDTRANSPARENCYMODE, nMode); +} + +void SvtPrintOptions_Impl::SetReduceGradients(bool bState) +{ + impl_setValue(PROPERTYNAME_REDUCEGRADIENTS, bState); +} + +void SvtPrintOptions_Impl::SetReducedGradientMode(sal_Int16 nMode) +{ + impl_setValue(PROPERTYNAME_REDUCEDGRADIENTMODE, nMode); +} + +void SvtPrintOptions_Impl::SetReducedGradientStepCount(sal_Int16 nStepCount ) +{ + impl_setValue(PROPERTYNAME_REDUCEDGRADIENTSTEPCOUNT, nStepCount); +} + +void SvtPrintOptions_Impl::SetReduceBitmaps(bool bState ) +{ + impl_setValue(PROPERTYNAME_REDUCEBITMAPS, bState); +} + +void SvtPrintOptions_Impl::SetReducedBitmapMode(sal_Int16 nMode ) +{ + impl_setValue(PROPERTYNAME_REDUCEDBITMAPMODE, nMode); +} + +void SvtPrintOptions_Impl::SetReducedBitmapResolution(sal_Int16 nResolution ) +{ + impl_setValue(PROPERTYNAME_REDUCEDBITMAPRESOLUTION, nResolution); +} + +void SvtPrintOptions_Impl::SetReducedBitmapIncludesTransparency(bool bState ) +{ + impl_setValue(PROPERTYNAME_REDUCEDBITMAPINCLUDESTRANSPARENCY, bState); +} + +void SvtPrintOptions_Impl::SetConvertToGreyscales(bool bState) +{ + impl_setValue(PROPERTYNAME_CONVERTTOGREYSCALES, bState); +} + +void SvtPrintOptions_Impl::SetPDFAsStandardPrintJobFormat(bool bState) +{ + impl_setValue(PROPERTYNAME_PDFASSTANDARDPRINTJOBFORMAT, bState); +} + +SvtPrintOptions_Impl::~SvtPrintOptions_Impl() +{ + m_xNode.clear(); + m_xCfg.clear(); +} + +void SvtPrintOptions_Impl::impl_setValue (const OUString& sProp, bool bNew ) +{ + try + { + if ( ! m_xNode.is()) + return; + + css::uno::Reference<css::beans::XPropertySet> xSet(m_xNode, css::uno::UNO_QUERY); + if ( ! xSet.is()) + return; + + bool bOld = ! bNew; + if ( ! (xSet->getPropertyValue(sProp) >>= bOld)) + return; + + if (bOld != bNew) + { + xSet->setPropertyValue(sProp, css::uno::makeAny(bNew)); + ::comphelper::ConfigurationHelper::flush(m_xCfg); + } + } + catch(const css::uno::Exception&) + { + DBG_UNHANDLED_EXCEPTION("svtools.config"); + } +} + +void SvtPrintOptions_Impl::impl_setValue (const OUString& sProp, + ::sal_Int16 nNew ) +{ + try + { + if ( ! m_xNode.is()) + return; + + css::uno::Reference<css::beans::XPropertySet> xSet(m_xNode, css::uno::UNO_QUERY); + if ( ! xSet.is()) + return; + + ::sal_Int16 nOld = nNew+1; + if ( ! (xSet->getPropertyValue(sProp) >>= nOld)) + return; + + if (nOld != nNew) + { + xSet->setPropertyValue(sProp, css::uno::makeAny(nNew)); + ::comphelper::ConfigurationHelper::flush(m_xCfg); + } + } + catch(const css::uno::Exception&) + { + DBG_UNHANDLED_EXCEPTION("svtools.config"); + } +} + +SvtBasePrintOptions::SvtBasePrintOptions() + : m_pDataContainer(nullptr) +{ +} + +SvtBasePrintOptions::~SvtBasePrintOptions() +{ +} + +Mutex& SvtBasePrintOptions::GetOwnStaticMutex() +{ + static Mutex ourMutex; + + return ourMutex; +} + +bool SvtBasePrintOptions::IsReduceTransparency() +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return officecfg::Office::Common::Print::Option::Printer::ReduceTransparency::get(); +} + +sal_Int16 SvtBasePrintOptions::GetReducedTransparencyMode() +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return officecfg::Office::Common::Print::Option::Printer::ReducedTransparencyMode::get(); +} + +bool SvtBasePrintOptions::IsReduceGradients() +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return officecfg::Office::Common::Print::Option::Printer::ReduceGradients::get(); +} + +sal_Int16 SvtBasePrintOptions::GetReducedGradientMode() +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return officecfg::Office::Common::Print::Option::Printer::ReducedGradientMode::get(); +} + +sal_Int16 SvtBasePrintOptions::GetReducedGradientStepCount() +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return officecfg::Office::Common::Print::Option::Printer::ReducedGradientStepCount::get(); +} + +bool SvtBasePrintOptions::IsReduceBitmaps() +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return officecfg::Office::Common::Print::Option::Printer::ReduceBitmaps::get(); +} + +sal_Int16 SvtBasePrintOptions::GetReducedBitmapMode() +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return officecfg::Office::Common::Print::Option::Printer::ReducedBitmapMode::get(); +} + +sal_Int16 SvtBasePrintOptions::GetReducedBitmapResolution() +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return officecfg::Office::Common::Print::Option::Printer::ReducedBitmapResolution::get(); +} + +bool SvtBasePrintOptions::IsReducedBitmapIncludesTransparency() +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return officecfg::Office::Common::Print::Option::Printer::ReducedBitmapIncludesTransparency::get(); +} + +bool SvtBasePrintOptions::IsConvertToGreyscales() +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return officecfg::Office::Common::Print::Option::Printer::ConvertToGreyscales::get(); +} + +bool SvtBasePrintOptions::IsPDFAsStandardPrintJobFormat() +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return officecfg::Office::Common::Print::Option::Printer::PDFAsStandardPrintJobFormat::get(); +} + +void SvtBasePrintOptions::SetReduceTransparency( bool bState ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetReduceTransparency( bState ) ; +} + +void SvtBasePrintOptions::SetReducedTransparencyMode( sal_Int16 nMode ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetReducedTransparencyMode( nMode ); +} + +void SvtBasePrintOptions::SetReduceGradients( bool bState ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetReduceGradients( bState ); +} + +void SvtBasePrintOptions::SetReducedGradientMode( sal_Int16 nMode ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetReducedGradientMode( nMode ); +} + +void SvtBasePrintOptions::SetReducedGradientStepCount( sal_Int16 nStepCount ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetReducedGradientStepCount( nStepCount ); +} + +void SvtBasePrintOptions::SetReduceBitmaps( bool bState ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetReduceBitmaps( bState ); +} + +void SvtBasePrintOptions::SetReducedBitmapMode( sal_Int16 nMode ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetReducedBitmapMode( nMode ); +} + +void SvtBasePrintOptions::SetReducedBitmapResolution( sal_Int16 nResolution ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetReducedBitmapResolution( nResolution ); +} + +void SvtBasePrintOptions::SetReducedBitmapIncludesTransparency( bool bState ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetReducedBitmapIncludesTransparency( bState ); +} + +void SvtBasePrintOptions::SetConvertToGreyscales( bool bState ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetConvertToGreyscales( bState ); +} + +void SvtBasePrintOptions::SetPDFAsStandardPrintJobFormat( bool bState ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetPDFAsStandardPrintJobFormat( bState ); +} + +void SvtBasePrintOptions::GetPrinterOptions( PrinterOptions& rOptions ) +{ + rOptions.SetReduceTransparency( IsReduceTransparency() ); + rOptions.SetReducedTransparencyMode( static_cast<PrinterTransparencyMode>(GetReducedTransparencyMode()) ); + rOptions.SetReduceGradients( IsReduceGradients() ); + rOptions.SetReducedGradientMode( static_cast<PrinterGradientMode>(GetReducedGradientMode()) ); + rOptions.SetReducedGradientStepCount( GetReducedGradientStepCount() ); + rOptions.SetReduceBitmaps( IsReduceBitmaps() ); + rOptions.SetReducedBitmapMode( static_cast<PrinterBitmapMode>(GetReducedBitmapMode()) ); + rOptions.SetReducedBitmapResolution( aDPIArray[ std::min( static_cast<sal_uInt16>(GetReducedBitmapResolution()), sal_uInt16( DPI_COUNT - 1 ) ) ] ); + rOptions.SetReducedBitmapIncludesTransparency( IsReducedBitmapIncludesTransparency() ); + rOptions.SetConvertToGreyscales( IsConvertToGreyscales() ); + rOptions.SetPDFAsStandardPrintJobFormat( IsPDFAsStandardPrintJobFormat() ); +} + +void SvtBasePrintOptions::SetPrinterOptions( const PrinterOptions& rOptions ) +{ + SetReduceTransparency( rOptions.IsReduceTransparency() ); + SetReducedTransparencyMode( + sal::static_int_cast< sal_Int16 >( + rOptions.GetReducedTransparencyMode()) ); + SetReduceGradients( rOptions.IsReduceGradients() ); + SetReducedGradientMode( + sal::static_int_cast< sal_Int16 >(rOptions.GetReducedGradientMode()) ); + SetReducedGradientStepCount( rOptions.GetReducedGradientStepCount() ); + SetReduceBitmaps( rOptions.IsReduceBitmaps() ); + SetReducedBitmapMode( + sal::static_int_cast< sal_Int16 >(rOptions.GetReducedBitmapMode()) ); + SetReducedBitmapIncludesTransparency( rOptions.IsReducedBitmapIncludesTransparency() ); + SetConvertToGreyscales( rOptions.IsConvertToGreyscales() ); + SetPDFAsStandardPrintJobFormat( rOptions.IsPDFAsStandardPrintJobFormat() ); + + const sal_uInt16 nDPI = rOptions.GetReducedBitmapResolution(); + + if( nDPI < aDPIArray[ 0 ] ) + SetReducedBitmapResolution( 0 ); + else + { + for( long i = DPI_COUNT - 1; i >= 0; i-- ) + { + if( nDPI >= aDPIArray[ i ] ) + { + SetReducedBitmapResolution( static_cast<sal_Int16>(i) ); + i = -1; + } + } + } +} + +SvtPrinterOptions::SvtPrinterOptions() +{ + // Global access, must be guarded (multithreading!). + MutexGuard aGuard( GetOwnStaticMutex() ); + // Increase our refcount ... + ++m_nRefCount; + // ... and initialize our data container only if it not already! + if( m_pStaticDataContainer == nullptr ) + { + OUString aRootPath = ROOTNODE_START "/Printer"; + m_pStaticDataContainer = new SvtPrintOptions_Impl( aRootPath ); + pPrinterOptionsDataContainer = m_pStaticDataContainer; + svtools::ItemHolder2::holdConfigItem(EItem::PrintOptions); + } + + SetDataContainer( m_pStaticDataContainer ); +} + +SvtPrinterOptions::~SvtPrinterOptions() +{ + // Global access, must be guarded (multithreading!) + MutexGuard aGuard( GetOwnStaticMutex() ); + // Decrease our refcount. + --m_nRefCount; + // If last instance was deleted ... + // we must destroy our static data container! + if( m_nRefCount <= 0 ) + { + delete m_pStaticDataContainer; + m_pStaticDataContainer = nullptr; + pPrinterOptionsDataContainer = nullptr; + } +} + +SvtPrintFileOptions::SvtPrintFileOptions() +{ + // Global access, must be guarded (multithreading!). + MutexGuard aGuard( GetOwnStaticMutex() ); + // Increase our refcount ... + ++m_nRefCount; + // ... and initialize our data container only if it not already! + if( m_pStaticDataContainer == nullptr ) + { + OUString aRootPath = ROOTNODE_START "/File"; + m_pStaticDataContainer = new SvtPrintOptions_Impl( aRootPath ); + pPrintFileOptionsDataContainer = m_pStaticDataContainer; + + svtools::ItemHolder2::holdConfigItem(EItem::PrintFileOptions); + } + + SetDataContainer( m_pStaticDataContainer ); +} + +SvtPrintFileOptions::~SvtPrintFileOptions() +{ + // Global access, must be guarded (multithreading!) + MutexGuard aGuard( GetOwnStaticMutex() ); + // Decrease our refcount. + --m_nRefCount; + // If last instance was deleted ... + // we must destroy our static data container! + if( m_nRefCount <= 0 ) + { + delete m_pStaticDataContainer; + m_pStaticDataContainer = nullptr; + pPrintFileOptionsDataContainer = nullptr; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/config/slidesorterbaropt.cxx b/svtools/source/config/slidesorterbaropt.cxx new file mode 100644 index 000000000..770876048 --- /dev/null +++ b/svtools/source/config/slidesorterbaropt.cxx @@ -0,0 +1,431 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <svtools/slidesorterbaropt.hxx> +#include <unotools/configitem.hxx> +#include <tools/debug.hxx> +#include <osl/diagnose.h> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> + +#include <comphelper/lok.hxx> +#include <comphelper/sequence.hxx> +#include <rtl/instance.hxx> + +using namespace ::utl; +using namespace ::osl; +using namespace ::com::sun::star::uno; +using namespace ::com::sun::star; + +#define ROOTNODE_SLIDESORTERBAR "Office.Impress/MultiPaneGUI/SlideSorterBar/Visible" + +#define PROPERTYNAME_VISIBLE_IMPRESSVIEW OUString("ImpressView") +#define PROPERTYHANDLE_VISIBLE_IMPRESSVIEW 0 +#define PROPERTYNAME_VISIBLE_OUTLINEVIEW OUString("OutlineView") +#define PROPERTYHANDLE_VISIBLE_OUTLINEVIEW 1 +#define PROPERTYNAME_VISIBLE_NOTESVIEW OUString("NotesView") +#define PROPERTYHANDLE_VISIBLE_NOTESVIEW 2 +#define PROPERTYNAME_VISIBLE_HANDOUTVIEW OUString("HandoutView") +#define PROPERTYHANDLE_VISIBLE_HANDOUTVIEW 3 +#define PROPERTYNAME_VISIBLE_SLIDESORTERVIEW OUString("SlideSorterView") +#define PROPERTYHANDLE_VISIBLE_SLIDESORTERVIEW 4 +#define PROPERTYNAME_VISIBLE_DRAWVIEW OUString("DrawView") +#define PROPERTYHANDLE_VISIBLE_DRAWVIEW 5 + +class SvtSlideSorterBarOptions_Impl : public ConfigItem +{ + Sequence< OUString > m_seqPropertyNames; + + public: + + SvtSlideSorterBarOptions_Impl(); + ~SvtSlideSorterBarOptions_Impl() override; + + /** called for notify of configmanager + + This method is called from the ConfigManager before the application ends or from the + PropertyChangeListener if the sub tree broadcasts changes. You must update your + internal values. + + \sa baseclass ConfigItem + \param[in,out] seqPropertyNames is the list of properties which should be updated. + */ + virtual void Notify( const Sequence< OUString >& seqPropertyNames ) override; + + /** + loads required data from the configuration. It's called in the constructor to + read all entries and form ::Notify to re-read changed setting + */ + void Load( const Sequence< OUString >& rPropertyNames ); + + // public interface + bool m_bVisibleImpressView; + bool m_bVisibleOutlineView; + bool m_bVisibleNotesView; + bool m_bVisibleHandoutView; + bool m_bVisibleSlideSorterView; + bool m_bVisibleDrawView; + + private: + virtual void ImplCommit() final override; + + /** return list of key names of our configuration management which represent our module tree + + This method returns a static const list of key names. We need it to get needed values from + configuration management. + + \return A list of needed configuration keys is returned. + */ + static Sequence< OUString > GetPropertyNames(); + + void SetVisibleViewImpl( bool& bVisibleView, bool bVisible ); + + public: + void SetVisibleImpressView( bool bVisible) + { SetVisibleViewImpl( m_bVisibleImpressView, bVisible ); } + + void SetVisibleOutlineView( bool bVisible) + { SetVisibleViewImpl( m_bVisibleOutlineView, bVisible ); } + + void SetVisibleNotesView( bool bVisible) + { SetVisibleViewImpl( m_bVisibleNotesView, bVisible ); } + + void SetVisibleHandoutView( bool bVisible) + { SetVisibleViewImpl( m_bVisibleHandoutView, bVisible ); } + + void SetVisibleSlideSorterView( bool bVisible) + { SetVisibleViewImpl( m_bVisibleSlideSorterView, bVisible ); } + + void SetVisibleDrawView( bool bVisible) + { SetVisibleViewImpl( m_bVisibleDrawView, bVisible ); } + +}; + +SvtSlideSorterBarOptions_Impl::SvtSlideSorterBarOptions_Impl() + // Init baseclasses first + : ConfigItem( ROOTNODE_SLIDESORTERBAR ) + , m_seqPropertyNames(GetPropertyNames()) + , m_bVisibleImpressView( false ) + , m_bVisibleOutlineView( false ) + , m_bVisibleNotesView( false ) + , m_bVisibleHandoutView( false ) + , m_bVisibleSlideSorterView( false ) + , m_bVisibleDrawView( false ) + +{ + // Use our static list of configuration keys to get his values. + Sequence< Any > seqValues = GetProperties( m_seqPropertyNames ); + + // Safe impossible cases. + // We need values from ALL configuration keys. + // Follow assignment use order of values in relation to our list of key names! + DBG_ASSERT( !(m_seqPropertyNames.getLength()!=seqValues.getLength()), + "SvtSlideSorterBarOptions_Impl::SvtSlideSorterBarOptions_Impl()\nI miss some values of configuration keys!\n" ); + + // Copy values from list in right order to our internal member. + for( sal_Int32 nProperty=0; nProperty<seqValues.getLength(); ++nProperty ) + { + if (!seqValues[nProperty].hasValue()) + continue; + switch( nProperty ) + { + case PROPERTYHANDLE_VISIBLE_IMPRESSVIEW : + { + if( !(seqValues[nProperty] >>= m_bVisibleImpressView) ) + OSL_FAIL("Wrong type of \"SlideSorterBar\\VisibleImpressView\"!" ); + break; + } + case PROPERTYHANDLE_VISIBLE_OUTLINEVIEW : + { + if( !(seqValues[nProperty] >>= m_bVisibleOutlineView) ) + OSL_FAIL("Wrong type of \"SlideSorterBar\\VisibleOutlineView\"!" ); + break; + } + case PROPERTYHANDLE_VISIBLE_NOTESVIEW : + { + if( !(seqValues[nProperty] >>= m_bVisibleNotesView) ) + OSL_FAIL("Wrong type of \"SlideSorterBar\\VisibleNotesView\"!" ); + break; + } + case PROPERTYHANDLE_VISIBLE_HANDOUTVIEW : + { + if( !(seqValues[nProperty] >>= m_bVisibleHandoutView) ) + OSL_FAIL("Wrong type of \"SlideSorterBar\\VisibleHandoutView\"!" ); + break; + } + case PROPERTYHANDLE_VISIBLE_SLIDESORTERVIEW : + { + if( !(seqValues[nProperty] >>= m_bVisibleSlideSorterView) ) + OSL_FAIL("Wrong type of \"SlideSorterBar\\VisibleSlideSorterView\"!" ); + break; + } + case PROPERTYHANDLE_VISIBLE_DRAWVIEW : + { + if( !(seqValues[nProperty] >>= m_bVisibleDrawView) ) + OSL_FAIL("Wrong type of \"SlideSorterBar\\VisibleDrawView\"!" ); + break; + } + } + } + + // Enable notification mechanism of our baseclass. + // We need it to get information about changes outside these class on our used configuration keys! + EnableNotification( m_seqPropertyNames ); +} + +SvtSlideSorterBarOptions_Impl::~SvtSlideSorterBarOptions_Impl() +{ + if (IsModified()) + Commit(); +} + +void SvtSlideSorterBarOptions_Impl::Load( const Sequence< OUString >& rPropertyNames ) +{ + const uno::Sequence< OUString> aInternalPropertyNames( GetPropertyNames()); + Sequence< Any > seqValues = GetProperties( rPropertyNames ); + + // Safe impossible cases. + // We need values from ALL configuration keys. + // Follow assignment use order of values in relation to our list of key names! + DBG_ASSERT( !(rPropertyNames.getLength()!=seqValues.getLength()), + "SvtSlideSorterBarOptions_Impl::SvtSlideSorterBarOptions_Impl()\nI miss some values of configuration keys!\n" ); + + // Copy values from list in right order to our internal member. + for( sal_Int32 nProperty=0; nProperty<seqValues.getLength(); ++nProperty ) + { + if (!seqValues[nProperty].hasValue()) + continue; + switch( comphelper::findValue(aInternalPropertyNames, rPropertyNames[nProperty]) ) + { + case PROPERTYHANDLE_VISIBLE_IMPRESSVIEW: + { + if( !(seqValues[nProperty] >>= m_bVisibleImpressView) ) + OSL_FAIL("Wrong type of \"SlideSorterBar\\VisibleImpressView\"!" ); + } + break; + case PROPERTYHANDLE_VISIBLE_OUTLINEVIEW : + { + if( !(seqValues[nProperty] >>= m_bVisibleOutlineView) ) + OSL_FAIL("Wrong type of \"SlideSorterBar\\VisibleOutlineView\"!" ); + } + break; + case PROPERTYHANDLE_VISIBLE_NOTESVIEW : + { + if( !(seqValues[nProperty] >>= m_bVisibleNotesView) ) + OSL_FAIL("Wrong type of \"SlideSorterBar\\VisibleNotesView\"!" ); + } + break; + case PROPERTYHANDLE_VISIBLE_HANDOUTVIEW : + { + if( !(seqValues[nProperty] >>= m_bVisibleHandoutView) ) + OSL_FAIL("Wrong type of \"SlideSorterBar\\VisibleHandoutView\"!" ); + } + break; + case PROPERTYHANDLE_VISIBLE_SLIDESORTERVIEW : + { + if( !(seqValues[nProperty] >>= m_bVisibleSlideSorterView) ) + OSL_FAIL("Wrong type of \"SlideSorterBar\\VisibleSlideSorterView\"!" ); + } + break; + + case PROPERTYHANDLE_VISIBLE_DRAWVIEW : + { + if( !(seqValues[nProperty] >>= m_bVisibleDrawView) ) + OSL_FAIL("Wrong type of \"SlideSorterBar\\VisibleDrawView\"!" ); + } + break; + } + } +} + +void SvtSlideSorterBarOptions_Impl::Notify( const Sequence< OUString >& rPropertyNames ) +{ + Load( rPropertyNames ); +} + +void SvtSlideSorterBarOptions_Impl::ImplCommit() +{ + // Get names of supported properties, create a list for values and copy current values to it. + sal_Int32 nCount = m_seqPropertyNames.getLength(); + Sequence< Any > seqValues ( nCount ); + for( sal_Int32 nProperty=0; nProperty<nCount; ++nProperty ) + { + switch( nProperty ) + { + case PROPERTYHANDLE_VISIBLE_IMPRESSVIEW: + { + seqValues[nProperty] <<= m_bVisibleImpressView; + break; + } + case PROPERTYHANDLE_VISIBLE_OUTLINEVIEW: + { + seqValues[nProperty] <<= m_bVisibleOutlineView; + break; + } + case PROPERTYHANDLE_VISIBLE_NOTESVIEW: + { + seqValues[nProperty] <<= m_bVisibleNotesView; + break; + } + case PROPERTYHANDLE_VISIBLE_HANDOUTVIEW: + { + seqValues[nProperty] <<= m_bVisibleHandoutView; + break; + } + case PROPERTYHANDLE_VISIBLE_SLIDESORTERVIEW: + { + seqValues[nProperty] <<= m_bVisibleSlideSorterView; + break; + } + case PROPERTYHANDLE_VISIBLE_DRAWVIEW: + { + seqValues[nProperty] <<= m_bVisibleDrawView; + break; + } + + } + } + // Set properties in configuration. + PutProperties( m_seqPropertyNames, seqValues ); +} + +Sequence< OUString > SvtSlideSorterBarOptions_Impl::GetPropertyNames() +{ + // Build list of configuration key names. + const OUString pProperties[] = + { + PROPERTYNAME_VISIBLE_IMPRESSVIEW, + PROPERTYNAME_VISIBLE_OUTLINEVIEW, + PROPERTYNAME_VISIBLE_NOTESVIEW, + PROPERTYNAME_VISIBLE_HANDOUTVIEW, + PROPERTYNAME_VISIBLE_SLIDESORTERVIEW, + PROPERTYNAME_VISIBLE_DRAWVIEW, + }; + + // Initialize return sequence with these list and run + return Sequence< OUString >( pProperties, SAL_N_ELEMENTS( pProperties ) ); +} + +void SvtSlideSorterBarOptions_Impl::SetVisibleViewImpl( bool& bVisibleView, bool bVisible ) +{ + if( bVisibleView != bVisible ) + { + bVisibleView = bVisible; + SetModified(); + } +} + +namespace { + std::weak_ptr<SvtSlideSorterBarOptions_Impl> g_pSlideSorterBarOptions; +} + +SvtSlideSorterBarOptions::SvtSlideSorterBarOptions() +{ + // Global access, must be guarded (multithreading!). + MutexGuard aGuard( GetInitMutex() ); + + m_pImpl = g_pSlideSorterBarOptions.lock(); + if( !m_pImpl ) + { + m_pImpl = std::make_shared<SvtSlideSorterBarOptions_Impl>(); + g_pSlideSorterBarOptions = m_pImpl; + } +} + +SvtSlideSorterBarOptions::~SvtSlideSorterBarOptions() +{ + // Global access, must be guarded (multithreading!) + MutexGuard aGuard( GetInitMutex() ); + + m_pImpl.reset(); +} + +bool SvtSlideSorterBarOptions::GetVisibleImpressView() const +{ + static const bool bRunningUnitTest = getenv("LO_TESTNAME"); + return m_pImpl->m_bVisibleImpressView && (!bRunningUnitTest || !comphelper::LibreOfficeKit::isActive()); +} + +void SvtSlideSorterBarOptions::SetVisibleImpressView(bool bVisible) +{ + m_pImpl->SetVisibleImpressView( bVisible ); +} + +bool SvtSlideSorterBarOptions::GetVisibleOutlineView() const +{ + return m_pImpl->m_bVisibleOutlineView; +} + +void SvtSlideSorterBarOptions::SetVisibleOutlineView(bool bVisible) +{ + m_pImpl->SetVisibleOutlineView( bVisible ); +} + +bool SvtSlideSorterBarOptions::GetVisibleNotesView() const +{ + return m_pImpl->m_bVisibleNotesView; +} + +void SvtSlideSorterBarOptions::SetVisibleNotesView(bool bVisible) +{ + m_pImpl->SetVisibleNotesView( bVisible ); +} + +bool SvtSlideSorterBarOptions::GetVisibleHandoutView() const +{ + return m_pImpl->m_bVisibleHandoutView; +} + +void SvtSlideSorterBarOptions::SetVisibleHandoutView(bool bVisible) +{ + m_pImpl->SetVisibleHandoutView( bVisible ); +} + +bool SvtSlideSorterBarOptions::GetVisibleSlideSorterView() const +{ + return m_pImpl->m_bVisibleSlideSorterView && !comphelper::LibreOfficeKit::isActive(); +} + +void SvtSlideSorterBarOptions::SetVisibleSlideSorterView(bool bVisible) +{ + m_pImpl->SetVisibleSlideSorterView( bVisible ); +} + +bool SvtSlideSorterBarOptions::GetVisibleDrawView() const +{ + return m_pImpl->m_bVisibleDrawView; +} + +void SvtSlideSorterBarOptions::SetVisibleDrawView(bool bVisible) +{ + m_pImpl->SetVisibleDrawView( bVisible ); +} + +namespace +{ + class theSvtSlideSorterBarOptionsMutex : + public rtl::Static< osl::Mutex, theSvtSlideSorterBarOptionsMutex > {}; +} + +Mutex & SvtSlideSorterBarOptions::GetInitMutex() +{ + return theSvtSlideSorterBarOptionsMutex::get(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/config/test/test.cxx b/svtools/source/config/test/test.cxx new file mode 100644 index 000000000..c84d2ca9f --- /dev/null +++ b/svtools/source/config/test/test.cxx @@ -0,0 +1,215 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + + +// switches +// use it to enable test scenarios + + +#define TEST_DYNAMICMENUOPTIONS + +#include <unotools/dynamicmenuoptions.hxx> + +#include <cppuhelper/bootstrap.hxx> +#include <com/sun/star/lang/XMultiServiceFactory.hpp> +#include <com/sun/star/lang/XInitialization.hpp> +#include <com/sun/star/registry/XSimpleRegistry.hpp> + +#include <cppuhelper/servicefactory.hxx> +#include <comphelper/processfactory.hxx> +#include <com/sun/star/uno/Reference.h> +#include <com/sun/star/uno/Sequence.h> + +#include <rtl/ustring> +#include <rtl/ustrbuf.hxx> +#include <osl/diagnose.h> +#include <sal/log.hxx> + +#include <vcl/event.hxx> +#include <vcl/svapp.hxx> + +using namespace ::osl ; +using namespace ::comphelper ; +using namespace ::com::sun::star::uno ; +using namespace ::com::sun::star::lang ; +using namespace ::com::sun::star::beans ; +using namespace ::com::sun::star::registry ; + +class TestApplication : public Application +{ + + // interface + + public: + void Main(); + + + // test methods + + private: + void impl_testDynamicMenuOptions(); + + + // helper methods + + private: + static Reference< XMultiServiceFactory > getUNOServiceManager(); + + + // member + + private: + +}; // class TestApplication + + +// global variables + + +TestApplication aTestApplication ; + + +// main + + +void TestApplication::Main() +{ + /**-*********************************************************************************************************** + initialize program + **************************************************************************************************************/ + + // Init global servicemanager and set it for external services. + ::comphelper::setProcessServiceFactory( TestApplication::getUNOServiceManager() ); + // Control success of operation. + OSL_ENSURE( !(::comphelper::getProcessServiceFactory()!=TestApplication::getUNOServiceManager()), "TestApplication::Main() Global servicemanager not right initialized." ); + + /**-*********************************************************************************************************** + test area + **************************************************************************************************************/ + + #ifdef TEST_DYNAMICMENUOPTIONS + impl_testDynamicMenuOptions(); + #endif + +// Execute(); + OSL_FAIL( "Test was successful!" ); +} + + +// test configuration of dynamic menus "New" and "Wizard" + +void TestApplication::impl_testDynamicMenuOptions() +{ + SvtDynamicMenuOptions aCFG; + + // Test: + // read menus + // if( menus == empty ) + // { + // fill it with samples + // read it again + // } + // output content + + Sequence< Sequence< PropertyValue > > lNewMenu = aCFG.GetMenu( EDynamicMenuType::NewMenu ); + Sequence< Sequence< PropertyValue > > lWizardMenu = aCFG.GetMenu( EDynamicMenuType::WizardMenu ); + + if( lNewMenu.getLength() < 1 ) + { + aCFG.AppendItem( EDynamicMenuType::NewMenu, "private:factory/swriter", "new writer", "icon_writer", "_blank"); + aCFG.AppendItem( EDynamicMenuType::NewMenu, "private:factory/scalc", "new calc", "icon_calc", "_blank"); + aCFG.AppendItem( EDynamicMenuType::NewMenu, "private:factory/sdraw", "new draw", "icon_draw", "_blank"); + + lNewMenu = aCFG.GetMenu( EDynamicMenuType::NewMenu ); + } + + if( lWizardMenu.getLength() < 1 ) + { + aCFG.AppendItem( EDynamicMenuType::WizardMenu, "file://a", "system file", "icon_file", "_self"); + aCFG.AppendItem( EDynamicMenuType::WizardMenu, "ftp://b", "ftp host", "icon_ftp", "_self"); + aCFG.AppendItem( EDynamicMenuType::WizardMenu, "http://c", "www", "icon_www", "_self"); + + lWizardMenu = aCFG.GetMenu( EDynamicMenuType::WizardMenu ); + } + + sal_uInt32 nItemCount ; + sal_uInt32 nItem ; + sal_uInt32 nPropertyCount; + sal_uInt32 nProperty ; + OUString sPropertyValue; + OUStringBuffer sOut( 5000 ) ; + + nItemCount = lNewMenu.getLength(); + for( nItem=0; nItem<nItemCount; ++nItem ) + { + nPropertyCount = lNewMenu[nItem].getLength(); + for( nProperty=0; nProperty<nPropertyCount; ++nProperty ) + { + lNewMenu[nItem][nProperty].Value >>= sPropertyValue; + + sOut.appendAscii ( "New/" ); + sOut.append ( (sal_Int32)nItem ); + sOut.appendAscii ( "/" ); + sOut.append ( lNewMenu[nItem][nProperty].Name ); + sOut.appendAscii ( " = " ); + sOut.append ( sPropertyValue ); + sOut.appendAscii ( "\n" ); + } + } + + sOut.appendAscii("\n--------------------------------------\n"); + + nItemCount = lWizardMenu.getLength(); + for( nItem=0; nItem<nItemCount; ++nItem ) + { + nPropertyCount = lNewMenu[nItem].getLength(); + for( nProperty=0; nProperty<nPropertyCount; ++nProperty ) + { + lWizardMenu[nItem][nProperty].Value >>= sPropertyValue; + + sOut.appendAscii ( "Wizard/" ); + sOut.append ( (sal_Int32)nItem ); + sOut.appendAscii ( "/" ); + sOut.append ( lNewMenu[nItem][nProperty].Name ); + sOut.appendAscii ( " = " ); + sOut.append ( sPropertyValue ); + sOut.appendAscii ( "\n" ); + } + } + + SAL_WARN( "svtools", sOut ); +} + + +// create new uno servicemanager by using normal applicat.rdb and user.rdb of an office installation! +// Don't use this application at the same time like the office! + +Reference< XMultiServiceFactory > TestApplication::getUNOServiceManager() +{ + static Reference< XMultiServiceFactory > smgr; + if( ! smgr.is() ) + { + Reference< XComponentContext > rCtx = + cppu::defaultBootstrap_InitialComponentContext(); + smgr.set( rCtx->getServiceManager() , UNO_QUERY ); + } + return smgr; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/contnr/DocumentInfoPreview.cxx b/svtools/source/contnr/DocumentInfoPreview.cxx new file mode 100644 index 000000000..93b8b27e5 --- /dev/null +++ b/svtools/source/contnr/DocumentInfoPreview.cxx @@ -0,0 +1,159 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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/config.h> + +#include <com/sun/star/beans/XPropertySet.hpp> +#include <com/sun/star/document/XDocumentProperties.hpp> +#include <com/sun/star/script/CannotConvertException.hpp> +#include <com/sun/star/script/Converter.hpp> +#include <com/sun/star/script/XTypeConverter.hpp> +#include <comphelper/processfactory.hxx> +#include <comphelper/string.hxx> +#include <rtl/ustring.hxx> +#include <svtools/DocumentInfoPreview.hxx> +#include <svmedit2.hxx> +#include <vcl/txtattr.hxx> +#include <vcl/settings.hxx> +#include <vcl/svapp.hxx> +#include <tools/datetime.hxx> +#include <tools/diagnose_ex.h> +#include <unotools/localedatawrapper.hxx> + +#include <templwin.hrc> +#include "templwin.hxx" + +namespace svtools { + +ODocumentInfoPreview::ODocumentInfoPreview(vcl::Window * pParent, WinBits nBits) + : Window(pParent, WB_DIALOGCONTROL) + , m_pEditWin( VclPtr<ExtMultiLineEdit>::Create(this, nBits) ) +{ + m_pEditWin->SetLeftMargin(10); + m_pEditWin->Show(); + m_pEditWin->EnableCursor(false); +} + +ODocumentInfoPreview::~ODocumentInfoPreview() +{ + disposeOnce(); +} + +void ODocumentInfoPreview::dispose() +{ + m_pEditWin.disposeAndClear(); + Window::dispose(); +} + +void ODocumentInfoPreview::Resize() { + m_pEditWin->SetPosSizePixel(Point(0, 0), GetOutputSize()); +} + +void ODocumentInfoPreview::clear() { + m_pEditWin->SetText(OUString()); +} + +void ODocumentInfoPreview::fill( + css::uno::Reference< css::document::XDocumentProperties > const & xDocProps) +{ + assert(xDocProps.is()); + + m_pEditWin->SetAutoScroll(false); + + insertNonempty(DI_TITLE, xDocProps->getTitle()); + insertNonempty(DI_FROM, xDocProps->getAuthor()); + insertDateTime(DI_DATE, xDocProps->getCreationDate()); + insertNonempty(DI_MODIFIEDBY, xDocProps->getModifiedBy()); + insertDateTime(DI_MODIFIEDDATE, xDocProps->getModificationDate()); + insertNonempty(DI_PRINTBY, xDocProps->getPrintedBy()); + insertDateTime(DI_PRINTDATE, xDocProps->getPrintDate()); + insertNonempty(DI_THEME, xDocProps->getSubject()); + insertNonempty( + DI_KEYWORDS, + comphelper::string::convertCommaSeparated(xDocProps->getKeywords())); + insertNonempty(DI_DESCRIPTION, xDocProps->getDescription()); + + // User-defined (custom) properties: + css::uno::Reference< css::beans::XPropertySet > user( + xDocProps->getUserDefinedProperties(), css::uno::UNO_QUERY_THROW); + css::uno::Reference< css::beans::XPropertySetInfo > info( + user->getPropertySetInfo()); + const css::uno::Sequence< css::beans::Property > props(info->getProperties()); + for (const auto& rProp : props) { + OUString name(rProp.Name); + css::uno::Any aAny(user->getPropertyValue(name)); + css::uno::Reference< css::script::XTypeConverter > conv( + css::script::Converter::create( + comphelper::getProcessComponentContext())); + OUString value; + try { + value = conv->convertToSimpleType(aAny, css::uno::TypeClass_STRING). + get< OUString >(); + } catch (css::script::CannotConvertException &) { + TOOLS_INFO_EXCEPTION("svtools.contnr", "ignored"); + } + if (!value.isEmpty()) { + insertEntry(name, value); + } + } + + m_pEditWin->SetSelection(Selection(0, 0)); + m_pEditWin->SetAutoScroll(true); +} + +void ODocumentInfoPreview::insertEntry( + OUString const & title, OUString const & value) +{ + if (!m_pEditWin->GetText().isEmpty()) { + m_pEditWin->InsertText("\n\n"); + } + OUString caption(title + ":\n"); + m_pEditWin->InsertText(caption); + m_pEditWin->SetAttrib( + TextAttribFontWeight(WEIGHT_BOLD), m_pEditWin->GetParagraphCount() - 2, + 0, caption.getLength() - 1); + m_pEditWin->InsertText(value); +} + +void ODocumentInfoPreview::insertNonempty(long id, OUString const & value) +{ + if (!value.isEmpty()) { + insertEntry(SvtDocInfoTable_Impl::GetString(id), value); + } +} + +void ODocumentInfoPreview::insertDateTime( + long id, css::util::DateTime const & value) +{ + DateTime aToolsDT( + Date(value.Day, value.Month, value.Year), + tools::Time( + value.Hours, value.Minutes, value.Seconds, value.NanoSeconds)); + if (aToolsDT.IsValidAndGregorian()) { + const LocaleDataWrapper& rLocaleWrapper( Application::GetSettings().GetLocaleDataWrapper() ); + OUStringBuffer buf(rLocaleWrapper.getDate(aToolsDT)); + buf.append(", "); + buf.append(rLocaleWrapper.getTime(aToolsDT)); + insertEntry(SvtDocInfoTable_Impl::GetString(id), buf.makeStringAndClear()); + } +} + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/contnr/querydelete.cxx b/svtools/source/contnr/querydelete.cxx new file mode 100644 index 000000000..334d75eac --- /dev/null +++ b/svtools/source/contnr/querydelete.cxx @@ -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 . + */ + +#include <svtools/querydelete.hxx> + +namespace svtools +{ +QueryDeleteDlg_Impl::QueryDeleteDlg_Impl(weld::Widget* pParent, const OUString& rName) + : MessageDialogController(pParent, "svt/ui/querydeletedialog.ui", "QueryDeleteDialog") + , m_xAllButton(m_xBuilder->weld_button("all")) +{ + // display specified texts + m_xDialog->set_secondary_text(m_xDialog->get_secondary_text().replaceFirst("%s", rName)); +} + +QueryDeleteDlg_Impl::~QueryDeleteDlg_Impl() {} +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/contnr/templwin.cxx b/svtools/source/contnr/templwin.cxx new file mode 100644 index 000000000..acd337e51 --- /dev/null +++ b/svtools/source/contnr/templwin.cxx @@ -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 . + */ + +#include <svtools/svtresid.hxx> +#include "templwin.hxx" +#include <templwin.hrc> + +namespace SvtDocInfoTable_Impl +{ + OUString GetString(int nId) + { + for (size_t i = 0; i < SAL_N_ELEMENTS(STRARY_SVT_DOCINFO); ++i) + { + if (STRARY_SVT_DOCINFO[i].second == nId) + return SvtResId(STRARY_SVT_DOCINFO[i].first); + } + + return OUString(); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/contnr/templwin.hxx b/svtools/source/contnr/templwin.hxx new file mode 100644 index 000000000..1a3f435af --- /dev/null +++ b/svtools/source/contnr/templwin.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 . + */ +#pragma once + +#include <rtl/ustring.hxx> + +namespace SvtDocInfoTable_Impl +{ + OUString GetString(int nId); +}; + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/control/accessibleruler.cxx b/svtools/source/control/accessibleruler.cxx new file mode 100644 index 000000000..cfd54364e --- /dev/null +++ b/svtools/source/control/accessibleruler.cxx @@ -0,0 +1,362 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <com/sun/star/accessibility/AccessibleRole.hpp> +#include <com/sun/star/accessibility/IllegalAccessibleComponentStateException.hpp> +#include <unotools/accessiblestatesethelper.hxx> +#include <com/sun/star/accessibility/AccessibleStateType.hpp> +#include <comphelper/accessibleeventnotifier.hxx> +#include <cppuhelper/supportsservice.hxx> +#include <toolkit/helper/convert.hxx> +#include <vcl/svapp.hxx> +#include <osl/mutex.hxx> +#include <tools/gen.hxx> + +#include <svtools/ruler.hxx> +#include "accessibleruler.hxx" + +using namespace ::cppu; +using namespace ::osl; +using namespace ::com::sun::star; +using namespace ::com::sun::star::uno; +using namespace ::com::sun::star::accessibility; + + +//===== internal ============================================================ + +SvtRulerAccessible::SvtRulerAccessible( + const uno::Reference< XAccessible >& rxParent, Ruler& rRepr, const OUString& rName ) : + + SvtRulerAccessible_Base( m_aMutex ), + msName( rName ), + mxParent( rxParent ), + mpRepr( &rRepr ), + mnClientId( 0 ) +{ +} + +SvtRulerAccessible::~SvtRulerAccessible() +{ + + if( IsAlive() ) + { + osl_atomic_increment( &m_refCount ); + dispose(); // set mpRepr = NULL & release all children + } +} + +//===== XAccessible ========================================================= + +uno::Reference< XAccessibleContext > SAL_CALL SvtRulerAccessible::getAccessibleContext() +{ + return this; +} + +//===== XAccessibleComponent ================================================ + +sal_Bool SAL_CALL SvtRulerAccessible::containsPoint( const awt::Point& rPoint ) +{ + // no guard -> done in getBounds() +// return GetBoundingBox().IsInside( VCLPoint( rPoint ) ); + return tools::Rectangle( Point( 0, 0 ), GetBoundingBox().GetSize() ).IsInside( VCLPoint( rPoint ) ); +} + +uno::Reference< XAccessible > SAL_CALL SvtRulerAccessible::getAccessibleAtPoint( const awt::Point& ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + + ThrowExceptionIfNotAlive(); + + uno::Reference< XAccessible > xRet; + + + return xRet; +} + +awt::Rectangle SAL_CALL SvtRulerAccessible::getBounds() +{ + // no guard -> done in GetBoundingBox() + return AWTRectangle( GetBoundingBox() ); +} + +awt::Point SAL_CALL SvtRulerAccessible::getLocation() +{ + // no guard -> done in GetBoundingBox() + return AWTPoint( GetBoundingBox().TopLeft() ); +} + +awt::Point SAL_CALL SvtRulerAccessible::getLocationOnScreen() +{ + // no guard -> done in GetBoundingBoxOnScreen() + return AWTPoint( GetBoundingBoxOnScreen().TopLeft() ); +} + +awt::Size SAL_CALL SvtRulerAccessible::getSize() +{ + // no guard -> done in GetBoundingBox() + return AWTSize( GetBoundingBox().GetSize() ); +} + +bool SvtRulerAccessible::isVisible() +{ + ::osl::MutexGuard aGuard( m_aMutex ); + + ThrowExceptionIfNotAlive(); + + return mpRepr->IsVisible(); +} + +//===== XAccessibleContext ================================================== +sal_Int32 SAL_CALL SvtRulerAccessible::getAccessibleChildCount() +{ + ::osl::MutexGuard aGuard( m_aMutex ); + + ThrowExceptionIfNotAlive(); + + return 0; +} + +uno::Reference< XAccessible > SAL_CALL SvtRulerAccessible::getAccessibleChild( sal_Int32 ) +{ + uno::Reference< XAccessible > xChild ; + + return xChild; +} + +uno::Reference< XAccessible > SAL_CALL SvtRulerAccessible::getAccessibleParent() +{ + return mxParent; +} + +sal_Int32 SAL_CALL SvtRulerAccessible::getAccessibleIndexInParent() +{ + ::osl::MutexGuard aGuard( m_aMutex ); + // Use a simple but slow solution for now. Optimize later. + + // Iterate over all the parent's children and search for this object. + if( mxParent.is() ) + { + uno::Reference< XAccessibleContext > xParentContext( mxParent->getAccessibleContext() ); + if( xParentContext.is() ) + { + sal_Int32 nChildCount = xParentContext->getAccessibleChildCount(); + for( sal_Int32 i = 0 ; i < nChildCount ; ++i ) + { + uno::Reference< XAccessible > xChild( xParentContext->getAccessibleChild( i ) ); + if( xChild.get() == static_cast<XAccessible*>(this) ) + return i; + } + } + } + + // Return -1 to indicate that this object's parent does not know about the + // object. + return -1; +} + +sal_Int16 SAL_CALL SvtRulerAccessible::getAccessibleRole() +{ + return AccessibleRole::RULER; +} + +OUString SAL_CALL SvtRulerAccessible::getAccessibleDescription() +{ + return OUString(); +} + +OUString SAL_CALL SvtRulerAccessible::getAccessibleName() +{ + ::osl::MutexGuard aGuard( m_aMutex ); + return msName; +} + +/** Return empty uno::Reference to indicate that the relation set is not + supported. +*/ +uno::Reference< XAccessibleRelationSet > SAL_CALL SvtRulerAccessible::getAccessibleRelationSet() +{ + return uno::Reference< XAccessibleRelationSet >(); +} + + +uno::Reference< XAccessibleStateSet > SAL_CALL SvtRulerAccessible::getAccessibleStateSet() +{ + ::osl::MutexGuard aGuard( m_aMutex ); + utl::AccessibleStateSetHelper* pStateSetHelper = new utl::AccessibleStateSetHelper; + + if( IsAlive() ) + { + pStateSetHelper->AddState( AccessibleStateType::ENABLED ); + + pStateSetHelper->AddState( AccessibleStateType::SHOWING ); + + if( isVisible() ) + pStateSetHelper->AddState( AccessibleStateType::VISIBLE ); + + if ( mpRepr->GetStyle() & WB_HORZ ) + pStateSetHelper->AddState( AccessibleStateType::HORIZONTAL ); + else + pStateSetHelper->AddState( AccessibleStateType::VERTICAL ); + + if(pStateSetHelper->contains(AccessibleStateType::FOCUSABLE)) + { + pStateSetHelper->RemoveState( AccessibleStateType::FOCUSABLE ); + } + + } + + + return pStateSetHelper; +} + +lang::Locale SAL_CALL SvtRulerAccessible::getLocale() +{ + ::osl::MutexGuard aGuard( m_aMutex ); + if( mxParent.is() ) + { + uno::Reference< XAccessibleContext > xParentContext( mxParent->getAccessibleContext() ); + if( xParentContext.is() ) + return xParentContext->getLocale(); + } + + // No parent. Therefore throw exception to indicate this cluelessness. + throw IllegalAccessibleComponentStateException(); +} + +void SAL_CALL SvtRulerAccessible::addAccessibleEventListener( const uno::Reference< XAccessibleEventListener >& xListener ) +{ + if (xListener.is()) + { + ::osl::MutexGuard aGuard( m_aMutex ); + if (!mnClientId) + mnClientId = comphelper::AccessibleEventNotifier::registerClient( ); + comphelper::AccessibleEventNotifier::addEventListener( mnClientId, xListener ); + } +} + +void SAL_CALL SvtRulerAccessible::removeAccessibleEventListener( const uno::Reference< XAccessibleEventListener >& xListener ) +{ + if (!(xListener.is() && mnClientId)) + return; + + ::osl::MutexGuard aGuard( m_aMutex ); + + sal_Int32 nListenerCount = comphelper::AccessibleEventNotifier::removeEventListener( mnClientId, xListener ); + if ( !nListenerCount ) + { + // no listeners anymore + // -> revoke ourself. This may lead to the notifier thread dying (if we were the last client), + // and at least to us not firing any events anymore, in case somebody calls + // NotifyAccessibleEvent, again + comphelper::AccessibleEventNotifier::revokeClient( mnClientId ); + mnClientId = 0; + } +} + +void SAL_CALL SvtRulerAccessible::grabFocus() +{ + SolarMutexGuard aSolarGuard; + ::osl::MutexGuard aGuard( m_aMutex ); + + ThrowExceptionIfNotAlive(); + + mpRepr->GrabFocus(); +} + +sal_Int32 SvtRulerAccessible::getForeground( ) +{ + SolarMutexGuard aSolarGuard; + ::osl::MutexGuard aGuard( m_aMutex ); + ThrowExceptionIfNotAlive(); + + return sal_Int32(mpRepr->GetControlForeground()); +} +sal_Int32 SvtRulerAccessible::getBackground( ) +{ + SolarMutexGuard aSolarGuard; + ::osl::MutexGuard aGuard( m_aMutex ); + ThrowExceptionIfNotAlive(); + + return sal_Int32(mpRepr->GetControlBackground()); +} + +// XServiceInfo +OUString SAL_CALL SvtRulerAccessible::getImplementationName() +{ + return "com.sun.star.comp.ui.SvtRulerAccessible"; +} + +sal_Bool SAL_CALL SvtRulerAccessible::supportsService( const OUString& sServiceName ) +{ + return cppu::supportsService( this, sServiceName ); +} + +Sequence< OUString > SAL_CALL SvtRulerAccessible::getSupportedServiceNames() +{ + return { "com.sun.star.accessibility.AccessibleContext" }; +} + +//===== XTypeProvider ======================================================= +Sequence< sal_Int8 > SAL_CALL SvtRulerAccessible::getImplementationId() +{ + return css::uno::Sequence<sal_Int8>(); +} + +void SAL_CALL SvtRulerAccessible::disposing() +{ + if( rBHelper.bDisposed ) + return; + + ::osl::MutexGuard aGuard( m_aMutex ); + mpRepr = nullptr; // object dies with representation + + // Send a disposing to all listeners. + if ( mnClientId ) + { + comphelper::AccessibleEventNotifier::revokeClientNotifyDisposing( mnClientId, *this ); + mnClientId = 0; + } + mxParent.clear(); +} + +tools::Rectangle SvtRulerAccessible::GetBoundingBoxOnScreen() +{ + SolarMutexGuard aSolarGuard; + ::osl::MutexGuard aGuard( m_aMutex ); + + ThrowExceptionIfNotAlive(); + return tools::Rectangle( mpRepr->GetParent()->OutputToAbsoluteScreenPixel( mpRepr->GetPosPixel() ), mpRepr->GetSizePixel() ); +} + +tools::Rectangle SvtRulerAccessible::GetBoundingBox() +{ + SolarMutexGuard aSolarGuard; + ::osl::MutexGuard aGuard( m_aMutex ); + + ThrowExceptionIfNotAlive(); + + return tools::Rectangle( mpRepr->GetPosPixel(), mpRepr->GetSizePixel() ); +} + +void SvtRulerAccessible::ThrowExceptionIfNotAlive() +{ + if( rBHelper.bDisposed || rBHelper.bInDispose ) + throw lang::DisposedException(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/control/accessibleruler.hxx b/svtools/source/control/accessibleruler.hxx new file mode 100644 index 000000000..bd7d46123 --- /dev/null +++ b/svtools/source/control/accessibleruler.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 . + */ +#ifndef INCLUDED_SVTOOLS_ACCESSIBLERULER_HXX +#define INCLUDED_SVTOOLS_ACCESSIBLERULER_HXX + +#include <com/sun/star/accessibility/XAccessible.hpp> +#include <com/sun/star/accessibility/XAccessibleComponent.hpp> +#include <com/sun/star/accessibility/XAccessibleContext.hpp> +#include <com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp> + +#include <com/sun/star/uno/Reference.hxx> +#include <com/sun/star/lang/XServiceInfo.hpp> +#include <cppuhelper/interfacecontainer.h> +#include <cppuhelper/compbase5.hxx> +#include <cppuhelper/basemutex.hxx> +#include <vcl/vclptr.hxx> + +namespace tools { class Rectangle; } +class Ruler; + + +typedef ::cppu::WeakAggComponentImplHelper5< + css::accessibility::XAccessible, + css::accessibility::XAccessibleComponent, + css::accessibility::XAccessibleContext, + css::accessibility::XAccessibleEventBroadcaster, + css::lang::XServiceInfo > + SvtRulerAccessible_Base; + +class SvtRulerAccessible final : public ::cppu::BaseMutex, public SvtRulerAccessible_Base +{ +public: + //===== internal ======================================================== + SvtRulerAccessible( + const css::uno::Reference< css::accessibility::XAccessible>& rxParent, Ruler& rRepresentation, const OUString& rName ); + + /// @throws css::uno::RuntimeException + bool + isVisible(); + + //===== XAccessible ===================================================== + + virtual css::uno::Reference< css::accessibility::XAccessibleContext> SAL_CALL + getAccessibleContext() override; + + //===== XAccessibleComponent ============================================ + + virtual sal_Bool SAL_CALL + containsPoint( const css::awt::Point& rPoint ) override; + + virtual css::uno::Reference< css::accessibility::XAccessible > SAL_CALL + getAccessibleAtPoint( const css::awt::Point& rPoint ) 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; + + //===== XAccessibleContext ============================================== + + virtual sal_Int32 SAL_CALL + getAccessibleChildCount() override; + + virtual css::uno::Reference< css::accessibility::XAccessible> SAL_CALL + getAccessibleChild( sal_Int32 nIndex ) 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; + + //===== 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; + + //===== XTypeProvider =================================================== + + virtual css::uno::Sequence<sal_Int8> SAL_CALL + getImplementationId() override; + +private: + + virtual ~SvtRulerAccessible() override; + + virtual void SAL_CALL disposing() override; + + /// @returns true if it's disposed or in disposing + inline bool IsAlive() const; + + /// @throws DisposedException if it's not alive + void ThrowExceptionIfNotAlive(); + + /// @Return the object's current bounding box relative to the desktop. + /// + /// @throws css::uno::RuntimeException + tools::Rectangle GetBoundingBoxOnScreen(); + + /// @Return the object's current bounding box relative to the parent object. + /// + /// @throws css::uno::RuntimeException + tools::Rectangle GetBoundingBox(); + + /// Name of this object. + OUString msName; + + /// Reference to the parent object. + css::uno::Reference< css::accessibility::XAccessible > + mxParent; + + /// pointer to internal representation + VclPtr<Ruler> mpRepr; + + /// client id in the AccessibleEventNotifier queue + sal_uInt32 mnClientId; +}; + +inline bool SvtRulerAccessible::IsAlive() const +{ + return !rBHelper.bDisposed && !rBHelper.bInDispose; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/control/asynclink.cxx b/svtools/source/control/asynclink.cxx new file mode 100644 index 000000000..31a7b28e7 --- /dev/null +++ b/svtools/source/control/asynclink.cxx @@ -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 . + */ + + +#include <svtools/asynclink.hxx> +#include <osl/mutex.hxx> +#include <sal/log.hxx> +#include <tools/debug.hxx> +#include <vcl/timer.hxx> +#include <vcl/idle.hxx> +#include <vcl/svapp.hxx> + + +namespace svtools { + +void AsynchronLink::CreateMutex() +{ + if( !_pMutex ) _pMutex.reset( new osl::Mutex ); +} + +void AsynchronLink::Call( void* pObj, bool bAllowDoubles ) +{ + SAL_INFO_IF( !_bInCall, "svtools", "Recursives Call. Eher ueber Timer. TLX Fragen" ); // Do NOT translate. This is a valuable historical artefact. + if( _aLink.IsSet() ) + { + _pArg = pObj; + DBG_ASSERT( bAllowDoubles || !_nEventId, "Already made a call" ); + ClearPendingCall(); + if( _pMutex ) _pMutex->acquire(); + _nEventId = Application::PostUserEvent( LINK( this, AsynchronLink, HandleCall_PostUserEvent) ); + if( _pMutex ) _pMutex->release(); + } +} + +AsynchronLink::~AsynchronLink() +{ + if( _nEventId ) + { + Application::RemoveUserEvent( _nEventId ); + } + if( _pDeleted ) *_pDeleted = true; + _pMutex.reset(); +} + +IMPL_LINK_NOARG( AsynchronLink, HandleCall_Idle, Timer*, void ) +{ + if( _pMutex ) _pMutex->acquire(); + _nEventId = nullptr; + if( _pMutex ) _pMutex->release(); + Call_Impl( _pArg ); +} + +IMPL_LINK_NOARG( AsynchronLink, HandleCall_PostUserEvent, void*, void ) +{ + HandleCall_Idle(nullptr); +} + +void AsynchronLink::ClearPendingCall() +{ + if( _pMutex ) _pMutex->acquire(); + if( _nEventId ) + { + Application::RemoveUserEvent( _nEventId ); + _nEventId = nullptr; + } + if( _pMutex ) _pMutex->release(); +} + +void AsynchronLink::Call_Impl( void* pArg ) +{ + _bInCall = true; + bool bDeleted = false; + _pDeleted = &bDeleted; + _aLink.Call( pArg ); + if( !bDeleted ) + { + _bInCall = false; + _pDeleted = nullptr; + } +} + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/control/calendar.cxx b/svtools/source/control/calendar.cxx new file mode 100644 index 000000000..d1b7f5d11 --- /dev/null +++ b/svtools/source/control/calendar.cxx @@ -0,0 +1,346 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <vcl/floatwin.hxx> +#include <vcl/button.hxx> +#include <vcl/fixed.hxx> +#include <vcl/event.hxx> + +#include <svtools/strings.hrc> +#include <svtools/svtresid.hxx> +#include <svtools/calendar.hxx> + +#define CALFIELD_EXTRA_BUTTON_WIDTH 14 +#define CALFIELD_EXTRA_BUTTON_HEIGHT 8 +#define CALFIELD_SEP_X 6 +#define CALFIELD_BORDERLINE_X 5 +#define CALFIELD_BORDER_YTOP 4 +#define CALFIELD_BORDER_Y 5 + +class ImplCFieldFloatWin : public FloatingWindow +{ +private: + VclPtr<Calendar> mpCalendar; + VclPtr<PushButton> mpTodayBtn; + VclPtr<PushButton> mpNoneBtn; + VclPtr<FixedLine> mpFixedLine; + +public: + explicit ImplCFieldFloatWin( vcl::Window* pParent ); + virtual ~ImplCFieldFloatWin() override; + virtual void dispose() override; + + void SetCalendar( Calendar* pCalendar ) + { mpCalendar = pCalendar; } + + PushButton* EnableTodayBtn( bool bEnable ); + PushButton* EnableNoneBtn( bool bEnable ); + void ArrangeButtons(); + + virtual bool EventNotify( NotifyEvent& rNEvt ) override; +}; + +ImplCFieldFloatWin::ImplCFieldFloatWin( vcl::Window* pParent ) : + FloatingWindow( pParent, WB_BORDER | WB_SYSTEMWINDOW | WB_NOSHADOW ), + mpCalendar(nullptr), mpTodayBtn(nullptr), mpNoneBtn(nullptr), mpFixedLine(nullptr) +{ +} + +ImplCFieldFloatWin::~ImplCFieldFloatWin() +{ + disposeOnce(); +} + +void ImplCFieldFloatWin::dispose() +{ + mpTodayBtn.disposeAndClear(); + mpNoneBtn.disposeAndClear(); + mpFixedLine.disposeAndClear(); + mpCalendar.clear(); + FloatingWindow::dispose(); +} + +PushButton* ImplCFieldFloatWin::EnableTodayBtn( bool bEnable ) +{ + if ( bEnable ) + { + if ( !mpTodayBtn ) + { + mpTodayBtn = VclPtr<PushButton>::Create( this, WB_NOPOINTERFOCUS ); + OUString aTodayText(SvtResId(STR_SVT_CALENDAR_TODAY)); + mpTodayBtn->SetText( aTodayText ); + Size aSize; + aSize.setWidth( mpTodayBtn->GetCtrlTextWidth( mpTodayBtn->GetText() ) ); + aSize.setHeight( mpTodayBtn->GetTextHeight() ); + aSize.AdjustWidth(CALFIELD_EXTRA_BUTTON_WIDTH ); + aSize.AdjustHeight(CALFIELD_EXTRA_BUTTON_HEIGHT ); + mpTodayBtn->SetSizePixel( aSize ); + mpTodayBtn->Show(); + } + } + else + { + mpTodayBtn.disposeAndClear(); + } + + return mpTodayBtn; +} + +PushButton* ImplCFieldFloatWin::EnableNoneBtn( bool bEnable ) +{ + if ( bEnable ) + { + if ( !mpNoneBtn ) + { + mpNoneBtn = VclPtr<PushButton>::Create( this, WB_NOPOINTERFOCUS ); + OUString aNoneText(SvtResId(STR_SVT_CALENDAR_NONE)); + mpNoneBtn->SetText( aNoneText ); + Size aSize; + aSize.setWidth( mpNoneBtn->GetCtrlTextWidth( mpNoneBtn->GetText() ) ); + aSize.setHeight( mpNoneBtn->GetTextHeight() ); + aSize.AdjustWidth(CALFIELD_EXTRA_BUTTON_WIDTH ); + aSize.AdjustHeight(CALFIELD_EXTRA_BUTTON_HEIGHT ); + mpNoneBtn->SetSizePixel( aSize ); + mpNoneBtn->Show(); + } + } + else + { + mpNoneBtn.disposeAndClear(); + } + + return mpNoneBtn; +} + +void ImplCFieldFloatWin::ArrangeButtons() +{ + long nBtnHeight = 0; + long nBtnWidth = 0; + Size aOutSize = GetOutputSizePixel(); + if ( mpTodayBtn && mpNoneBtn ) + { + Size aTodayBtnSize = mpTodayBtn->GetSizePixel(); + Size aNoneBtnSize = mpNoneBtn->GetSizePixel(); + if ( aTodayBtnSize.Width() < aNoneBtnSize.Width() ) + aTodayBtnSize.setWidth( aNoneBtnSize.Width() ); + else + aNoneBtnSize.setWidth( aTodayBtnSize.Width() ); + if ( aTodayBtnSize.Height() < aNoneBtnSize.Height() ) + aTodayBtnSize.setHeight( aNoneBtnSize.Height() ); + else + aNoneBtnSize.setHeight( aTodayBtnSize.Height() ); + + nBtnWidth = aTodayBtnSize.Width() + aNoneBtnSize.Width() + CALFIELD_SEP_X; + nBtnHeight = aTodayBtnSize.Height(); + long nX = (aOutSize.Width()-nBtnWidth)/2; + long nY = aOutSize.Height()+CALFIELD_BORDER_Y+CALFIELD_BORDER_YTOP; + mpTodayBtn->SetPosSizePixel( Point( nX, nY ), aTodayBtnSize ); + nX += aTodayBtnSize.Width() + CALFIELD_SEP_X; + mpNoneBtn->SetPosSizePixel( Point( nX, nY ), aNoneBtnSize ); + } + else if ( mpTodayBtn ) + { + Size aTodayBtnSize = mpTodayBtn->GetSizePixel(); + nBtnWidth = aTodayBtnSize.Width(); + nBtnHeight = aTodayBtnSize.Height(); + mpTodayBtn->SetPosPixel( Point( (aOutSize.Width()-nBtnWidth)/2, aOutSize.Height()+CALFIELD_BORDER_Y+CALFIELD_BORDER_YTOP ) ); + } + else if ( mpNoneBtn ) + { + Size aNoneBtnSize = mpNoneBtn->GetSizePixel(); + nBtnWidth = aNoneBtnSize.Width(); + nBtnHeight = aNoneBtnSize.Height(); + mpNoneBtn->SetPosPixel( Point( (aOutSize.Width()-nBtnWidth)/2, aOutSize.Height()+CALFIELD_BORDER_Y+CALFIELD_BORDER_YTOP ) ); + } + + if ( nBtnHeight ) + { + if ( !mpFixedLine ) + { + mpFixedLine = VclPtr<FixedLine>::Create( this ); + mpFixedLine->Show(); + } + long nLineWidth = aOutSize.Width()-(CALFIELD_BORDERLINE_X*2); + mpFixedLine->setPosSizePixel( (aOutSize.Width()-nLineWidth)/2, aOutSize.Height()+((CALFIELD_BORDER_YTOP-2)/2), + nLineWidth, 2 ); + aOutSize.AdjustHeight(nBtnHeight + (CALFIELD_BORDER_Y*2) + CALFIELD_BORDER_YTOP ); + SetOutputSizePixel( aOutSize ); + } + else + { + mpFixedLine.disposeAndClear(); + } +} + +bool ImplCFieldFloatWin::EventNotify( NotifyEvent& rNEvt ) +{ + if ( rNEvt.GetType() == MouseNotifyEvent::KEYINPUT ) + { + const KeyEvent* pKEvt = rNEvt.GetKeyEvent(); + if ( pKEvt->GetKeyCode().GetCode() == KEY_RETURN ) + mpCalendar->Select(); + } + + return FloatingWindow::EventNotify( rNEvt ); +} + +CalendarField::CalendarField(vcl::Window* pParent, WinBits nWinStyle) + : DateField(pParent, nWinStyle) + , mpFloatWin(nullptr) + , mpCalendar(nullptr) + , mpTodayBtn(nullptr) + , mpNoneBtn(nullptr) + , mbToday(false) + , mbNone(false) +{ +} + +CalendarField::~CalendarField() +{ + disposeOnce(); +} + +void CalendarField::dispose() +{ + mpCalendar.disposeAndClear(); + mpFloatWin.disposeAndClear(); + mpTodayBtn.clear(); + mpNoneBtn.clear(); + DateField::dispose(); +} + +IMPL_LINK( CalendarField, ImplSelectHdl, Calendar*, pCalendar, void ) +{ + if ( pCalendar->IsTravelSelect() ) + return; + + mpFloatWin->EndPopupMode(); + EndDropDown(); + GrabFocus(); + Date aNewDate = mpCalendar->GetFirstSelectedDate(); + if ( IsEmptyDate() || ( aNewDate != GetDate() ) ) + { + SetDate( aNewDate ); + SetModifyFlag(); + Modify(); + } +} + +IMPL_LINK( CalendarField, ImplClickHdl, Button*, pButton, void ) +{ + PushButton* pBtn = static_cast<PushButton*>(pButton); + mpFloatWin->EndPopupMode(); + EndDropDown(); + GrabFocus(); + + if ( pBtn == mpTodayBtn ) + { + Date aToday( Date::SYSTEM ); + if ( (aToday != GetDate()) || IsEmptyDate() ) + { + SetDate( aToday ); + SetModifyFlag(); + Modify(); + } + } + else if ( pBtn == mpNoneBtn ) + { + if ( !IsEmptyDate() ) + { + SetEmptyDate(); + SetModifyFlag(); + Modify(); + } + } +} + +IMPL_LINK_NOARG(CalendarField, ImplPopupModeEndHdl, FloatingWindow*, void) +{ + EndDropDown(); + GrabFocus(); + mpCalendar->EndSelection(); +} + +bool CalendarField::ShowDropDown( bool bShow ) +{ + if ( bShow ) + { + Calendar* pCalendar = GetCalendar(); + + Date aDate = GetDate(); + if ( IsEmptyDate() || !aDate.IsValidAndGregorian() ) + { + aDate = Date( Date::SYSTEM ); + } + pCalendar->SetCurDate( aDate ); + Point aPos( GetParent()->OutputToScreenPixel( GetPosPixel() ) ); + tools::Rectangle aRect( aPos, GetSizePixel() ); + aRect.AdjustBottom( -1 ); + mpCalendar->SetOutputSizePixel( mpCalendar->CalcWindowSizePixel() ); + mpFloatWin->SetOutputSizePixel( mpCalendar->GetSizePixel() ); + mpFloatWin->SetCalendar( mpCalendar ); + mpTodayBtn = mpFloatWin->EnableTodayBtn( mbToday ); + mpNoneBtn = mpFloatWin->EnableNoneBtn( mbNone ); + if ( mpTodayBtn ) + mpTodayBtn->SetClickHdl( LINK( this, CalendarField, ImplClickHdl ) ); + if ( mpNoneBtn ) + mpNoneBtn->SetClickHdl( LINK( this, CalendarField, ImplClickHdl ) ); + mpFloatWin->ArrangeButtons(); + mpCalendar->EnableCallEverySelect(); + mpCalendar->StartSelection(); + mpCalendar->GrabFocus(); + mpCalendar->Show(); + mpFloatWin->StartPopupMode( aRect, FloatWinPopupFlags::Down ); + } + else + { + mpFloatWin->EndPopupMode( FloatWinPopupEndFlags::Cancel ); + mpCalendar->EndSelection(); + EndDropDown(); + } + return true; +} + +Calendar* CalendarField::GetCalendar() +{ + if ( !mpFloatWin ) + { + mpFloatWin = VclPtr<ImplCFieldFloatWin>::Create( this ); + mpFloatWin->SetPopupModeEndHdl( LINK( this, CalendarField, ImplPopupModeEndHdl ) ); + mpCalendar = VclPtr<Calendar>::Create( mpFloatWin, WB_TABSTOP ); + mpCalendar->SetPosPixel( Point() ); + mpCalendar->SetSelectHdl( LINK( this, CalendarField, ImplSelectHdl ) ); + } + + return mpCalendar; +} + +void CalendarField::StateChanged( StateChangedType nStateChange ) +{ + DateField::StateChanged( nStateChange ); + + if ( ( nStateChange == StateChangedType::Style ) && GetSubEdit() ) + { + WinBits nAllAlignmentBits = ( WB_LEFT | WB_CENTER | WB_RIGHT | WB_TOP | WB_VCENTER | WB_BOTTOM ); + WinBits nMyAlignment = GetStyle() & nAllAlignmentBits; + GetSubEdit()->SetStyle( ( GetSubEdit()->GetStyle() & ~nAllAlignmentBits ) | nMyAlignment ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/control/collatorres.cxx b/svtools/source/control/collatorres.cxx new file mode 100644 index 000000000..c2db6b4e9 --- /dev/null +++ b/svtools/source/control/collatorres.cxx @@ -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 . + */ + +#include <svtools/svtresid.hxx> +#include <svtools/strings.hrc> +#include <svtools/collatorres.hxx> + +// implementation of the collator-algorithm-name translation +CollatorResource::CollatorResource() +{ + m_aData.emplace_back("alphanumeric", SvtResId(STR_SVT_COLLATE_ALPHANUMERIC)); + m_aData.emplace_back("charset", SvtResId(STR_SVT_COLLATE_CHARSET)); + m_aData.emplace_back("dict", SvtResId(STR_SVT_COLLATE_DICTIONARY)); + m_aData.emplace_back("normal", SvtResId(STR_SVT_COLLATE_NORMAL)); + m_aData.emplace_back("pinyin", SvtResId(STR_SVT_COLLATE_PINYIN)); + m_aData.emplace_back("radical", SvtResId(STR_SVT_COLLATE_RADICAL)); + m_aData.emplace_back("stroke", SvtResId(STR_SVT_COLLATE_STROKE)); + m_aData.emplace_back("unicode", SvtResId(STR_SVT_COLLATE_UNICODE)); + m_aData.emplace_back("zhuyin", SvtResId(STR_SVT_COLLATE_ZHUYIN)); + m_aData.emplace_back("phonebook", SvtResId(STR_SVT_COLLATE_PHONEBOOK)); + m_aData.emplace_back("phonetic (alphanumeric first)", SvtResId(STR_SVT_COLLATE_PHONETIC_F)); + m_aData.emplace_back("phonetic (alphanumeric last)", SvtResId(STR_SVT_COLLATE_PHONETIC_L)); +} + +const OUString& +CollatorResource::GetTranslation(const OUString &r_Algorithm) +{ + sal_Int32 nIndex = r_Algorithm.indexOf('.'); + OUString aLocaleFreeAlgorithm; + + if (nIndex == -1) + { + aLocaleFreeAlgorithm = r_Algorithm; + } + else + { + nIndex += 1; + aLocaleFreeAlgorithm = r_Algorithm.copy(nIndex); + } + + for (size_t i = 0; i < m_aData.size(); ++i) + { + if (aLocaleFreeAlgorithm == m_aData[i].GetAlgorithm()) + return m_aData[i].GetTranslation(); + } + + return r_Algorithm; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/control/ctrlbox.cxx b/svtools/source/control/ctrlbox.cxx new file mode 100644 index 000000000..4a57f2e5b --- /dev/null +++ b/svtools/source/control/ctrlbox.cxx @@ -0,0 +1,1663 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <config_folders.h> + +#include <comphelper/lok.hxx> +#include <i18nutil/unicode.hxx> +#include <tools/stream.hxx> +#include <vcl/builder.hxx> +#include <vcl/customweld.hxx> +#include <vcl/event.hxx> +#include <vcl/svapp.hxx> +#include <vcl/fieldvalues.hxx> +#include <vcl/settings.hxx> +#include <vcl/image.hxx> +#include <vcl/virdev.hxx> +#include <rtl/math.hxx> +#include <sal/macros.h> +#include <sal/log.hxx> +#include <comphelper/processfactory.hxx> +#include <comphelper/string.hxx> +#include <unotools/charclass.hxx> +#include <unotools/fontoptions.hxx> +#include <unotools/localedatawrapper.hxx> + +#include <svtools/borderline.hxx> +#include <svtools/sampletext.hxx> +#include <svtools/svtresid.hxx> +#include <svtools/strings.hrc> +#include <svtools/ctrlbox.hxx> +#include <svtools/ctrltool.hxx> +#include <svtools/borderhelper.hxx> +#include <svtools/valueset.hxx> + +#include <basegfx/polygon/b2dpolygon.hxx> +#include <basegfx/polygon/b2dpolygontools.hxx> +#include <editeng/borderline.hxx> + +#include <rtl/bootstrap.hxx> + +#include <boost/property_tree/ptree.hpp> + +#include <borderline.hrc> + +#include <stdio.h> + +#define IMGOUTERTEXTSPACE 5 +#define EXTRAFONTSIZE 5 +#define GAPTOEXTRAPREVIEW 10 +#define MINGAPWIDTH 2 + +#define FONTNAMEBOXMRUENTRIESFILE "/user/config/fontnameboxmruentries" + + +BorderWidthImpl::BorderWidthImpl( BorderWidthImplFlags nFlags, double nRate1, double nRate2, double nRateGap ): + m_nFlags( nFlags ), + m_nRate1( nRate1 ), + m_nRate2( nRate2 ), + m_nRateGap( nRateGap ) +{ +} + +bool BorderWidthImpl::operator== ( const BorderWidthImpl& r ) const +{ + return ( m_nFlags == r.m_nFlags ) && + ( m_nRate1 == r.m_nRate1 ) && + ( m_nRate2 == r.m_nRate2 ) && + ( m_nRateGap == r.m_nRateGap ); +} + +long BorderWidthImpl::GetLine1( long nWidth ) const +{ + long result = static_cast<long>(m_nRate1); + if ( m_nFlags & BorderWidthImplFlags::CHANGE_LINE1 ) + { + long const nConstant2 = (m_nFlags & BorderWidthImplFlags::CHANGE_LINE2) ? 0 : m_nRate2; + long const nConstantD = (m_nFlags & BorderWidthImplFlags::CHANGE_DIST ) ? 0 : m_nRateGap; + result = std::max<long>(0, + static_cast<long>((m_nRate1 * nWidth) + 0.5) + - (nConstant2 + nConstantD)); + if (result == 0 && m_nRate1 > 0.0 && nWidth > 0) + { // fdo#51777: hack to essentially treat 1 twip DOUBLE border + result = 1; // as 1 twip SINGLE border + } + } + return result; +} + +long BorderWidthImpl::GetLine2( long nWidth ) const +{ + long result = static_cast<long>(m_nRate2); + if ( m_nFlags & BorderWidthImplFlags::CHANGE_LINE2) + { + long const nConstant1 = (m_nFlags & BorderWidthImplFlags::CHANGE_LINE1) ? 0 : m_nRate1; + long const nConstantD = (m_nFlags & BorderWidthImplFlags::CHANGE_DIST ) ? 0 : m_nRateGap; + result = std::max<long>(0, + static_cast<long>((m_nRate2 * nWidth) + 0.5) + - (nConstant1 + nConstantD)); + } + return result; +} + +long BorderWidthImpl::GetGap( long nWidth ) const +{ + long result = static_cast<long>(m_nRateGap); + if ( m_nFlags & BorderWidthImplFlags::CHANGE_DIST ) + { + long const nConstant1 = (m_nFlags & BorderWidthImplFlags::CHANGE_LINE1) ? 0 : m_nRate1; + long const nConstant2 = (m_nFlags & BorderWidthImplFlags::CHANGE_LINE2) ? 0 : m_nRate2; + result = std::max<long>(0, + static_cast<long>((m_nRateGap * nWidth) + 0.5) + - (nConstant1 + nConstant2)); + } + + // Avoid having too small distances (less than 0.1pt) + if ( result < MINGAPWIDTH && m_nRate1 > 0 && m_nRate2 > 0 ) + result = MINGAPWIDTH; + + return result; +} + +static double lcl_getGuessedWidth( long nTested, double nRate, bool bChanging ) +{ + double nWidth = -1.0; + if ( bChanging ) + nWidth = double( nTested ) / nRate; + else + { + if ( rtl::math::approxEqual(double( nTested ), nRate) ) + nWidth = nRate; + } + + return nWidth; +} + +long BorderWidthImpl::GuessWidth( long nLine1, long nLine2, long nGap ) +{ + std::vector< double > aToCompare; + bool bInvalid = false; + + bool bLine1Change = bool( m_nFlags & BorderWidthImplFlags::CHANGE_LINE1 ); + double nWidth1 = lcl_getGuessedWidth( nLine1, m_nRate1, bLine1Change ); + if ( bLine1Change ) + aToCompare.push_back( nWidth1 ); + else if (nWidth1 < 0) + bInvalid = true; + + bool bLine2Change = bool( m_nFlags & BorderWidthImplFlags::CHANGE_LINE2 ); + double nWidth2 = lcl_getGuessedWidth( nLine2, m_nRate2, bLine2Change ); + if ( bLine2Change ) + aToCompare.push_back( nWidth2 ); + else if (nWidth2 < 0) + bInvalid = true; + + bool bGapChange = bool( m_nFlags & BorderWidthImplFlags::CHANGE_DIST ); + double nWidthGap = lcl_getGuessedWidth( nGap, m_nRateGap, bGapChange ); + if ( bGapChange && nGap >= MINGAPWIDTH ) + aToCompare.push_back( nWidthGap ); + else if ( !bGapChange && nWidthGap < 0 ) + bInvalid = true; + + // non-constant line width factors must sum to 1 + assert((((bLine1Change) ? m_nRate1 : 0) + + ((bLine2Change) ? m_nRate2 : 0) + + ((bGapChange) ? m_nRateGap : 0)) - 1.0 < 0.00001 ); + + double nWidth = 0.0; + if ( (!bInvalid) && (!aToCompare.empty()) ) + { + nWidth = *aToCompare.begin(); + for (auto const& elem : aToCompare) + { + bInvalid = ( nWidth != elem ); + if (bInvalid) + break; + } + nWidth = bInvalid ? 0.0 : nLine1 + nLine2 + nGap; + } + + return nWidth; +} + +static void lclDrawPolygon( OutputDevice& rDev, const basegfx::B2DPolygon& rPolygon, long nWidth, SvxBorderLineStyle nDashing ) +{ + AntialiasingFlags nOldAA = rDev.GetAntialiasing(); + rDev.SetAntialiasing( nOldAA & ~AntialiasingFlags::EnableB2dDraw ); + + long nPix = rDev.PixelToLogic(Size(1, 1)).Width(); + basegfx::B2DPolyPolygon aPolygons = svtools::ApplyLineDashing(rPolygon, nDashing, nPix); + + // Handle problems of width 1px in Pixel mode: 0.5px gives a 1px line + if (rDev.GetMapMode().GetMapUnit() == MapUnit::MapPixel && nWidth == nPix) + nWidth = 0; + + for ( sal_uInt32 i = 0; i < aPolygons.count( ); i++ ) + { + const basegfx::B2DPolygon& aDash = aPolygons.getB2DPolygon( i ); + basegfx::B2DPoint aStart = aDash.getB2DPoint( 0 ); + basegfx::B2DPoint aEnd = aDash.getB2DPoint( aDash.count() - 1 ); + + basegfx::B2DVector aVector( aEnd - aStart ); + aVector.normalize( ); + const basegfx::B2DVector aPerpendicular(basegfx::getPerpendicular(aVector)); + + const basegfx::B2DVector aWidthOffset( double( nWidth ) / 2 * aPerpendicular); + basegfx::B2DPolygon aDashPolygon; + aDashPolygon.append( aStart + aWidthOffset ); + aDashPolygon.append( aEnd + aWidthOffset ); + aDashPolygon.append( aEnd - aWidthOffset ); + aDashPolygon.append( aStart - aWidthOffset ); + aDashPolygon.setClosed( true ); + + rDev.DrawPolygon( aDashPolygon ); + } + + rDev.SetAntialiasing( nOldAA ); +} + +namespace svtools { + +/** + * Dashing array must start with a line width and end with a blank width. + */ +static std::vector<double> GetDashing( SvxBorderLineStyle nDashing ) +{ + std::vector<double> aPattern; + switch (nDashing) + { + case SvxBorderLineStyle::DOTTED: + aPattern.push_back( 1.0 ); // line + aPattern.push_back( 2.0 ); // blank + break; + case SvxBorderLineStyle::DASHED: + aPattern.push_back( 16.0 ); // line + aPattern.push_back( 5.0 ); // blank + break; + case SvxBorderLineStyle::FINE_DASHED: + aPattern.push_back( 6.0 ); // line + aPattern.push_back( 2.0 ); // blank + break; + case SvxBorderLineStyle::DASH_DOT: + aPattern.push_back( 16.0 ); // line + aPattern.push_back( 5.0 ); // blank + aPattern.push_back( 5.0 ); // line + aPattern.push_back( 5.0 ); // blank + break; + case SvxBorderLineStyle::DASH_DOT_DOT: + aPattern.push_back( 16.0 ); // line + aPattern.push_back( 5.0 ); // blank + aPattern.push_back( 5.0 ); // line + aPattern.push_back( 5.0 ); // blank + aPattern.push_back( 5.0 ); // line + aPattern.push_back( 5.0 ); // blank + break; + default: + ; + } + + return aPattern; +} + +namespace { + +class ApplyScale +{ + double mfScale; +public: + explicit ApplyScale( double fScale ) : mfScale(fScale) {} + void operator() ( double& rVal ) + { + rVal *= mfScale; + } +}; + +} + +std::vector<double> GetLineDashing( SvxBorderLineStyle nDashing, double fScale ) +{ + std::vector<double> aPattern = GetDashing(nDashing); + std::for_each(aPattern.begin(), aPattern.end(), ApplyScale(fScale)); + return aPattern; +} + +basegfx::B2DPolyPolygon ApplyLineDashing( const basegfx::B2DPolygon& rPolygon, SvxBorderLineStyle nDashing, double fScale ) +{ + std::vector<double> aPattern = GetDashing(nDashing); + std::for_each(aPattern.begin(), aPattern.end(), ApplyScale(fScale)); + + basegfx::B2DPolyPolygon aPolygons; + + if (aPattern.empty()) + aPolygons.append(rPolygon); + else + basegfx::utils::applyLineDashing(rPolygon, aPattern, &aPolygons); + + return aPolygons; +} + +void DrawLine( OutputDevice& rDev, const Point& rP1, const Point& rP2, + sal_uInt32 nWidth, SvxBorderLineStyle nDashing ) +{ + DrawLine( rDev, basegfx::B2DPoint( rP1.X(), rP1.Y() ), + basegfx::B2DPoint( rP2.X(), rP2.Y( ) ), nWidth, nDashing ); +} + +void DrawLine( OutputDevice& rDev, const basegfx::B2DPoint& rP1, const basegfx::B2DPoint& rP2, + sal_uInt32 nWidth, SvxBorderLineStyle nDashing ) +{ + basegfx::B2DPolygon aPolygon; + aPolygon.append( rP1 ); + aPolygon.append( rP2 ); + lclDrawPolygon( rDev, aPolygon, nWidth, nDashing ); +} + +} + +static Size gUserItemSz; +static int gFontNameBoxes; +static size_t gPreviewsPerDevice; +static std::vector<VclPtr<VirtualDevice>> gFontPreviewVirDevs; +static std::vector<OUString> gRenderedFontNames; + +FontNameBox::FontNameBox(std::unique_ptr<weld::ComboBox> p) + : m_xComboBox(std::move(p)) + , mnPreviewProgress(0) + , mbWYSIWYG(false) + , maUpdateIdle("FontNameBox Preview Update") +{ + ++gFontNameBoxes; + InitFontMRUEntriesFile(); + + maUpdateIdle.SetPriority(TaskPriority::LOWEST); + maUpdateIdle.SetInvokeHandler(LINK(this, FontNameBox, UpdateHdl)); +} + +FontNameBox::~FontNameBox() +{ + if (mpFontList) + { + SaveMRUEntries (maFontMRUEntriesFile); + ImplDestroyFontList(); + } + --gFontNameBoxes; + if (!gFontNameBoxes) + { + for (auto &rDev : gFontPreviewVirDevs) + rDev.disposeAndClear(); + gFontPreviewVirDevs.clear(); + gRenderedFontNames.clear(); + } +} + +void FontNameBox::SaveMRUEntries(const OUString& aFontMRUEntriesFile) const +{ + OString aEntries(OUStringToOString(m_xComboBox->get_mru_entries(), + RTL_TEXTENCODING_UTF8)); + + if (aEntries.isEmpty() || aFontMRUEntriesFile.isEmpty()) + return; + + SvFileStream aStream; + aStream.Open( aFontMRUEntriesFile, StreamMode::WRITE | StreamMode::TRUNC ); + if( ! (aStream.IsOpen() && aStream.IsWritable()) ) + { + SAL_INFO("svtools.control", "FontNameBox::SaveMRUEntries: opening mru entries file " << aFontMRUEntriesFile << " failed"); + return; + } + + aStream.SetLineDelimiter( LINEEND_LF ); + aStream.WriteLine( aEntries ); + aStream.WriteLine( OString() ); +} + +void FontNameBox::LoadMRUEntries( const OUString& aFontMRUEntriesFile ) +{ + if (aFontMRUEntriesFile.isEmpty()) + return; + + SvtFontOptions aFontOpt; + if (!aFontOpt.IsFontHistoryEnabled()) + return; + + SvFileStream aStream( aFontMRUEntriesFile, StreamMode::READ ); + if( ! aStream.IsOpen() ) + { + SAL_INFO("svtools.control", "FontNameBox::LoadMRUEntries: opening mru entries file " << aFontMRUEntriesFile << " failed"); + return; + } + + OString aLine; + aStream.ReadLine( aLine ); + OUString aEntries = OStringToOUString(aLine, + RTL_TEXTENCODING_UTF8); + m_xComboBox->set_mru_entries(aEntries); +} + +void FontNameBox::InitFontMRUEntriesFile() +{ + OUString sUserConfigDir("${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER "/" SAL_CONFIGFILE( "bootstrap") "::UserInstallation}"); + rtl::Bootstrap::expandMacros(sUserConfigDir); + + maFontMRUEntriesFile = sUserConfigDir; + if( !maFontMRUEntriesFile.isEmpty() ) + { + maFontMRUEntriesFile += FONTNAMEBOXMRUENTRIESFILE; + } +} + +void FontNameBox::ImplDestroyFontList() +{ + mpFontList.reset(); + mnPreviewProgress = 0; + maUpdateIdle.Stop(); +} + +void FontNameBox::Fill( const FontList* pList ) +{ + // store old text and clear box + OUString aOldText = m_xComboBox->get_active_text(); + OUString rEntries = m_xComboBox->get_mru_entries(); + bool bLoadFromFile = rEntries.isEmpty(); + m_xComboBox->freeze(); + m_xComboBox->clear(); + + ImplDestroyFontList(); + mpFontList.reset(new ImplFontList); + + // insert fonts + size_t nFontCount = pList->GetFontNameCount(); + for (size_t i = 0; i < nFontCount; ++i) + { + const FontMetric& rFontMetric = pList->GetFontName(i); + m_xComboBox->append(OUString::number(i), rFontMetric.GetFamilyName()); + mpFontList->push_back(rFontMetric); + } + + if (bLoadFromFile) + LoadMRUEntries(maFontMRUEntriesFile); + else + m_xComboBox->set_mru_entries(rEntries); + + m_xComboBox->thaw(); + + if (mbWYSIWYG && nFontCount) + { + assert(mnPreviewProgress == 0 && "ImplDestroyFontList wasn't called"); + maUpdateIdle.Start(); + } + + // restore text + if (!aOldText.isEmpty()) + set_active_or_entry_text(aOldText); +} + +void FontNameBox::EnableWYSIWYG(bool bEnable) +{ + if (comphelper::LibreOfficeKit::isActive()) + return; + if (mbWYSIWYG == bEnable) + return; + mbWYSIWYG = bEnable; + + static bool bGlobalsInited; + if (mbWYSIWYG && !bGlobalsInited) + { + gUserItemSz = Size(m_xComboBox->get_approximate_digit_width() * 52, m_xComboBox->get_text_height()); + gUserItemSz.setHeight(gUserItemSz.Height() * 16); + gUserItemSz.setHeight(gUserItemSz.Height() / 10); + + size_t nMaxDeviceHeight = SAL_MAX_INT16 / 2; // see limitXCreatePixmap + gPreviewsPerDevice = nMaxDeviceHeight / gUserItemSz.Height(); + + bGlobalsInited = true; + } + + if (mbWYSIWYG) + { + m_xComboBox->connect_custom_get_size(LINK(this, FontNameBox, CustomGetSizeHdl)); + m_xComboBox->connect_custom_render(LINK(this, FontNameBox, CustomRenderHdl)); + } + else + { + m_xComboBox->connect_custom_get_size(Link<OutputDevice&, Size>()); + m_xComboBox->connect_custom_render(Link<weld::ComboBox::render_args, void>()); + } + m_xComboBox->set_custom_renderer(mbWYSIWYG); +} + +IMPL_STATIC_LINK_NOARG(FontNameBox, CustomGetSizeHdl, OutputDevice&, Size) +{ + return gUserItemSz; +} + +namespace +{ + long shrinkFontToFit(OUString const &rSampleText, long nH, vcl::Font &rFont, OutputDevice &rDevice, tools::Rectangle &rTextRect) + { + long nWidth = 0; + + Size aSize( rFont.GetFontSize() ); + + //Make sure it fits in the available height + while (aSize.Height() > 0) + { + if (!rDevice.GetTextBoundRect(rTextRect, rSampleText)) + break; + if (rTextRect.GetHeight() <= nH) + { + nWidth = rTextRect.GetWidth(); + break; + } + + aSize.AdjustHeight( -(EXTRAFONTSIZE) ); + rFont.SetFontSize(aSize); + rDevice.SetFont(rFont); + } + + return nWidth; + } +} + +IMPL_LINK_NOARG(FontNameBox, UpdateHdl, Timer*, void) +{ + CachePreview(mnPreviewProgress++, nullptr); + // tdf#132536 limit to ~25 pre-rendered for now. The font caches look + // b0rked, the massive charmaps are ~never swapped out, and don't count + // towards the size of a font in the font cache and if the freetype font + // cache size is set experimentally very low then we crash, so there's an + // awful lot to consider there. + if (mnPreviewProgress < std::min<size_t>(25, mpFontList->size())) + maUpdateIdle.Start(); +} + +static void DrawPreview(const FontMetric& rFontMetric, const Point& rTopLeft, OutputDevice& rDevice, bool bSelected) +{ + rDevice.Push(PushFlags::TEXTCOLOR); + + const StyleSettings& rStyleSettings = Application::GetSettings().GetStyleSettings(); + if (bSelected) + rDevice.SetTextColor(rStyleSettings.GetHighlightTextColor()); + else + rDevice.SetTextColor(rStyleSettings.GetDialogTextColor()); + + long nX = rTopLeft.X(); + long nH = gUserItemSz.Height(); + + nX += IMGOUTERTEXTSPACE; + + const bool bSymbolFont = isSymbolFont(rFontMetric); + + vcl::Font aOldFont(rDevice.GetFont()); + Size aSize( aOldFont.GetFontSize() ); + aSize.AdjustHeight(EXTRAFONTSIZE ); + vcl::Font aFont( rFontMetric ); + aFont.SetFontSize( aSize ); + rDevice.SetFont(aFont); + + bool bUsingCorrectFont = true; + tools::Rectangle aTextRect; + + // Preview the font name + const OUString& sFontName = rFontMetric.GetFamilyName(); + + //If it shouldn't or can't draw its own name because it doesn't have the glyphs + if (!canRenderNameOfSelectedFont(rDevice)) + bUsingCorrectFont = false; + else + { + //Make sure it fits in the available height, shrinking the font if necessary + bUsingCorrectFont = shrinkFontToFit(sFontName, nH, aFont, rDevice, aTextRect) != 0; + } + + if (!bUsingCorrectFont) + { + rDevice.SetFont(aOldFont); + rDevice.GetTextBoundRect(aTextRect, sFontName); + } + + long nTextHeight = aTextRect.GetHeight(); + long nDesiredGap = (nH-nTextHeight)/2; + long nVertAdjust = nDesiredGap - aTextRect.Top(); + Point aPos( nX, rTopLeft.Y() + nVertAdjust ); + rDevice.DrawText(aPos, sFontName); + long nTextX = aPos.X() + aTextRect.GetWidth() + GAPTOEXTRAPREVIEW; + + if (!bUsingCorrectFont) + rDevice.SetFont(aFont); + + OUString sSampleText; + + if (!bSymbolFont) + { + const bool bNameBeginsWithLatinText = rFontMetric.GetFamilyName()[0] <= 'z'; + + if (bNameBeginsWithLatinText || !bUsingCorrectFont) + sSampleText = makeShortRepresentativeTextForSelectedFont(rDevice); + } + + //If we're not a symbol font, but could neither render our own name and + //we can't determine what script it would like to render, then try a + //few well known scripts + if (sSampleText.isEmpty() && !bUsingCorrectFont) + { + static const UScriptCode aScripts[] = + { + USCRIPT_ARABIC, + USCRIPT_HEBREW, + + USCRIPT_BENGALI, + USCRIPT_GURMUKHI, + USCRIPT_GUJARATI, + USCRIPT_ORIYA, + USCRIPT_TAMIL, + USCRIPT_TELUGU, + USCRIPT_KANNADA, + USCRIPT_MALAYALAM, + USCRIPT_SINHALA, + USCRIPT_DEVANAGARI, + + USCRIPT_THAI, + USCRIPT_LAO, + USCRIPT_GEORGIAN, + USCRIPT_TIBETAN, + USCRIPT_SYRIAC, + USCRIPT_MYANMAR, + USCRIPT_ETHIOPIC, + USCRIPT_KHMER, + USCRIPT_MONGOLIAN, + + USCRIPT_KOREAN, + USCRIPT_JAPANESE, + USCRIPT_HAN, + USCRIPT_SIMPLIFIED_HAN, + USCRIPT_TRADITIONAL_HAN, + + USCRIPT_GREEK + }; + + for (const UScriptCode& rScript : aScripts) + { + OUString sText = makeShortRepresentativeTextForScript(rScript); + if (!sText.isEmpty()) + { + bool bHasSampleTextGlyphs = (-1 == rDevice.HasGlyphs(aFont, sText)); + if (bHasSampleTextGlyphs) + { + sSampleText = sText; + break; + } + } + } + + static const UScriptCode aMinimalScripts[] = + { + USCRIPT_HEBREW, //e.g. biblical hebrew + USCRIPT_GREEK + }; + + for (const UScriptCode& rMinimalScript : aMinimalScripts) + { + OUString sText = makeShortMinimalTextForScript(rMinimalScript); + if (!sText.isEmpty()) + { + bool bHasSampleTextGlyphs = (-1 == rDevice.HasGlyphs(aFont, sText)); + if (bHasSampleTextGlyphs) + { + sSampleText = sText; + break; + } + } + } + } + + //If we're a symbol font, or for some reason the font still couldn't + //render something representative of what it would like to render then + //make up some semi-random text that it *can* display + if (bSymbolFont || (!bUsingCorrectFont && sSampleText.isEmpty())) + sSampleText = makeShortRepresentativeSymbolTextForSelectedFont(rDevice); + + if (!sSampleText.isEmpty()) + { + const Size &rItemSize = gUserItemSz; + + //leave a little border at the edge + long nSpace = rItemSize.Width() - nTextX - IMGOUTERTEXTSPACE; + if (nSpace >= 0) + { + //Make sure it fits in the available height, and get how wide that would be + long nWidth = shrinkFontToFit(sSampleText, nH, aFont, rDevice, aTextRect); + //Chop letters off until it fits in the available width + while (nWidth > nSpace || nWidth > gUserItemSz.Width()) + { + sSampleText = sSampleText.copy(0, sSampleText.getLength()-1); + nWidth = rDevice.GetTextBoundRect(aTextRect, sSampleText) ? + aTextRect.GetWidth() : 0; + } + + //center the text on the line + if (!sSampleText.isEmpty() && nWidth) + { + nTextHeight = aTextRect.GetHeight(); + nDesiredGap = (nH-nTextHeight)/2; + nVertAdjust = nDesiredGap - aTextRect.Top(); + aPos = Point(nTextX + nSpace - nWidth, rTopLeft.Y() + nVertAdjust); + rDevice.DrawText(aPos, sSampleText); + } + } + } + + rDevice.SetFont(aOldFont); + rDevice.Pop(); +} + +OutputDevice& FontNameBox::CachePreview(size_t nIndex, Point* pTopLeft) +{ + SolarMutexGuard aGuard; + const FontMetric& rFontMetric = (*mpFontList)[nIndex]; + const OUString& rFontName = rFontMetric.GetFamilyName(); + + size_t nPreviewIndex; + auto xFind = std::find(gRenderedFontNames.begin(), gRenderedFontNames.end(), rFontName); + bool bPreviewAvailable = xFind != gRenderedFontNames.end(); + if (!bPreviewAvailable) + { + nPreviewIndex = gRenderedFontNames.size(); + gRenderedFontNames.push_back(rFontName); + } + else + nPreviewIndex = std::distance(gRenderedFontNames.begin(), xFind); + + size_t nPage = nPreviewIndex / gPreviewsPerDevice; + size_t nIndexInPage = nPreviewIndex - (nPage * gPreviewsPerDevice); + + Point aTopLeft(0, gUserItemSz.Height() * nIndexInPage); + + if (!bPreviewAvailable) + { + if (nPage >= gFontPreviewVirDevs.size()) + { + gFontPreviewVirDevs.emplace_back(m_xComboBox->create_render_virtual_device()); + VirtualDevice& rDevice = *gFontPreviewVirDevs.back(); + rDevice.SetOutputSizePixel(Size(gUserItemSz.Width(), gUserItemSz.Height() * gPreviewsPerDevice)); + if (vcl::Window* pDefaultDevice = dynamic_cast<vcl::Window*>(Application::GetDefaultDevice())) + pDefaultDevice->SetPointFont(rDevice, m_xComboBox->get_font()); + assert(gFontPreviewVirDevs.size() == nPage + 1); + } + + DrawPreview(rFontMetric, aTopLeft, *gFontPreviewVirDevs.back(), false); + } + + if (pTopLeft) + *pTopLeft = aTopLeft; + + return *gFontPreviewVirDevs[nPage]; +} + +IMPL_LINK(FontNameBox, CustomRenderHdl, weld::ComboBox::render_args, aPayload, void) +{ + vcl::RenderContext& rRenderContext = std::get<0>(aPayload); + const ::tools::Rectangle& rRect = std::get<1>(aPayload); + bool bSelected = std::get<2>(aPayload); + const OUString& rId = std::get<3>(aPayload); + + sal_uInt32 nIndex = rId.toUInt32(); + + Point aDestPoint(rRect.TopLeft()); + auto nMargin = (rRect.GetHeight() - gUserItemSz.Height()) / 2; + aDestPoint.AdjustY(nMargin); + + if (bSelected) + { + const FontMetric& rFontMetric = (*mpFontList)[nIndex]; + DrawPreview(rFontMetric, aDestPoint, rRenderContext, true); + } + else + { + // use cache of unselected entries + Point aTopLeft; + OutputDevice& rDevice = CachePreview(nIndex, &aTopLeft); + + rRenderContext.DrawOutDev(aDestPoint, gUserItemSz, + aTopLeft, gUserItemSz, + rDevice); + } +} + +void FontNameBox::set_active_or_entry_text(const OUString& rText) +{ + const int nFound = m_xComboBox->find_text(rText); + if (nFound != -1) + m_xComboBox->set_active(nFound); + m_xComboBox->set_entry_text(rText); +} + +FontStyleBox::FontStyleBox(std::unique_ptr<weld::ComboBox> p) + : m_xComboBox(std::move(p)) +{ + //Use the standard texts to get an optimal size and stick to that size. + //That should stop the character dialog dancing around. + auto nMaxLen = m_xComboBox->get_pixel_size(SvtResId(STR_SVT_STYLE_LIGHT)).Width(); + nMaxLen = std::max(nMaxLen, m_xComboBox->get_pixel_size(SvtResId(STR_SVT_STYLE_LIGHT_ITALIC)).Width()); + nMaxLen = std::max(nMaxLen, m_xComboBox->get_pixel_size(SvtResId(STR_SVT_STYLE_NORMAL)).Width()); + nMaxLen = std::max(nMaxLen, m_xComboBox->get_pixel_size(SvtResId(STR_SVT_STYLE_NORMAL_ITALIC)).Width()); + nMaxLen = std::max(nMaxLen, m_xComboBox->get_pixel_size(SvtResId(STR_SVT_STYLE_BOLD)).Width()); + nMaxLen = std::max(nMaxLen, m_xComboBox->get_pixel_size(SvtResId(STR_SVT_STYLE_BOLD_ITALIC)).Width()); + nMaxLen = std::max(nMaxLen, m_xComboBox->get_pixel_size(SvtResId(STR_SVT_STYLE_BLACK)).Width()); + nMaxLen = std::max(nMaxLen, m_xComboBox->get_pixel_size(SvtResId(STR_SVT_STYLE_BLACK_ITALIC)).Width()); + m_xComboBox->set_entry_width_chars(std::ceil(nMaxLen / m_xComboBox->get_approximate_digit_width())); +} + +void FontStyleBox::Fill( const OUString& rName, const FontList* pList ) +{ + m_xComboBox->freeze(); + OUString aOldText = m_xComboBox->get_active_text(); + int nPos = m_xComboBox->get_active(); + m_xComboBox->clear(); + + // does a font with this name already exist? + sal_Handle hFontMetric = pList->GetFirstFontMetric( rName ); + if ( hFontMetric ) + { + OUString aStyleText; + FontWeight eLastWeight = WEIGHT_DONTKNOW; + FontItalic eLastItalic = ITALIC_NONE; + FontWidth eLastWidth = WIDTH_DONTKNOW; + bool bNormal = false; + bool bItalic = false; + bool bBold = false; + bool bBoldItalic = false; + bool bInsert = false; + FontMetric aFontMetric; + while ( hFontMetric ) + { + aFontMetric = FontList::GetFontMetric( hFontMetric ); + + FontWeight eWeight = aFontMetric.GetWeight(); + FontItalic eItalic = aFontMetric.GetItalic(); + FontWidth eWidth = aFontMetric.GetWidthType(); + // Only if the attributes are different, we insert the + // Font to avoid double Entries in different languages + if ( (eWeight != eLastWeight) || (eItalic != eLastItalic) || + (eWidth != eLastWidth) ) + { + if ( bInsert ) + m_xComboBox->append_text(aStyleText); + + if ( eWeight <= WEIGHT_NORMAL ) + { + if ( eItalic != ITALIC_NONE ) + bItalic = true; + else + bNormal = true; + } + else + { + if ( eItalic != ITALIC_NONE ) + bBoldItalic = true; + else + bBold = true; + } + + // For wrong StyleNames we replace this with the correct once + aStyleText = pList->GetStyleName( aFontMetric ); + bInsert = m_xComboBox->find_text(aStyleText) == -1; + if ( !bInsert ) + { + aStyleText = pList->GetStyleName( eWeight, eItalic ); + bInsert = m_xComboBox->find_text(aStyleText) == -1; + } + + eLastWeight = eWeight; + eLastItalic = eItalic; + eLastWidth = eWidth; + } + else + { + if ( bInsert ) + { + // If we have two names for the same attributes + // we prefer the translated standard names + const OUString& rAttrStyleText = pList->GetStyleName( eWeight, eItalic ); + if (rAttrStyleText != aStyleText) + { + OUString aTempStyleText = pList->GetStyleName( aFontMetric ); + if (rAttrStyleText == aTempStyleText) + aStyleText = rAttrStyleText; + bInsert = m_xComboBox->find_text(aStyleText) == -1; + } + } + } + + if ( !bItalic && (aStyleText == pList->GetItalicStr()) ) + bItalic = true; + else if ( !bBold && (aStyleText == pList->GetBoldStr()) ) + bBold = true; + else if ( !bBoldItalic && (aStyleText == pList->GetBoldItalicStr()) ) + bBoldItalic = true; + + hFontMetric = FontList::GetNextFontMetric( hFontMetric ); + } + + if ( bInsert ) + m_xComboBox->append_text(aStyleText); + + // certain style as copy + if ( bNormal ) + { + if ( !bItalic ) + m_xComboBox->append_text(pList->GetItalicStr()); + if ( !bBold ) + m_xComboBox->append_text(pList->GetBoldStr()); + } + if ( !bBoldItalic ) + { + if ( bNormal || bItalic || bBold ) + m_xComboBox->append_text(pList->GetBoldItalicStr()); + } + if (!aOldText.isEmpty()) + { + int nFound = m_xComboBox->find_text(aOldText); + if (nFound != -1) + m_xComboBox->set_active(nFound); + else + { + if (nPos >= m_xComboBox->get_count()) + m_xComboBox->set_active(0); + else + m_xComboBox->set_active(nPos); + } + } + } + else + { + // insert standard styles if no font + m_xComboBox->append_text(pList->GetNormalStr()); + m_xComboBox->append_text(pList->GetItalicStr()); + m_xComboBox->append_text(pList->GetBoldStr()); + m_xComboBox->append_text(pList->GetBoldItalicStr()); + if (!aOldText.isEmpty()) + { + if (nPos >= m_xComboBox->get_count()) + m_xComboBox->set_active(0); + else + m_xComboBox->set_active(nPos); + } + } + m_xComboBox->thaw(); +} + +FontSizeBox::FontSizeBox(std::unique_ptr<weld::ComboBox> p) + : pFontList(nullptr) + , nSavedValue(0) + , nMin(20) + , nMax(9999) + , eUnit(FieldUnit::POINT) + , nDecimalDigits(1) + , nRelMin(0) + , nRelMax(0) + , nRelStep(0) + , nPtRelMin(0) + , nPtRelMax(0) + , nPtRelStep(0) + , bRelativeMode(false) + , bRelative(false) + , bPtRelative(false) + , bStdSize(false) + , m_xComboBox(std::move(p)) +{ + m_xComboBox->set_entry_width_chars(std::ceil(m_xComboBox->get_pixel_size(format_number(105)).Width() / + m_xComboBox->get_approximate_digit_width())); + m_xComboBox->connect_focus_out(LINK(this, FontSizeBox, ReformatHdl)); + m_xComboBox->connect_changed(LINK(this, FontSizeBox, ModifyHdl)); +} + +void FontSizeBox::set_active_or_entry_text(const OUString& rText) +{ + const int nFound = m_xComboBox->find_text(rText); + if (nFound != -1) + m_xComboBox->set_active(nFound); + m_xComboBox->set_entry_text(rText); +} + +IMPL_LINK(FontSizeBox, ReformatHdl, weld::Widget&, rWidget, void) +{ + FontSizeNames aFontSizeNames(Application::GetSettings().GetUILanguageTag().getLanguageType()); + if (!bRelativeMode || !aFontSizeNames.IsEmpty()) + { + if (aFontSizeNames.Name2Size(m_xComboBox->get_active_text()) != 0) + return; + } + + set_value(get_value()); + + m_aFocusOutHdl.Call(rWidget); +} + +IMPL_LINK(FontSizeBox, ModifyHdl, weld::ComboBox&, rBox, void) +{ + if (bRelativeMode) + { + OUString aStr = comphelper::string::stripStart(rBox.get_active_text(), ' '); + + bool bNewMode = bRelative; + bool bOldPtRelMode = bPtRelative; + + if ( bRelative ) + { + bPtRelative = false; + const sal_Unicode* pStr = aStr.getStr(); + while ( *pStr ) + { + if ( ((*pStr < '0') || (*pStr > '9')) && (*pStr != '%') && !unicode::isSpace(*pStr) ) + { + if ( ('-' == *pStr || '+' == *pStr) && !bPtRelative ) + bPtRelative = true; + else if ( bPtRelative && 'p' == *pStr && 't' == *++pStr ) + ; + else + { + bNewMode = false; + break; + } + } + pStr++; + } + } + else if (!aStr.isEmpty()) + { + if ( -1 != aStr.indexOf('%') ) + { + bNewMode = true; + bPtRelative = false; + } + + if ( '-' == aStr[0] || '+' == aStr[0] ) + { + bNewMode = true; + bPtRelative = true; + } + } + + if ( bNewMode != bRelative || bPtRelative != bOldPtRelMode ) + SetRelative( bNewMode ); + } + m_aChangeHdl.Call(rBox); +} + +void FontSizeBox::Fill( const FontMetric* pFontMetric, const FontList* pList ) +{ + // remember for relative mode + pFontList = pList; + + // no font sizes need to be set for relative mode + if ( bRelative ) + return; + + // query font sizes + const sal_IntPtr* pTempAry; + const sal_IntPtr* pAry = nullptr; + + if( pFontMetric ) + { + aFontMetric = *pFontMetric; + pAry = pList->GetSizeAry( *pFontMetric ); + } + else + { + pAry = FontList::GetStdSizeAry(); + } + + // first insert font size names (for simplified/traditional chinese) + FontSizeNames aFontSizeNames( Application::GetSettings().GetUILanguageTag().getLanguageType() ); + if ( pAry == FontList::GetStdSizeAry() ) + { + // for standard sizes we don't need to bother + if (bStdSize && m_xComboBox->get_count() && aFontSizeNames.IsEmpty()) + return; + bStdSize = true; + } + else + bStdSize = false; + + int nSelectionStart, nSelectionEnd; + m_xComboBox->get_entry_selection_bounds(nSelectionStart, nSelectionEnd); + OUString aStr = m_xComboBox->get_active_text(); + + m_xComboBox->freeze(); + m_xComboBox->clear(); + int nPos = 0; + + if ( !aFontSizeNames.IsEmpty() ) + { + if ( pAry == FontList::GetStdSizeAry() ) + { + // for scalable fonts all font size names + sal_uLong nCount = aFontSizeNames.Count(); + for( sal_uLong i = 0; i < nCount; i++ ) + { + OUString aSizeName = aFontSizeNames.GetIndexName( i ); + sal_IntPtr nSize = aFontSizeNames.GetIndexSize( i ); + OUString sId(OUString::number(-nSize)); // mark as special + m_xComboBox->insert(nPos, aSizeName, &sId, nullptr, nullptr); + nPos++; + } + } + else + { + // for fixed size fonts only selectable font size names + pTempAry = pAry; + while ( *pTempAry ) + { + OUString aSizeName = aFontSizeNames.Size2Name( *pTempAry ); + if ( !aSizeName.isEmpty() ) + { + OUString sId(OUString::number(-(*pTempAry))); // mark as special + m_xComboBox->insert(nPos, aSizeName, &sId, nullptr, nullptr); + nPos++; + } + pTempAry++; + } + } + } + + // then insert numerical font size values + pTempAry = pAry; + while (*pTempAry) + { + InsertValue(*pTempAry); + ++pTempAry; + } + + set_active_or_entry_text(aStr); + m_xComboBox->select_entry_region(nSelectionStart, nSelectionEnd); + m_xComboBox->thaw(); +} + +void FontSizeBox::EnableRelativeMode( sal_uInt16 nNewMin, sal_uInt16 nNewMax, sal_uInt16 nStep ) +{ + bRelativeMode = true; + nRelMin = nNewMin; + nRelMax = nNewMax; + nRelStep = nStep; + SetUnit(FieldUnit::POINT); +} + +void FontSizeBox::EnablePtRelativeMode( short nNewMin, short nNewMax, short nStep ) +{ + bRelativeMode = true; + nPtRelMin = nNewMin; + nPtRelMax = nNewMax; + nPtRelStep = nStep; + SetUnit(FieldUnit::POINT); +} + +void FontSizeBox::InsertValue(int i) +{ + OUString sNumber(OUString::number(i)); + m_xComboBox->append(sNumber, format_number(i)); +} + +void FontSizeBox::SetRelative( bool bNewRelative ) +{ + if ( !bRelativeMode ) + return; + + int nSelectionStart, nSelectionEnd; + m_xComboBox->get_entry_selection_bounds(nSelectionStart, nSelectionEnd); + OUString aStr = comphelper::string::stripStart(m_xComboBox->get_active_text(), ' '); + + if (bNewRelative) + { + bRelative = true; + bStdSize = false; + + m_xComboBox->clear(); + + if (bPtRelative) + { + SetDecimalDigits( 1 ); + SetRange(nPtRelMin, nPtRelMax); + SetUnit(FieldUnit::POINT); + + short i = nPtRelMin, n = 0; + // JP 30.06.98: more than 100 values are not useful + while ( i <= nPtRelMax && n++ < 100 ) + { + InsertValue( i ); + i = i + nPtRelStep; + } + } + else + { + SetDecimalDigits(0); + SetRange(nRelMin, nRelMax); + SetUnit(FieldUnit::PERCENT); + + sal_uInt16 i = nRelMin; + while ( i <= nRelMax ) + { + InsertValue( i ); + i = i + nRelStep; + } + } + } + else + { + if (pFontList) + m_xComboBox->clear(); + bRelative = bPtRelative = false; + SetDecimalDigits(1); + SetRange(20, 9999); + SetUnit(FieldUnit::POINT); + if ( pFontList) + Fill( &aFontMetric, pFontList ); + } + + set_active_or_entry_text(aStr); + m_xComboBox->select_entry_region(nSelectionStart, nSelectionEnd); +} + +OUString FontSizeBox::format_number(int nValue) const +{ + OUString sRet; + + //pawn percent off to icu to decide whether percent is separated from its number for this locale + if (eUnit == FieldUnit::PERCENT) + { + double fValue = nValue; + fValue /= weld::SpinButton::Power10(nDecimalDigits); + sRet = unicode::formatPercent(fValue, Application::GetSettings().GetUILanguageTag()); + } + else + { + const SvtSysLocale aSysLocale; + const LocaleDataWrapper& rLocaleData = aSysLocale.GetLocaleData(); + sRet = rLocaleData.getNum(nValue, nDecimalDigits, true, false); + if (eUnit != FieldUnit::NONE && eUnit != FieldUnit::DEGREE) + sRet += " "; + assert(eUnit != FieldUnit::PERCENT); + sRet += weld::MetricSpinButton::MetricToString(eUnit); + } + + if (bRelativeMode && bPtRelative && (0 <= nValue) && !sRet.isEmpty()) + sRet = "+" + sRet; + + return sRet; +} + +void FontSizeBox::SetValue(int nNewValue, FieldUnit eInUnit) +{ + auto nTempValue = vcl::ConvertValue(nNewValue, 0, GetDecimalDigits(), eInUnit, GetUnit()); + if (nTempValue < nMin) + nTempValue = nMin; + else if (nTempValue > nMax) + nTempValue = nMax; + if (!bRelative) + { + FontSizeNames aFontSizeNames(Application::GetSettings().GetUILanguageTag().getLanguageType()); + // conversion loses precision; however font sizes should + // never have a problem with that + OUString aName = aFontSizeNames.Size2Name(nTempValue); + if (!aName.isEmpty() && m_xComboBox->find_text(aName) != -1) + { + m_xComboBox->set_active_text(aName); + return; + } + } + OUString aResult = format_number(nTempValue); + set_active_or_entry_text(aResult); +} + +void FontSizeBox::set_value(int nNewValue) +{ + SetValue(nNewValue, eUnit); +} + +int FontSizeBox::get_value() const +{ + OUString aStr = m_xComboBox->get_active_text(); + if (!bRelative) + { + FontSizeNames aFontSizeNames(Application::GetSettings().GetUILanguageTag().getLanguageType()); + auto nValue = aFontSizeNames.Name2Size(aStr); + if (nValue) + return vcl::ConvertValue(nValue, 0, GetDecimalDigits(), GetUnit(), GetUnit()); + } + + const SvtSysLocale aSysLocale; + const LocaleDataWrapper& rLocaleData = aSysLocale.GetLocaleData(); + double fResult(0.0); + (void)vcl::TextToValue(aStr, fResult, 0, GetDecimalDigits(), rLocaleData, GetUnit()); + if (!aStr.isEmpty()) + { + if (fResult < nMin) + fResult = nMin; + else if (fResult > nMax) + fResult = nMax; + } + return fResult; +} + +SvxBorderLineStyle SvtLineListBox::GetSelectEntryStyle() const +{ + if (m_xLineSet->IsNoSelection()) + return SvxBorderLineStyle::NONE; + auto nId = m_xLineSet->GetSelectedItemId(); + return static_cast<SvxBorderLineStyle>(nId - 1); +} + +namespace +{ + Size getPreviewSize(const weld::Widget& rControl) + { + return Size(rControl.get_approximate_digit_width() * 15, rControl.get_text_height()); + } +} + +void SvtLineListBox::ImpGetLine( long nLine1, long nLine2, long nDistance, + Color aColor1, Color aColor2, Color aColorDist, + SvxBorderLineStyle nStyle, BitmapEx& rBmp ) +{ + Size aSize(getPreviewSize(*m_xControl)); + + // SourceUnit to Twips + if ( eSourceUnit == FieldUnit::POINT ) + { + nLine1 /= 5; + nLine2 /= 5; + nDistance /= 5; + } + + // Paint the lines + aSize = aVirDev->PixelToLogic( aSize ); + long nPix = aVirDev->PixelToLogic( Size( 0, 1 ) ).Height(); + sal_uInt32 n1 = nLine1; + sal_uInt32 n2 = nLine2; + long nDist = nDistance; + n1 += nPix-1; + n1 -= n1%nPix; + if ( n2 ) + { + nDist += nPix-1; + nDist -= nDist%nPix; + n2 += nPix-1; + n2 -= n2%nPix; + } + long nVirHeight = n1+nDist+n2; + if ( nVirHeight > aSize.Height() ) + aSize.setHeight( nVirHeight ); + // negative width should not be drawn + if ( aSize.Width() <= 0 ) + return; + + Size aVirSize = aVirDev->LogicToPixel( aSize ); + if ( aVirDev->GetOutputSizePixel() != aVirSize ) + aVirDev->SetOutputSizePixel( aVirSize ); + aVirDev->SetFillColor( aColorDist ); + aVirDev->DrawRect( tools::Rectangle( Point(), aSize ) ); + + aVirDev->SetFillColor( aColor1 ); + + double y1 = double( n1 ) / 2; + svtools::DrawLine( *aVirDev, basegfx::B2DPoint( 0, y1 ), basegfx::B2DPoint( aSize.Width( ), y1 ), n1, nStyle ); + + if ( n2 ) + { + double y2 = n1 + nDist + double( n2 ) / 2; + aVirDev->SetFillColor( aColor2 ); + svtools::DrawLine( *aVirDev, basegfx::B2DPoint( 0, y2 ), basegfx::B2DPoint( aSize.Width(), y2 ), n2, SvxBorderLineStyle::SOLID ); + } + rBmp = aVirDev->GetBitmapEx( Point(), Size( aSize.Width(), n1+nDist+n2 ) ); +} + +namespace +{ + OUString GetLineStyleName(SvxBorderLineStyle eStyle) + { + OUString sRet; + for (sal_uInt32 i = 0; i < SAL_N_ELEMENTS(RID_SVXSTR_BORDERLINE); ++i) + { + if (eStyle == RID_SVXSTR_BORDERLINE[i].second) + { + sRet = SvtResId(RID_SVXSTR_BORDERLINE[i].first); + break; + } + } + return sRet; + } +} + +SvtLineListBox::SvtLineListBox(std::unique_ptr<weld::MenuButton> pControl) + : m_xControl(std::move(pControl)) + , m_xBuilder(Application::CreateBuilder(m_xControl.get(), "svt/ui/linewindow.ui")) + , m_xTopLevel(m_xBuilder->weld_widget("line_popup_window")) + , m_xNoneButton(m_xBuilder->weld_button("none_line_button")) + , m_xLineSet(new ValueSet(nullptr)) + , m_xLineSetWin(new weld::CustomWeld(*m_xBuilder, "lineset", *m_xLineSet)) + , m_nWidth( 5 ) + , aVirDev(VclPtr<VirtualDevice>::Create()) + , aColor(COL_BLACK) + , maPaintCol(COL_BLACK) +{ + const StyleSettings& rStyleSettings = Application::GetSettings().GetStyleSettings(); + m_xLineSet->SetStyle(WinBits(WB_FLATVALUESET | WB_NO_DIRECTSELECT | WB_TABSTOP)); + m_xLineSet->SetItemHeight(rStyleSettings.GetListBoxPreviewDefaultPixelSize().Height() + 1); + m_xLineSet->SetColCount(1); + m_xLineSet->SetSelectHdl(LINK(this, SvtLineListBox, ValueSelectHdl)); + + m_xNoneButton->connect_clicked(LINK(this, SvtLineListBox, NoneHdl)); + + m_xTopLevel->connect_focus_in(LINK(this, SvtLineListBox, FocusHdl)); + m_xControl->set_popover(m_xTopLevel.get()); + m_xControl->connect_toggled(LINK(this, SvtLineListBox, ToggleHdl)); + + // lock size to these maxes height/width so it doesn't jump around in size + m_xControl->set_label(GetLineStyleName(SvxBorderLineStyle::NONE)); + Size aNonePrefSize = m_xControl->get_preferred_size(); + m_xControl->set_label(""); + aVirDev->SetOutputSizePixel(getPreviewSize(*m_xControl)); + m_xControl->set_image(aVirDev); + Size aSolidPrefSize = m_xControl->get_preferred_size(); + m_xControl->set_size_request(std::max(aNonePrefSize.Width(), aSolidPrefSize.Width()), + std::max(aNonePrefSize.Height(), aSolidPrefSize.Height())); + + eSourceUnit = FieldUnit::POINT; + + aVirDev->SetLineColor(); + aVirDev->SetMapMode(MapMode(MapUnit::MapTwip)); + + UpdatePaintLineColor(); +} + +IMPL_LINK_NOARG(SvtLineListBox, FocusHdl, weld::Widget&, void) +{ + if (GetSelectEntryStyle() == SvxBorderLineStyle::NONE) + m_xNoneButton->grab_focus(); + else + m_xLineSet->GrabFocus(); +} + +IMPL_LINK(SvtLineListBox, ToggleHdl, weld::ToggleButton&, rButton, void) +{ + if (rButton.get_active()) + FocusHdl(*m_xTopLevel); +} + +IMPL_LINK_NOARG(SvtLineListBox, NoneHdl, weld::Button&, void) +{ + SelectEntry(SvxBorderLineStyle::NONE); + ValueSelectHdl(nullptr); +} + +SvtLineListBox::~SvtLineListBox() +{ +} + +sal_Int32 SvtLineListBox::GetStylePos( sal_Int32 nListPos ) +{ + sal_Int32 nPos = -1; + --nListPos; + + sal_Int32 n = 0; + size_t i = 0; + size_t nCount = m_vLineList.size(); + while ( nPos == -1 && i < nCount ) + { + if ( nListPos == n ) + nPos = static_cast<sal_Int32>(i); + n++; + i++; + } + + return nPos; +} + +void SvtLineListBox::SelectEntry(SvxBorderLineStyle nStyle) +{ + if (nStyle == SvxBorderLineStyle::NONE) + m_xLineSet->SetNoSelection(); + else + m_xLineSet->SelectItem(static_cast<sal_Int16>(nStyle) + 1); + UpdatePreview(); +} + +void SvtLineListBox::InsertEntry( + const BorderWidthImpl& rWidthImpl, SvxBorderLineStyle nStyle, long nMinWidth, + ColorFunc pColor1Fn, ColorFunc pColor2Fn, ColorDistFunc pColorDistFn ) +{ + m_vLineList.emplace_back(new ImpLineListData( + rWidthImpl, nStyle, nMinWidth, pColor1Fn, pColor2Fn, pColorDistFn)); +} + +void SvtLineListBox::UpdatePaintLineColor() +{ + const StyleSettings& rSettings = Application::GetSettings().GetStyleSettings(); + Color aNewCol(rSettings.GetWindowColor().IsDark() ? rSettings.GetLabelTextColor() : aColor); + + bool bRet = aNewCol != maPaintCol; + + if( bRet ) + maPaintCol = aNewCol; +} + +void SvtLineListBox::UpdateEntries() +{ + UpdatePaintLineColor( ); + + SvxBorderLineStyle eSelected = GetSelectEntryStyle(); + + // Remove the old entries + m_xLineSet->Clear(); + + // Add the new entries based on the defined width + + sal_uInt16 n = 0; + sal_uInt16 nCount = m_vLineList.size( ); + while ( n < nCount ) + { + auto& pData = m_vLineList[ n ]; + BitmapEx aBmp; + ImpGetLine( pData->GetLine1ForWidth( m_nWidth ), + pData->GetLine2ForWidth( m_nWidth ), + pData->GetDistForWidth( m_nWidth ), + GetColorLine1(m_xLineSet->GetItemCount()), + GetColorLine2(m_xLineSet->GetItemCount()), + GetColorDist(m_xLineSet->GetItemCount()), + pData->GetStyle(), aBmp ); + sal_Int16 nItemId = static_cast<sal_Int16>(pData->GetStyle()) + 1; + m_xLineSet->InsertItem(nItemId, Image(aBmp), GetLineStyleName(pData->GetStyle())); + if (pData->GetStyle() == eSelected) + m_xLineSet->SelectItem(nItemId); + n++; + } + + m_xLineSet->SetOptimalSize(); +} + +Color SvtLineListBox::GetColorLine1( sal_Int32 nPos ) +{ + sal_Int32 nStyle = GetStylePos( nPos ); + if (nStyle == -1) + return GetPaintColor( ); + auto& pData = m_vLineList[ nStyle ]; + return pData->GetColorLine1( GetColor( ) ); +} + +Color SvtLineListBox::GetColorLine2( sal_Int32 nPos ) +{ + sal_Int32 nStyle = GetStylePos(nPos); + if (nStyle == -1) + return GetPaintColor( ); + auto& pData = m_vLineList[ nStyle ]; + return pData->GetColorLine2( GetColor( ) ); +} + +Color SvtLineListBox::GetColorDist( sal_Int32 nPos ) +{ + const StyleSettings& rSettings = Application::GetSettings().GetStyleSettings(); + Color rResult = rSettings.GetFieldColor(); + + sal_Int32 nStyle = GetStylePos( nPos ); + if (nStyle == -1) + return rResult; + auto& pData = m_vLineList[ nStyle ]; + return pData->GetColorDist( GetColor( ), rResult ); +} + +IMPL_LINK_NOARG(SvtLineListBox, ValueSelectHdl, ValueSet*, void) +{ + maSelectHdl.Call(*this); + UpdatePreview(); + if (m_xControl->get_active()) + m_xControl->set_active(false); +} + +void SvtLineListBox::UpdatePreview() +{ + SvxBorderLineStyle eStyle = GetSelectEntryStyle(); + for (sal_uInt32 i = 0; i < SAL_N_ELEMENTS(RID_SVXSTR_BORDERLINE); ++i) + { + if (eStyle == RID_SVXSTR_BORDERLINE[i].second) + { + m_xControl->set_label(SvtResId(RID_SVXSTR_BORDERLINE[i].first)); + break; + } + } + + if (eStyle == SvxBorderLineStyle::NONE) + { + m_xControl->set_image(nullptr); + m_xControl->set_label(GetLineStyleName(SvxBorderLineStyle::NONE)); + } + else + { + Image aImage(m_xLineSet->GetItemImage(m_xLineSet->GetSelectedItemId())); + m_xControl->set_label(""); + const auto nPos = (aVirDev->GetOutputSizePixel().Height() - aImage.GetSizePixel().Height()) / 2; + aVirDev->Push(PushFlags::MAPMODE); + aVirDev->SetMapMode(MapMode(MapUnit::MapPixel)); + aVirDev->Erase(); + aVirDev->DrawImage(Point(0, nPos), aImage); + m_xControl->set_image(aVirDev.get()); + aVirDev->Pop(); + } +} + +SvtCalendarBox::SvtCalendarBox(std::unique_ptr<weld::MenuButton> pControl) + : m_xControl(std::move(pControl)) + , m_xBuilder(Application::CreateBuilder(m_xControl.get(), "svt/ui/datewindow.ui")) + , m_xTopLevel(m_xBuilder->weld_widget("date_popup_window")) + , m_xCalendar(m_xBuilder->weld_calendar("date")) +{ + m_xControl->set_popover(m_xTopLevel.get()); + m_xCalendar->connect_selected(LINK(this, SvtCalendarBox, SelectHdl)); + m_xCalendar->connect_activated(LINK(this, SvtCalendarBox, ActivateHdl)); +} + +void SvtCalendarBox::set_date(const Date& rDate) +{ + m_xCalendar->set_date(rDate); + set_label_from_date(); +} + +void SvtCalendarBox::set_label_from_date() +{ + const LocaleDataWrapper& rLocaleData = Application::GetSettings().GetLocaleDataWrapper(); + m_xControl->set_label(rLocaleData.getDate(m_xCalendar->get_date())); +} + +IMPL_LINK_NOARG(SvtCalendarBox, SelectHdl, weld::Calendar&, void) +{ + set_label_from_date(); + m_aSelectHdl.Call(*this); +} + +IMPL_LINK_NOARG(SvtCalendarBox, ActivateHdl, weld::Calendar&, void) +{ + if (m_xControl->get_active()) + m_xControl->set_active(false); + m_aActivatedHdl.Call(*this); +} + +SvtCalendarBox::~SvtCalendarBox() +{ +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/control/ctrltool.cxx b/svtools/source/control/ctrltool.cxx new file mode 100644 index 000000000..cdd1aed8a --- /dev/null +++ b/svtools/source/control/ctrltool.cxx @@ -0,0 +1,890 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <memory> +#include <string.h> + +#include <tools/debug.hxx> +#include <tools/fract.hxx> +#include <i18nlangtag/languagetag.hxx> +#include <i18nlangtag/mslangid.hxx> +#include <vcl/outdev.hxx> +#include <vcl/svapp.hxx> +#include <vcl/settings.hxx> +#include <sal/macros.h> +#include <svtools/strings.hrc> +#include <svtools/svtresid.hxx> +#include <svtools/ctrltool.hxx> +#include <o3tl/typed_flags_set.hxx> +#include <comphelper/lok.hxx> + +// Standard fontsizes for scalable Fonts +const sal_IntPtr FontList::aStdSizeAry[] = +{ + 60, + 70, + 80, + 90, + 100, + 105, + 110, + 120, + 130, + 140, + 150, + 160, + 180, + 200, + 220, + 240, + 260, + 280, + 320, + 360, + 400, + 440, + 480, + 540, + 600, + 660, + 720, + 800, + 880, + 960, + 0 +}; + +namespace { + +class ImplFontListFontMetric : public FontMetric +{ + friend FontList; + +private: + VclPtr<OutputDevice> mpDevice; + ImplFontListFontMetric* mpNext; + +public: + ImplFontListFontMetric( const FontMetric& rInfo, + OutputDevice* pDev ) : + FontMetric( rInfo ), mpDevice(pDev), mpNext(nullptr) + { + } + + OutputDevice* GetDevice() const { return mpDevice; } +}; + +enum class FontListFontNameType +{ + NONE = 0x00, + PRINTER = 0x01, + SCREEN = 0x02, +}; + +} + +namespace o3tl +{ + template<> struct typed_flags<FontListFontNameType> : is_typed_flags<FontListFontNameType, 0x3> {}; +} + +class ImplFontListNameInfo +{ + friend class FontList; + +private: + OUString maSearchName; + ImplFontListFontMetric* mpFirst; + FontListFontNameType mnType; + + explicit ImplFontListNameInfo(const OUString& rSearchName) + : maSearchName(rSearchName) + , mpFirst(nullptr) + , mnType(FontListFontNameType::NONE) + { + } +}; + +//sort normal to the start +static int sortWeightValue(FontWeight eWeight) +{ + if (eWeight < WEIGHT_NORMAL) + return eWeight + 1; + if (eWeight > WEIGHT_NORMAL) + return eWeight - 1; + return 0; // eWeight == WEIGHT_NORMAL +} + +static sal_Int32 ImplCompareFontMetric( ImplFontListFontMetric* pInfo1, + ImplFontListFontMetric* pInfo2 ) +{ + //Sort non italic before italics + if ( pInfo1->GetItalic() < pInfo2->GetItalic() ) + return -1; + else if ( pInfo1->GetItalic() > pInfo2->GetItalic() ) + return 1; + + //Sort normal weight to the start, followed by lightest to heaviest weights + int nWeight1 = sortWeightValue(pInfo1->GetWeight()); + int nWeight2 = sortWeightValue(pInfo2->GetWeight()); + + if ( nWeight1 < nWeight2 ) + return -1; + else if ( nWeight1 > nWeight2 ) + return 1; + + return pInfo1->GetStyleName().compareTo( pInfo2->GetStyleName() ); +} + +static OUString ImplMakeSearchString(const OUString& rStr) +{ + return rStr.toAsciiLowerCase(); +} + +static OUString ImplMakeSearchStringFromName(const OUString& rStr) +{ + // check for features before alternate font separator + sal_Int32 nColon = rStr.indexOf(':'); + sal_Int32 nSemiColon = rStr.indexOf(';'); + if (nColon != -1 && (nSemiColon == -1 || nColon < nSemiColon)) + return ImplMakeSearchString(rStr.getToken( 0, ':' )); + return ImplMakeSearchString(rStr.getToken( 0, ';' )); +} + +ImplFontListNameInfo* FontList::ImplFind(const OUString& rSearchName, sal_uInt32* pIndex) const +{ + // Append if there is no entry in the list or if the entry is larger + // then the last one. We only compare to the last entry as the list of VCL + // is returned sorted, which increases the probability that appending + // is more likely + if (m_Entries.empty()) + { + if ( pIndex ) + *pIndex = SAL_MAX_UINT32; + return nullptr; + } + else + { + const ImplFontListNameInfo* pCmpData = m_Entries.back().get(); + sal_Int32 nComp = rSearchName.compareTo( pCmpData->maSearchName ); + if (nComp > 0) + { + if ( pIndex ) + *pIndex = SAL_MAX_UINT32; + return nullptr; + } + else if (nComp == 0) + return const_cast<ImplFontListNameInfo*>(pCmpData); + } + + // search fonts in the list + const ImplFontListNameInfo* pCompareData; + const ImplFontListNameInfo* pFoundData = nullptr; + size_t nLow = 0; + size_t nHigh = m_Entries.size() - 1; + size_t nMid; + + do + { + nMid = (nLow + nHigh) / 2; + pCompareData = m_Entries[nMid].get(); + sal_Int32 nComp = rSearchName.compareTo(pCompareData->maSearchName); + if (nComp < 0) + { + if ( !nMid ) + break; + nHigh = nMid-1; + } + else + { + if (nComp > 0) + nLow = nMid + 1; + else + { + pFoundData = pCompareData; + break; + } + } + } + while ( nLow <= nHigh ); + + if ( pIndex ) + { + sal_Int32 nComp = rSearchName.compareTo(pCompareData->maSearchName); + if (nComp > 0) + *pIndex = (nMid+1); + else + *pIndex = nMid; + } + + return const_cast<ImplFontListNameInfo*>(pFoundData); +} + +ImplFontListNameInfo* FontList::ImplFindByName(const OUString& rStr) const +{ + OUString aSearchName = ImplMakeSearchStringFromName(rStr); + return ImplFind( aSearchName, nullptr ); +} + +void FontList::ImplInsertFonts(OutputDevice* pDevice, bool bInsertData) +{ + rtl_TextEncoding eSystemEncoding = osl_getThreadTextEncoding(); + + FontListFontNameType nType; + if ( pDevice->GetOutDevType() != OUTDEV_PRINTER ) + nType = FontListFontNameType::SCREEN; + else + nType = FontListFontNameType::PRINTER; + + // inquire all fonts from the device + int n = pDevice->GetDevFontCount(); + if (n == 0 && comphelper::LibreOfficeKit::isActive()) + { + pDevice->RefreshFontData(true); + n = pDevice->GetDevFontCount(); + } + + for (int i = 0; i < n; ++i) + { + FontMetric aFontMetric = pDevice->GetDevFont( i ); + OUString aSearchName(aFontMetric.GetFamilyName()); + ImplFontListNameInfo* pData; + sal_uInt32 nIndex; + aSearchName = ImplMakeSearchString(aSearchName); + pData = ImplFind( aSearchName, &nIndex ); + + if ( !pData ) + { + if ( bInsertData ) + { + ImplFontListFontMetric* pNewInfo = new ImplFontListFontMetric( aFontMetric, pDevice ); + pData = new ImplFontListNameInfo( aSearchName ); + pData->mpFirst = pNewInfo; + pNewInfo->mpNext = nullptr; + + if (nIndex < static_cast<sal_uInt32>(m_Entries.size())) + m_Entries.insert(m_Entries.begin()+nIndex, + std::unique_ptr<ImplFontListNameInfo>(pData)); + else + m_Entries.push_back(std::unique_ptr<ImplFontListNameInfo>(pData)); + } + } + else + { + if ( bInsertData ) + { + bool bInsert = true; + ImplFontListFontMetric* pPrev = nullptr; + ImplFontListFontMetric* pTemp = pData->mpFirst; + ImplFontListFontMetric* pNewInfo = new ImplFontListFontMetric( aFontMetric, pDevice ); + while ( pTemp ) + { + sal_Int32 eComp = ImplCompareFontMetric( pNewInfo, pTemp ); + if ( eComp <= 0 ) + { + if ( eComp == 0 ) + { + // Overwrite charset, because charset should match + // with the system charset + if ( (pTemp->GetCharSet() != eSystemEncoding) && + (pNewInfo->GetCharSet() == eSystemEncoding) ) + { + ImplFontListFontMetric* pTemp2 = pTemp->mpNext; + *static_cast<FontMetric*>(pTemp) = *static_cast<FontMetric*>(pNewInfo); + pTemp->mpNext = pTemp2; + } + delete pNewInfo; + bInsert = false; + } + + break; + } + + pPrev = pTemp; + pTemp = pTemp->mpNext; + } + + if ( bInsert ) + { + pNewInfo->mpNext = pTemp; + if ( pPrev ) + pPrev->mpNext = pNewInfo; + else + pData->mpFirst = pNewInfo; + } + } + } + + if ( pData ) + pData->mnType |= nType; + } +} + +FontList::FontList(OutputDevice* pDevice, OutputDevice* pDevice2) +{ + // initialise variables + mpDev = pDevice; + mpDev2 = pDevice2; + + // store style names + maLight = SvtResId(STR_SVT_STYLE_LIGHT); + maLightItalic = SvtResId(STR_SVT_STYLE_LIGHT_ITALIC); + maNormal = SvtResId(STR_SVT_STYLE_NORMAL); + maNormalItalic = SvtResId(STR_SVT_STYLE_NORMAL_ITALIC); + maBold = SvtResId(STR_SVT_STYLE_BOLD); + maBoldItalic = SvtResId(STR_SVT_STYLE_BOLD_ITALIC); + maBlack = SvtResId(STR_SVT_STYLE_BLACK); + maBlackItalic = SvtResId(STR_SVT_STYLE_BLACK_ITALIC); + + ImplInsertFonts(pDevice, true); + + // if required compare to the screen fonts + // in order to map the duplicates to Equal + bool bCompareWindow = false; + if ( !pDevice2 && (pDevice->GetOutDevType() == OUTDEV_PRINTER) ) + { + bCompareWindow = true; + pDevice2 = Application::GetDefaultDevice(); + } + + if ( pDevice2 && + (pDevice2->GetOutDevType() != pDevice->GetOutDevType()) ) + ImplInsertFonts(pDevice2, !bCompareWindow); +} + +FontList::~FontList() +{ + // delete FontMetrics + ImplFontListFontMetric *pTemp, *pInfo; + for (auto const& it : m_Entries) + { + pInfo = it->mpFirst; + while ( pInfo ) + { + pTemp = pInfo->mpNext; + delete pInfo; + pInfo = pTemp; + } + } +} + +std::unique_ptr<FontList> FontList::Clone() const +{ + return std::unique_ptr<FontList>(new FontList(mpDev, mpDev2)); +} + +const OUString& FontList::GetStyleName(FontWeight eWeight, FontItalic eItalic) const +{ + if ( eWeight > WEIGHT_BOLD ) + { + if ( eItalic > ITALIC_NONE ) + return maBlackItalic; + else + return maBlack; + } + else if ( eWeight > WEIGHT_MEDIUM ) + { + if ( eItalic > ITALIC_NONE ) + return maBoldItalic; + else + return maBold; + } + else if ( eWeight > WEIGHT_LIGHT ) + { + if ( eItalic > ITALIC_NONE ) + return maNormalItalic; + else + return maNormal; + } + else if ( eWeight != WEIGHT_DONTKNOW ) + { + if ( eItalic > ITALIC_NONE ) + return maLightItalic; + else + return maLight; + } + else + { + if ( eItalic > ITALIC_NONE ) + return maNormalItalic; + else + return maNormal; + } +} + +OUString FontList::GetStyleName(const FontMetric& rInfo) const +{ + OUString aStyleName = rInfo.GetStyleName(); + FontWeight eWeight = rInfo.GetWeight(); + FontItalic eItalic = rInfo.GetItalic(); + + // return synthetic Name if no StyleName was set + if (aStyleName.isEmpty()) + aStyleName = GetStyleName(eWeight, eItalic); + else + { + // Translate StyleName to localized name + OUString aCompareStyleName = aStyleName.toAsciiLowerCase().replaceAll(" ", ""); + if (aCompareStyleName == "bold") + aStyleName = maBold; + else if (aCompareStyleName == "bolditalic") + aStyleName = maBoldItalic; + else if (aCompareStyleName == "italic") + aStyleName = maNormalItalic; + else if (aCompareStyleName == "standard") + aStyleName = maNormal; + else if (aCompareStyleName == "regular") + aStyleName = maNormal; + else if (aCompareStyleName == "medium") + aStyleName = maNormal; + else if (aCompareStyleName == "light") + aStyleName = maLight; + else if (aCompareStyleName == "lightitalic") + aStyleName = maLightItalic; + else if (aCompareStyleName == "black") + aStyleName = maBlack; + else if (aCompareStyleName == "blackitalic") + aStyleName = maBlackItalic; + /* tdf#107700 support some less common style names with localization */ + else if (aCompareStyleName == "book") + aStyleName = SvtResId(STR_SVT_STYLE_BOOK); + else if (aCompareStyleName == "boldoblique") + aStyleName = SvtResId(STR_SVT_STYLE_BOLD_OBLIQUE); + else if (aCompareStyleName == "condensed") + aStyleName = SvtResId(STR_SVT_STYLE_CONDENSED); + else if (aCompareStyleName == "condensedbold") + aStyleName = SvtResId(STR_SVT_STYLE_CONDENSED_BOLD); + else if (aCompareStyleName == "condensedbolditalic") + aStyleName = SvtResId(STR_SVT_STYLE_CONDENSED_BOLD_ITALIC); + else if (aCompareStyleName == "condensedboldoblique") + aStyleName = SvtResId(STR_SVT_STYLE_CONDENSED_BOLD_OBLIQUE); + else if (aCompareStyleName == "condenseditalic") + aStyleName = SvtResId(STR_SVT_STYLE_CONDENSED_ITALIC); + else if (aCompareStyleName == "condensedoblique") + aStyleName = SvtResId(STR_SVT_STYLE_CONDENSED_OBLIQUE); + else if (aCompareStyleName == "extralight") + aStyleName = SvtResId(STR_SVT_STYLE_EXTRALIGHT); + else if (aCompareStyleName == "extralightitalic") + aStyleName = SvtResId(STR_SVT_STYLE_EXTRALIGHT_ITALIC); + /* Medium is synonym with Normal */ + else if (aCompareStyleName == "mediumitalic") + aStyleName = maNormalItalic; + else if (aCompareStyleName == "oblique") + aStyleName = SvtResId(STR_SVT_STYLE_OBLIQUE); + else if (aCompareStyleName == "semibold") + aStyleName = SvtResId(STR_SVT_STYLE_SEMIBOLD); + else if (aCompareStyleName == "semibolditalic") + aStyleName = SvtResId(STR_SVT_STYLE_SEMIBOLD_ITALIC); + + // fix up StyleName, because the PS Printer driver from + // W2000 returns wrong StyleNames (e.g. Bold instead of Bold Italic + // for Helvetica) + if ( eItalic > ITALIC_NONE ) + { + if ( (aStyleName == maNormal) || + (aStyleName == maBold) || + (aStyleName == maLight) || + (aStyleName == maBlack) ) + aStyleName = GetStyleName( eWeight, eItalic ); + } + } + + return aStyleName; +} + +OUString FontList::GetFontMapText( const FontMetric& rInfo ) const +{ + if ( rInfo.GetFamilyName().isEmpty() ) + { + return OUString(); + } + + // Search Fontname + ImplFontListNameInfo* pData = ImplFindByName( rInfo.GetFamilyName() ); + if ( !pData ) + { + if (maMapNotAvailable.isEmpty()) + maMapNotAvailable = SvtResId(STR_SVT_FONTMAP_NOTAVAILABLE); + return maMapNotAvailable; + } + + // search for synthetic style + FontListFontNameType nType = pData->mnType; + const OUString& rStyleName = rInfo.GetStyleName(); + if (!rStyleName.isEmpty()) + { + bool bNotSynthetic = false; + FontWeight eWeight = rInfo.GetWeight(); + FontItalic eItalic = rInfo.GetItalic(); + ImplFontListFontMetric* pFontMetric = pData->mpFirst; + while ( pFontMetric ) + { + if ( (eWeight == pFontMetric->GetWeight()) && + (eItalic == pFontMetric->GetItalic()) ) + { + bNotSynthetic = true; + break; + } + + pFontMetric = pFontMetric->mpNext; + } + + if ( !bNotSynthetic ) + { + if (maMapStyleNotAvailable.isEmpty()) + const_cast<FontList*>(this)->maMapStyleNotAvailable = SvtResId(STR_SVT_FONTMAP_STYLENOTAVAILABLE); + return maMapStyleNotAvailable; + } + } + + // Only Printer-Font? + if ( nType == FontListFontNameType::PRINTER ) + { + if (maMapPrinterOnly.isEmpty()) + const_cast<FontList*>(this)->maMapPrinterOnly = SvtResId(STR_SVT_FONTMAP_PRINTERONLY); + return maMapPrinterOnly; + } + else + { + if (maMapBoth.isEmpty()) + const_cast<FontList*>(this)->maMapBoth = SvtResId(STR_SVT_FONTMAP_BOTH); + return maMapBoth; + } +} + +namespace +{ + FontMetric makeMissing(ImplFontListFontMetric const * pFontNameInfo, const OUString &rName, + FontWeight eWeight, FontItalic eItalic) + { + FontMetric aInfo; + // if the fontname matches, we copy as much as possible + if (pFontNameInfo) + { + aInfo = *pFontNameInfo; + aInfo.SetStyleName(OUString()); + } + + aInfo.SetWeight(eWeight); + aInfo.SetItalic(eItalic); + + //If this is a known but uninstalled symbol font which we can remap to + //OpenSymbol then toggle its charset to be a symbol font + if (ConvertChar::GetRecodeData(rName, "OpenSymbol")) + aInfo.SetCharSet(RTL_TEXTENCODING_SYMBOL); + + return aInfo; + } +} + +FontMetric FontList::Get(const OUString& rName, const OUString& rStyleName) const +{ + ImplFontListNameInfo* pData = ImplFindByName( rName ); + ImplFontListFontMetric* pFontMetric = nullptr; + ImplFontListFontMetric* pFontNameInfo = nullptr; + if ( pData ) + { + ImplFontListFontMetric* pSearchInfo = pData->mpFirst; + pFontNameInfo = pSearchInfo; + pSearchInfo = pData->mpFirst; + while ( pSearchInfo ) + { + if (rStyleName.equalsIgnoreAsciiCase(GetStyleName(*pSearchInfo))) + { + pFontMetric = pSearchInfo; + break; + } + + pSearchInfo = pSearchInfo->mpNext; + } + } + + // reproduce attributes if data could not be found + FontMetric aInfo; + if ( !pFontMetric ) + { + FontWeight eWeight = WEIGHT_DONTKNOW; + FontItalic eItalic = ITALIC_NONE; + + if ( rStyleName == maNormal ) + { + eItalic = ITALIC_NONE; + eWeight = WEIGHT_NORMAL; + } + else if ( rStyleName == maNormalItalic ) + { + eItalic = ITALIC_NORMAL; + eWeight = WEIGHT_NORMAL; + } + else if ( rStyleName == maBold ) + { + eItalic = ITALIC_NONE; + eWeight = WEIGHT_BOLD; + } + else if ( rStyleName == maBoldItalic ) + { + eItalic = ITALIC_NORMAL; + eWeight = WEIGHT_BOLD; + } + else if ( rStyleName == maLight ) + { + eItalic = ITALIC_NONE; + eWeight = WEIGHT_LIGHT; + } + else if ( rStyleName == maLightItalic ) + { + eItalic = ITALIC_NORMAL; + eWeight = WEIGHT_LIGHT; + } + else if ( rStyleName == maBlack ) + { + eItalic = ITALIC_NONE; + eWeight = WEIGHT_BLACK; + } + else if ( rStyleName == maBlackItalic ) + { + eItalic = ITALIC_NORMAL; + eWeight = WEIGHT_BLACK; + } + aInfo = makeMissing(pFontNameInfo, rName, eWeight, eItalic); + } + else + aInfo = *pFontMetric; + + // set Fontname to keep FontAlias + aInfo.SetFamilyName( rName ); + aInfo.SetStyleName( rStyleName ); + + return aInfo; +} + +FontMetric FontList::Get(const OUString& rName, + FontWeight eWeight, FontItalic eItalic) const +{ + ImplFontListNameInfo* pData = ImplFindByName( rName ); + ImplFontListFontMetric* pFontMetric = nullptr; + ImplFontListFontMetric* pFontNameInfo = nullptr; + if ( pData ) + { + ImplFontListFontMetric* pSearchInfo = pData->mpFirst; + pFontNameInfo = pSearchInfo; + while ( pSearchInfo ) + { + if ( (eWeight == pSearchInfo->GetWeight()) && + (eItalic == pSearchInfo->GetItalic()) ) + { + pFontMetric = pSearchInfo; + break; + } + + pSearchInfo = pSearchInfo->mpNext; + } + } + + // reproduce attributes if data could not be found + FontMetric aInfo; + if ( !pFontMetric ) + aInfo = makeMissing(pFontNameInfo, rName, eWeight, eItalic); + else + aInfo = *pFontMetric; + + // set Fontname to keep FontAlias + aInfo.SetFamilyName( rName ); + + return aInfo; +} + +bool FontList::IsAvailable(const OUString& rName) const +{ + return (ImplFindByName( rName ) != nullptr); +} + +const FontMetric& FontList::GetFontName(size_t const nFont) const +{ + DBG_ASSERT( nFont < GetFontNameCount(), "FontList::GetFontName(): nFont >= Count" ); + + return *(m_Entries[nFont]->mpFirst); +} + +sal_Handle FontList::GetFirstFontMetric(const OUString& rName) const +{ + ImplFontListNameInfo* pData = ImplFindByName( rName ); + if ( !pData ) + return nullptr; + else + return static_cast<sal_Handle>(pData->mpFirst); +} + +sal_Handle FontList::GetNextFontMetric( sal_Handle hFontMetric ) +{ + ImplFontListFontMetric* pInfo = static_cast<ImplFontListFontMetric*>(hFontMetric); + return static_cast<sal_Handle>(pInfo->mpNext); +} + +const FontMetric& FontList::GetFontMetric( sal_Handle hFontMetric ) +{ + ImplFontListFontMetric* pInfo = static_cast<ImplFontListFontMetric*>(hFontMetric); + return *pInfo; +} + +const sal_IntPtr* FontList::GetSizeAry( const FontMetric& rInfo ) const +{ + // first delete Size-Array + mpSizeAry.reset(); + + // use standard sizes if no name + if ( rInfo.GetFamilyName().isEmpty() ) + return aStdSizeAry; + + // first search fontname in order to use device from the matching font + OutputDevice* pDevice = mpDev; + ImplFontListNameInfo* pData = ImplFindByName( rInfo.GetFamilyName() ); + if ( pData ) + pDevice = pData->mpFirst->GetDevice(); + + int nDevSizeCount = pDevice->GetDevFontSizeCount( rInfo ); + if ( !nDevSizeCount || + (pDevice->GetDevFontSize( rInfo, 0 ).Height() == 0) ) + return aStdSizeAry; + + MapMode aOldMapMode = pDevice->GetMapMode(); + MapMode aMap( MapUnit::Map10thInch, Point(), Fraction( 1, 72 ), Fraction( 1, 72 ) ); + pDevice->SetMapMode( aMap ); + + int nRealCount = 0; + long nOldHeight = 0; + mpSizeAry.reset(new sal_IntPtr[nDevSizeCount+1] ); + for (int i = 0; i < nDevSizeCount; ++i) + { + Size aSize = pDevice->GetDevFontSize( rInfo, i ); + if ( aSize.Height() != nOldHeight ) + { + nOldHeight = aSize.Height(); + mpSizeAry[nRealCount] = nOldHeight; + nRealCount++; + } + } + mpSizeAry[nRealCount] = 0; + + pDevice->SetMapMode( aOldMapMode ); + return mpSizeAry.get(); +} + +struct ImplFSNameItem +{ + sal_Int32 mnSize; + const char* mszUtf8Name; +}; + +static const ImplFSNameItem aImplSimplifiedChinese[] = +{ + { 50, "\xe5\x85\xab\xe5\x8f\xb7" }, + { 55, "\xe4\xb8\x83\xe5\x8f\xb7" }, + { 65, "\xe5\xb0\x8f\xe5\x85\xad" }, + { 75, "\xe5\x85\xad\xe5\x8f\xb7" }, + { 90, "\xe5\xb0\x8f\xe4\xba\x94" }, + { 105, "\xe4\xba\x94\xe5\x8f\xb7" }, + { 120, "\xe5\xb0\x8f\xe5\x9b\x9b" }, + { 140, "\xe5\x9b\x9b\xe5\x8f\xb7" }, + { 150, "\xe5\xb0\x8f\xe4\xb8\x89" }, + { 160, "\xe4\xb8\x89\xe5\x8f\xb7" }, + { 180, "\xe5\xb0\x8f\xe4\xba\x8c" }, + { 220, "\xe4\xba\x8c\xe5\x8f\xb7" }, + { 240, "\xe5\xb0\x8f\xe4\xb8\x80" }, + { 260, "\xe4\xb8\x80\xe5\x8f\xb7" }, + { 360, "\xe5\xb0\x8f\xe5\x88\x9d" }, + { 420, "\xe5\x88\x9d\xe5\x8f\xb7" } +}; + +FontSizeNames::FontSizeNames( LanguageType eLanguage ) +{ + if ( eLanguage == LANGUAGE_DONTKNOW ) + eLanguage = Application::GetSettings().GetUILanguageTag().getLanguageType(); + if ( eLanguage == LANGUAGE_SYSTEM ) + eLanguage = MsLangId::getSystemUILanguage(); + + if (MsLangId::isSimplifiedChinese(eLanguage)) + { + // equivalent for traditional chinese disabled by popular request, #i89077# + mpArray = aImplSimplifiedChinese; + mnElem = SAL_N_ELEMENTS(aImplSimplifiedChinese); + } + else + { + mpArray = nullptr; + mnElem = 0; + } +} + +sal_Int32 FontSizeNames::Name2Size( const OUString& rName ) const +{ + if ( mnElem ) + { + OString aName(OUStringToOString(rName, + RTL_TEXTENCODING_UTF8)); + + // linear search is sufficient for this rare case + for( long i = mnElem; --i >= 0; ) + if ( aName == mpArray[i].mszUtf8Name ) + return mpArray[i].mnSize; + } + + return 0; +} + +OUString FontSizeNames::Size2Name( sal_Int32 nValue ) const +{ + OUString aStr; + + // binary search + for( long lower = 0, upper = mnElem - 1; lower <= upper; ) + { + long mid = (upper + lower) >> 1; + if ( nValue == mpArray[mid].mnSize ) + { + aStr = OUString( mpArray[mid].mszUtf8Name, strlen(mpArray[mid].mszUtf8Name), RTL_TEXTENCODING_UTF8 ); + break; + } + else if ( nValue < mpArray[mid].mnSize ) + upper = mid - 1; + else /* ( nValue > mpArray[mid].mnSize ) */ + lower = mid + 1; + } + + return aStr; +} + +OUString FontSizeNames::GetIndexName( sal_Int32 nIndex ) const +{ + OUString aStr; + + if ( nIndex < mnElem ) + aStr = OUString( mpArray[nIndex].mszUtf8Name, strlen(mpArray[nIndex].mszUtf8Name), RTL_TEXTENCODING_UTF8 ); + + return aStr; +} + +sal_Int32 FontSizeNames::GetIndexSize( sal_Int32 nIndex ) const +{ + if ( nIndex >= mnElem ) + return 0; + return mpArray[nIndex].mnSize; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/control/indexentryres.cxx b/svtools/source/control/indexentryres.cxx new file mode 100644 index 000000000..9420a37b2 --- /dev/null +++ b/svtools/source/control/indexentryres.cxx @@ -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 . + */ + + +#include <svtools/svtresid.hxx> +#include <svtools/strings.hrc> +#include <svtools/indexentryres.hxx> + +// implementation of the indexentry-algorithm-name translation +IndexEntryResource::IndexEntryResource() +{ + m_aData.emplace_back("alphanumeric", SvtResId(STR_SVT_INDEXENTRY_ALPHANUMERIC)); + m_aData.emplace_back("dict", SvtResId(STR_SVT_INDEXENTRY_DICTIONARY)); + m_aData.emplace_back("pinyin", SvtResId(STR_SVT_INDEXENTRY_PINYIN)); + m_aData.emplace_back("radical", SvtResId(STR_SVT_INDEXENTRY_RADICAL)); + m_aData.emplace_back("stroke", SvtResId(STR_SVT_INDEXENTRY_STROKE)); + m_aData.emplace_back("zhuyin", SvtResId(STR_SVT_INDEXENTRY_ZHUYIN)); + m_aData.emplace_back("phonetic (alphanumeric first) (grouped by syllable)", SvtResId(STR_SVT_INDEXENTRY_PHONETIC_FS)); + m_aData.emplace_back("phonetic (alphanumeric first) (grouped by consonant)", SvtResId(STR_SVT_INDEXENTRY_PHONETIC_FC)); + m_aData.emplace_back("phonetic (alphanumeric last) (grouped by syllable)", SvtResId(STR_SVT_INDEXENTRY_PHONETIC_LS)); + m_aData.emplace_back("phonetic (alphanumeric last) (grouped by consonant)", SvtResId(STR_SVT_INDEXENTRY_PHONETIC_LC)); +} + +const OUString& IndexEntryResource::GetTranslation(const OUString &r_Algorithm) +{ + sal_Int32 nIndex = r_Algorithm.indexOf('.'); + OUString aLocaleFreeAlgorithm; + + if (nIndex == -1) + aLocaleFreeAlgorithm = r_Algorithm; + else { + nIndex += 1; + aLocaleFreeAlgorithm = r_Algorithm.copy(nIndex); + } + + for (size_t i = 0; i < m_aData.size(); ++i) + if (aLocaleFreeAlgorithm == m_aData[i].GetAlgorithm()) + return m_aData[i].GetTranslation(); + return r_Algorithm; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/control/inettbc.cxx b/svtools/source/control/inettbc.cxx new file mode 100644 index 000000000..9fcb473cc --- /dev/null +++ b/svtools/source/control/inettbc.cxx @@ -0,0 +1,1144 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifdef UNX +#include <pwd.h> +#endif + +#include <svtools/inettbc.hxx> +#include <tools/diagnose_ex.h> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Reference.hxx> +#include <com/sun/star/beans/Property.hpp> +#include <com/sun/star/beans/PropertyValue.hpp> +#include <com/sun/star/sdbc/XResultSet.hpp> +#include <com/sun/star/sdbc/XRow.hpp> +#include <com/sun/star/task/XInteractionHandler.hpp> +#include <com/sun/star/ucb/NumberedSortingInfo.hpp> +#include <com/sun/star/ucb/UniversalContentBroker.hpp> +#include <com/sun/star/ucb/XAnyCompareFactory.hpp> +#include <com/sun/star/ucb/XCommandProcessor2.hpp> +#include <com/sun/star/ucb/XProgressHandler.hpp> +#include <com/sun/star/ucb/XContentAccess.hpp> +#include <com/sun/star/ucb/SortedDynamicResultSetFactory.hpp> +#include <comphelper/processfactory.hxx> +#include <comphelper/string.hxx> +#include <rtl/instance.hxx> +#include <salhelper/thread.hxx> +#include <tools/debug.hxx> +#include <osl/file.hxx> +#include <osl/mutex.hxx> +#include <vcl/event.hxx> +#include <vcl/svapp.hxx> +#include <unotools/historyoptions.hxx> +#include <unotools/pathoptions.hxx> +#include <ucbhelper/commandenvironment.hxx> +#include <ucbhelper/content.hxx> +#include <unotools/ucbhelper.hxx> +#include <svtools/asynclink.hxx> +#include <svtools/urlfilter.hxx> + +#include <vector> +#include <algorithm> + +using namespace ::ucbhelper; +using namespace ::utl; +using namespace ::com::sun::star; +using namespace ::com::sun::star::beans; +using namespace ::com::sun::star::lang; +using namespace ::com::sun::star::sdbc; +using namespace ::com::sun::star::task; +using namespace ::com::sun::star::ucb; +using namespace ::com::sun::star::uno; + +class SvtURLBox_Impl +{ +public: + std::vector<OUString> aURLs; + std::vector<OUString> aCompletions; + std::vector<WildCard> m_aFilters; + + static bool TildeParsing( OUString& aText, OUString& aBaseUrl ); + + SvtURLBox_Impl( ) + { + FilterMatch::createWildCardFilterList(OUString(),m_aFilters); + } +}; + +class SvtMatchContext_Impl: public salhelper::Thread +{ + static ::osl::Mutex* pDirMutex; + + std::vector<OUString> aPickList; + std::vector<OUString> aCompletions; + std::vector<OUString> aURLs; + svtools::AsynchronLink aLink; + OUString aText; + SvtURLBox* pBox; + bool bOnlyDirectories; + bool bNoSelection; + + osl::Mutex mutex_; + bool stopped_; + css::uno::Reference< css::ucb::XCommandProcessor > processor_; + sal_Int32 commandId_; + + DECL_LINK( Select_Impl, void*, void ); + + virtual ~SvtMatchContext_Impl() override; + virtual void execute() override; + void doExecute(); + void Insert( const OUString& rCompletion, const OUString& rURL, bool bForce = false); + void ReadFolder( const OUString& rURL, const OUString& rMatch, bool bSmart ); + static void FillPicklist(std::vector<OUString>& rPickList); + +public: + SvtMatchContext_Impl( SvtURLBox* pBoxP, const OUString& rText ); + void Stop(); +}; + + +namespace +{ + struct theSvtMatchContextMutex + : public rtl::Static< ::osl::Mutex, theSvtMatchContextMutex > {}; +} + +SvtMatchContext_Impl::SvtMatchContext_Impl(SvtURLBox* pBoxP, const OUString& rText) + : Thread( "MatchContext_Impl" ) + , aLink( LINK( this, SvtMatchContext_Impl, Select_Impl ) ) + , aText( rText ) + , pBox( pBoxP ) + , bOnlyDirectories( pBoxP->bOnlyDirectories ) + , bNoSelection( pBoxP->bNoSelection ) + , stopped_(false) + , commandId_(0) +{ + aLink.CreateMutex(); + + FillPicklist( aPickList ); +} + +SvtMatchContext_Impl::~SvtMatchContext_Impl() +{ + aLink.ClearPendingCall(); +} + +void SvtMatchContext_Impl::FillPicklist(std::vector<OUString>& rPickList) +{ + // Read the history of picks + Sequence< Sequence< PropertyValue > > seqPicklist = SvtHistoryOptions().GetList( ePICKLIST ); + sal_uInt32 nCount = seqPicklist.getLength(); + + for( sal_uInt32 nItem=0; nItem < nCount; nItem++ ) + { + Sequence< PropertyValue > seqPropertySet = seqPicklist[ nItem ]; + + auto pProperty = std::find_if(seqPropertySet.begin(), seqPropertySet.end(), + [](const PropertyValue& rProperty) { return rProperty.Name == HISTORY_PROPERTYNAME_TITLE; }); + if (pProperty != seqPropertySet.end()) + { + OUString sTitle; + INetURLObject aURL; + + pProperty->Value >>= sTitle; + aURL.SetURL( sTitle ); + rPickList.insert(rPickList.begin() + nItem, aURL.GetMainURL(INetURLObject::DecodeMechanism::WithCharset)); + } + } +} + +void SvtMatchContext_Impl::Stop() +{ + css::uno::Reference< css::ucb::XCommandProcessor > proc; + sal_Int32 id(0); + { + osl::MutexGuard g(mutex_); + if (!stopped_) { + stopped_ = true; + proc = processor_; + id = commandId_; + } + } + if (proc.is()) { + proc->abort(id); + } + terminate(); +} + +void SvtMatchContext_Impl::execute( ) +{ + doExecute(); + aLink.Call( this ); +} + + +// This method is called via AsynchronLink, so it has the SolarMutex and +// calling solar code ( VCL ... ) is safe. It is called when the thread is +// terminated ( finished work or stopped ). Cancelling the thread via +// Cancellable does not discard the information gained so far, it +// inserts all collected completions into the listbox. + +IMPL_LINK_NOARG( SvtMatchContext_Impl, Select_Impl, void*, void ) +{ + // avoid recursion through cancel button + { + osl::MutexGuard g(mutex_); + if (stopped_) { + // Completion was stopped, no display: + return; + } + } + + // insert all completed strings into the listbox + pBox->clear(); + + for (auto const& completion : aCompletions) + { + // convert the file into a URL + OUString sURL; + osl::FileBase::getFileURLFromSystemPath(completion, sURL); + // note: if this doesn't work, we're not interested in: we're checking the + // untouched sCompletion then + + if ( !sURL.isEmpty() && !sURL.endsWith("/") ) + { + OUString sUpperURL( sURL.toAsciiUpperCase() ); + + if ( ::std::none_of( pBox->pImpl->m_aFilters.begin(), + pBox->pImpl->m_aFilters.end(), + FilterMatch( sUpperURL ) ) ) + { // this URL is not allowed + continue; + } + } + + pBox->append_text(completion); + } + + pBox->EnableAutocomplete(!bNoSelection); + + // transfer string lists to listbox and forget them + pBox->pImpl->aURLs = aURLs; + pBox->pImpl->aCompletions = aCompletions; + aURLs.clear(); + aCompletions.clear(); + + // the box has this control as a member so we have to set that member + // to zero before deleting ourself. + pBox->pCtx.clear(); +} + +void SvtMatchContext_Impl::Insert( const OUString& rCompletion, + const OUString& rURL, + bool bForce ) +{ + if( !bForce ) + { + // avoid doubles + if(find(aCompletions.begin(), aCompletions.end(), rCompletion) != aCompletions.end()) + return; + } + + aCompletions.push_back(rCompletion); + aURLs.push_back(rURL); +} + + +void SvtMatchContext_Impl::ReadFolder( const OUString& rURL, + const OUString& rMatch, + bool bSmart ) +{ + // check folder to scan + if( !UCBContentHelper::IsFolder( rURL ) ) + return; + + bool bPureHomePath = false; +#ifdef UNX + bPureHomePath = aText.startsWith( "~" ) && aText.indexOf( '/' ) == -1; +#endif + + bool bExectMatch = bPureHomePath + || aText == "." + || aText.endsWith("/.") + || aText.endsWith("/.."); + + // for pure home paths ( ~username ) the '.' at the end of rMatch + // means that it points to root catalog + // this is done only for file contents since home paths parsing is useful only for them + if ( bPureHomePath && rMatch == "file:///." ) + { + // a home that refers to / + + OUString aNewText = aText + "/"; + Insert( aNewText, rURL, true ); + + return; + } + + // string to match with + INetURLObject aMatchObj( rMatch ); + OUString aMatchName; + + if ( rURL != aMatchObj.GetMainURL( INetURLObject::DecodeMechanism::NONE ) ) + { + aMatchName = aMatchObj.getName( INetURLObject::LAST_SEGMENT, true, INetURLObject::DecodeMechanism::WithCharset ); + + // matching is always done case insensitive, but completion will be case sensitive and case preserving + aMatchName = aMatchName.toAsciiLowerCase(); + + // if the matchstring ends with a slash, we must search for this also + if ( rMatch.endsWith("/") ) + aMatchName += "/"; + } + + sal_Int32 nMatchLen = aMatchName.getLength(); + + INetURLObject aFolderObj( rURL ); + DBG_ASSERT( aFolderObj.GetProtocol() != INetProtocol::NotValid, "Invalid URL!" ); + + try + { + Content aCnt( aFolderObj.GetMainURL( INetURLObject::DecodeMechanism::NONE ), + new ::ucbhelper::CommandEnvironment( uno::Reference< XInteractionHandler >(), + uno::Reference< XProgressHandler >() ), + comphelper::getProcessComponentContext() ); + uno::Reference< XResultSet > xResultSet; + Sequence< OUString > aProps(2); + OUString* pProps = aProps.getArray(); + pProps[0] = "Title"; + pProps[1] = "IsFolder"; + + try + { + ResultSetInclude eInclude = INCLUDE_FOLDERS_AND_DOCUMENTS; + if ( bOnlyDirectories ) + eInclude = INCLUDE_FOLDERS_ONLY; + uno::Reference< XDynamicResultSet > xDynResultSet = aCnt.createDynamicCursor( aProps, eInclude ); + + uno::Reference < XAnyCompareFactory > xCompare; + uno::Reference < XSortedDynamicResultSetFactory > xSRSFac = + SortedDynamicResultSetFactory::create( ::comphelper::getProcessComponentContext() ); + + Sequence< NumberedSortingInfo > aSortInfo( 2 ); + NumberedSortingInfo* pInfo = aSortInfo.getArray(); + pInfo[ 0 ].ColumnIndex = 2; + pInfo[ 0 ].Ascending = false; + pInfo[ 1 ].ColumnIndex = 1; + pInfo[ 1 ].Ascending = true; + + uno::Reference< XDynamicResultSet > xDynamicResultSet = + xSRSFac->createSortedDynamicResultSet( xDynResultSet, aSortInfo, xCompare ); + + if ( xDynamicResultSet.is() ) + { + xResultSet = xDynamicResultSet->getStaticResultSet(); + } + } + catch( css::uno::Exception& ) {} + + if ( xResultSet.is() ) + { + uno::Reference< XRow > xRow( xResultSet, UNO_QUERY ); + uno::Reference< XContentAccess > xContentAccess( xResultSet, UNO_QUERY ); + + try + { + while ( schedule() && xResultSet->next() ) + { + OUString aURL = xContentAccess->queryContentIdentifierString(); + OUString aTitle = xRow->getString(1); + bool bIsFolder = xRow->getBoolean(2); + + // matching is always done case insensitive, but completion will be case sensitive and case preserving + aTitle = aTitle.toAsciiLowerCase(); + + if ( + !nMatchLen || + (bExectMatch && aMatchName == aTitle) || + (!bExectMatch && aTitle.startsWith(aMatchName)) + ) + { + // all names fit if matchstring is empty + INetURLObject aObj( aURL ); + sal_Unicode aDelimiter = '/'; + if ( bSmart ) + // when parsing is done "smart", the delimiter must be "guessed" + aObj.getFSysPath( static_cast<FSysStyle>(FSysStyle::Detect & ~FSysStyle::Vos), &aDelimiter ); + + if ( bIsFolder ) + aObj.setFinalSlash(); + + // get the last name of the URL + OUString aMatch = aObj.getName( INetURLObject::LAST_SEGMENT, true, INetURLObject::DecodeMechanism::WithCharset ); + OUString aInput( aText ); + if ( nMatchLen ) + { + if (aText.endsWith(".") || bPureHomePath) + { + // if a "special folder" URL was typed, don't touch the user input + aMatch = aMatch.copy( nMatchLen ); + } + else + { + // make the user input case preserving + DBG_ASSERT( aInput.getLength() >= nMatchLen, "Suspicious Matching!" ); + aInput = aInput.copy( 0, aInput.getLength() - nMatchLen ); + } + } + + aInput += aMatch; + + // folders should get a final slash automatically + if ( bIsFolder ) + aInput += OUStringChar(aDelimiter); + + Insert( aInput, aObj.GetMainURL( INetURLObject::DecodeMechanism::NONE ), true ); + } + } + } + catch( css::uno::Exception& ) + { + } + } + } + catch( css::uno::Exception& ) + { + } +} + +void SvtMatchContext_Impl::doExecute() +{ + ::osl::MutexGuard aGuard( theSvtMatchContextMutex::get() ); + { + // have we been stopped while we were waiting for the mutex? + osl::MutexGuard g(mutex_); + if (stopped_) { + return; + } + } + + // Reset match lists + aCompletions.clear(); + aURLs.clear(); + + // check for input + if ( aText.isEmpty() ) + return; + + if( aText.indexOf( '*' ) != -1 || aText.indexOf( '?' ) != -1 ) + // no autocompletion for wildcards + return; + + OUString aMatch; + INetProtocol eProt = INetURLObject::CompareProtocolScheme( aText ); + INetProtocol eBaseProt = INetURLObject::CompareProtocolScheme( pBox->aBaseURL ); + if ( pBox->aBaseURL.isEmpty() ) + eBaseProt = INetURLObject::CompareProtocolScheme( SvtPathOptions().GetWorkPath() ); + INetProtocol eSmartProt = pBox->GetSmartProtocol(); + + // if the user input is a valid URL, go on with it + // otherwise it could be parsed smart with a predefined smart protocol + // ( or if this is not set with the protocol of a predefined base URL ) + if( eProt == INetProtocol::NotValid || eProt == eSmartProt || (eSmartProt == INetProtocol::NotValid && eProt == eBaseProt) ) + { + // not stopped yet ? + if( schedule() ) + { + if ( eProt == INetProtocol::NotValid ) + aMatch = SvtURLBox::ParseSmart( aText, pBox->aBaseURL ); + else + aMatch = aText; + if ( !aMatch.isEmpty() ) + { + INetURLObject aURLObject( aMatch ); + OUString aMainURL( aURLObject.GetMainURL( INetURLObject::DecodeMechanism::NONE ) ); + // Disable autocompletion for anything but the (local) file + // system (for which access is hopefully fast), as the logic of + // how SvtMatchContext_Impl is used requires this code to run to + // completion before further user input is processed, and even + // SvtMatchContext_Impl::Stop does not guarantee a speedy + // return: + if ( !aMainURL.isEmpty() + && aURLObject.GetProtocol() == INetProtocol::File ) + { + // if text input is a directory, it must be part of the match list! Until then it is scanned + bool folder = false; + if (aURLObject.hasFinalSlash()) { + try { + css::uno::Reference< css::uno::XComponentContext > + ctx(comphelper::getProcessComponentContext()); + css::uno::Reference< + css::ucb::XUniversalContentBroker > ucb( + css::ucb::UniversalContentBroker::create( + ctx)); + css::uno::Sequence< css::beans::Property > prop(1); + prop[0].Name = "IsFolder"; + prop[0].Handle = -1; + prop[0].Type = cppu::UnoType< bool >::get(); + css::uno::Any res; + css::uno::Reference< css::ucb::XCommandProcessor > + proc( + ucb->queryContent( + ucb->createContentIdentifier(aMainURL)), + css::uno::UNO_QUERY_THROW); + css::uno::Reference< css::ucb::XCommandProcessor2 > + proc2(proc, css::uno::UNO_QUERY); + sal_Int32 id = proc->createCommandIdentifier(); + try { + { + osl::MutexGuard g(mutex_); + processor_ = proc; + commandId_ = id; + } + res = proc->execute( + css::ucb::Command( + "getPropertyValues", -1, + css::uno::makeAny(prop)), + id, + css::uno::Reference< + css::ucb::XCommandEnvironment >()); + } catch (...) { + if (proc2.is()) { + try { + proc2->releaseCommandIdentifier(id); + } catch (css::uno::RuntimeException &) { + TOOLS_WARN_EXCEPTION("svtools.control", "ignoring"); + } + } + throw; + } + if (proc2.is()) { + proc2->releaseCommandIdentifier(id); + } + { + osl::MutexGuard g(mutex_); + processor_.clear(); + // At least the neon-based WebDAV UCP does not + // properly support aborting commands, so return + // anyway now if an abort request had been + // ignored and the command execution only + // returned "successfully" after some timeout: + if (stopped_) { + return; + } + } + css::uno::Reference< css::sdbc::XRow > row( + res, css::uno::UNO_QUERY_THROW); + folder = row->getBoolean(1) && !row->wasNull(); + } catch (css::uno::Exception &) { + TOOLS_WARN_EXCEPTION("svtools.control", "ignoring"); + return; + } + } + if (folder) + Insert( aText, aMatch ); + else + // otherwise the parent folder will be taken + aURLObject.removeSegment(); + + // scan directory and insert all matches + ReadFolder( aURLObject.GetMainURL( INetURLObject::DecodeMechanism::NONE ), aMatch, eProt == INetProtocol::NotValid ); + } + } + } + } + + if ( bOnlyDirectories ) + // don't scan history picklist if only directories are allowed, picklist contains only files + return; + + bool bFull = false; + + INetURLObject aCurObj; + OUString aCurString, aCurMainURL; + INetURLObject aObj; + aObj.SetSmartProtocol( eSmartProt == INetProtocol::NotValid ? INetProtocol::Http : eSmartProt ); + for( ;; ) + { + for(const auto& rPick : aPickList) + { + if (!schedule()) + break; + + aCurObj.SetURL(rPick); + aCurObj.SetSmartURL( aCurObj.GetURLNoPass()); + aCurMainURL = aCurObj.GetMainURL( INetURLObject::DecodeMechanism::NONE ); + + if( eProt != INetProtocol::NotValid && aCurObj.GetProtocol() != eProt ) + continue; + + if( eSmartProt != INetProtocol::NotValid && aCurObj.GetProtocol() != eSmartProt ) + continue; + + switch( aCurObj.GetProtocol() ) + { + case INetProtocol::Http: + case INetProtocol::Https: + case INetProtocol::Ftp: + { + if( eProt == INetProtocol::NotValid && !bFull ) + { + aObj.SetSmartURL( aText ); + if( aObj.GetURLPath().getLength() > 1 ) + continue; + } + + aCurString = aCurMainURL; + if( eProt == INetProtocol::NotValid ) + { + // try if text matches the scheme + OUString aScheme( INetURLObject::GetScheme( aCurObj.GetProtocol() ) ); + if ( aScheme.startsWithIgnoreAsciiCase( aText ) && aText.getLength() < aScheme.getLength() ) + { + if( bFull ) + aMatch = aCurObj.GetMainURL( INetURLObject::DecodeMechanism::NONE ); + else + { + aCurObj.SetMark( "" ); + aCurObj.SetParam( "" ); + aCurObj.SetURLPath( "" ); + aMatch = aCurObj.GetMainURL( INetURLObject::DecodeMechanism::NONE ); + } + + Insert( aMatch, aMatch ); + } + + // now try smart matching + aCurString = aCurString.copy( aScheme.getLength() ); + } + + if( aCurString.startsWithIgnoreAsciiCase( aText ) ) + { + if( bFull ) + aMatch = aCurObj.GetMainURL( INetURLObject::DecodeMechanism::NONE ); + else + { + aCurObj.SetMark( "" ); + aCurObj.SetParam( "" ); + aCurObj.SetURLPath( "" ); + aMatch = aCurObj.GetMainURL( INetURLObject::DecodeMechanism::NONE ); + } + + OUString aURL( aMatch ); + if( eProt == INetProtocol::NotValid ) + aMatch = aMatch.copy( INetURLObject::GetScheme( aCurObj.GetProtocol() ).getLength() ); + + if( aText.getLength() < aMatch.getLength() ) + Insert( aMatch, aURL ); + + continue; + } + break; + } + default: + { + if( bFull ) + continue; + + if( aCurMainURL.startsWith(aText) ) + { + if( aText.getLength() < aCurMainURL.getLength() ) + Insert( aCurMainURL, aCurMainURL ); + + continue; + } + break; + } + } + } + + if( !bFull ) + bFull = true; + else + break; + } +} + +/** Parse leading ~ for Unix systems, + does nothing for Windows + */ +bool SvtURLBox_Impl::TildeParsing( + OUString& +#ifdef UNX + aText +#endif + , OUString& +#ifdef UNX + aBaseURL +#endif +) +{ +#ifdef UNX + if( aText.startsWith( "~" ) ) + { + OUString aParseTilde; + bool bTrailingSlash = true; // use trailing slash + + if( aText.getLength() == 1 || aText[ 1 ] == '/' ) + { + // covers "~" or "~/..." cases + const char* aHomeLocation = getenv( "HOME" ); + if( !aHomeLocation ) + aHomeLocation = ""; + + aParseTilde = OUString::createFromAscii(aHomeLocation); + + // in case the whole path is just "~" then there should + // be no trailing slash at the end + if( aText.getLength() == 1 ) + bTrailingSlash = false; + } + else + { + // covers "~username" and "~username/..." cases + sal_Int32 nNameEnd = aText.indexOf( '/' ); + OUString aUserName = aText.copy( 1, ( nNameEnd != -1 ) ? nNameEnd : ( aText.getLength() - 1 ) ); + + struct passwd* pPasswd = nullptr; +#ifdef __sun + Sequence< sal_Int8 > sBuf( 1024 ); + struct passwd aTmp; + sal_Int32 nRes = getpwnam_r( OUStringToOString( aUserName, RTL_TEXTENCODING_ASCII_US ).getStr(), + &aTmp, + (char*)sBuf.getArray(), + 1024, + &pPasswd ); + if( !nRes && pPasswd ) + aParseTilde = OUString::createFromAscii(pPasswd->pw_dir); + else + return false; // no such user +#else + pPasswd = getpwnam( OUStringToOString( aUserName, RTL_TEXTENCODING_ASCII_US ).getStr() ); + if( pPasswd ) + aParseTilde = OUString::createFromAscii(pPasswd->pw_dir); + else + return false; // no such user +#endif + + // in case the path is "~username" then there should + // be no trailing slash at the end + if( nNameEnd == -1 ) + bTrailingSlash = false; + } + + if( !bTrailingSlash ) + { + if( aParseTilde.isEmpty() || aParseTilde == "/" ) + { + // "/" path should be converted to "/." + aParseTilde = "/."; + } + else + { + // "blabla/" path should be converted to "blabla" + aParseTilde = comphelper::string::stripEnd(aParseTilde, '/'); + } + } + else + { + if( !aParseTilde.endsWith("/") ) + aParseTilde += "/"; + if( aText.getLength() > 2 ) + aParseTilde += aText.copy( 2 ); + } + + aText = aParseTilde; + aBaseURL.clear(); // tilde provide absolute path + } +#endif + + return true; +} + +//-- + +OUString SvtURLBox::ParseSmart( const OUString& _aText, const OUString& _aBaseURL ) +{ + OUString aMatch; + OUString aText = _aText; + OUString aBaseURL = _aBaseURL; + + // parse ~ for Unix systems + // does nothing for Windows + if( !SvtURLBox_Impl::TildeParsing( aText, aBaseURL ) ) + return OUString(); + + if( !aBaseURL.isEmpty() ) + { + INetProtocol eBaseProt = INetURLObject::CompareProtocolScheme( aBaseURL ); + + // if a base URL is set the string may be parsed relative + if( aText.startsWith( "/" ) ) + { + // text starting with slashes means absolute file URLs + OUString aTemp = INetURLObject::GetScheme( eBaseProt ); + + // file URL must be correctly encoded! + OUString aTextURL = INetURLObject::encode( aText, INetURLObject::PART_FPATH, + INetURLObject::EncodeMechanism::All ); + aTemp += aTextURL; + + INetURLObject aTmp( aTemp ); + if ( !aTmp.HasError() && aTmp.GetProtocol() != INetProtocol::NotValid ) + aMatch = aTmp.GetMainURL( INetURLObject::DecodeMechanism::NONE ); + } + else + { + OUString aSmart( aText ); + INetURLObject aObj( aBaseURL ); + + // HRO: I suppose this hack should only be done for Windows !!!??? +#ifdef _WIN32 + // HRO: INetURLObject::smatRel2Abs does not recognize '\\' as a relative path + // but in case of "\\\\" INetURLObject is right - this is an absolute path ! + + if( aText.startsWith("\\") && (aText.getLength() < 2 || aText[ 1 ] != '\\') ) + { + // cut to first segment + OUString aTmp = INetURLObject::GetScheme( eBaseProt ) + "/"; + aTmp += aObj.getName( 0, true, INetURLObject::DecodeMechanism::WithCharset ); + aObj.SetURL( aTmp ); + + aSmart = aSmart.copy(1); + } +#endif + // base URL must be a directory ! + aObj.setFinalSlash(); + + // take base URL and append current input + bool bWasAbsolute = false; +#ifdef UNX + // encode file URL correctly + aSmart = INetURLObject::encode( aSmart, INetURLObject::PART_FPATH, INetURLObject::EncodeMechanism::All ); +#endif + INetURLObject aTmp( aObj.smartRel2Abs( aSmart, bWasAbsolute ) ); + + if ( aText.endsWith(".") ) + // INetURLObject appends a final slash for the directories "." and "..", this is a bug! + // Remove it as a workaround + aTmp.removeFinalSlash(); + if ( !aTmp.HasError() && aTmp.GetProtocol() != INetProtocol::NotValid ) + aMatch = aTmp.GetMainURL( INetURLObject::DecodeMechanism::NONE ); + } + } + else + { + OUString aTmpMatch; + osl::FileBase::getFileURLFromSystemPath( aText, aTmpMatch ); + aMatch = aTmpMatch; + } + + return aMatch; +} + +IMPL_LINK_NOARG(SvtURLBox, TryAutoComplete, Timer *, void) +{ + OUString aCurText = m_xWidget->get_active_text(); + int nStartPos, nEndPos; + m_xWidget->get_entry_selection_bounds(nStartPos, nEndPos); + if (std::max(nStartPos, nEndPos) != aCurText.getLength()) + return; + + auto nLen = std::min(nStartPos, nEndPos); + aCurText = aCurText.copy( 0, nLen ); + if (!aCurText.isEmpty()) + { + if (pCtx.is()) + { + pCtx->Stop(); + pCtx->join(); + pCtx.clear(); + } + pCtx = new SvtMatchContext_Impl(this, aCurText); + pCtx->launch(); + } + else + m_xWidget->clear(); +} + +SvtURLBox::SvtURLBox(std::unique_ptr<weld::ComboBox> pWidget) + : eSmartProtocol(INetProtocol::NotValid) + , bOnlyDirectories( false ) + , bHistoryDisabled( false ) + , bNoSelection( false ) + , m_xWidget(std::move(pWidget)) +{ + //don't grow to fix mega-long urls + Size aSize(m_xWidget->get_preferred_size()); + m_xWidget->set_size_request(aSize.Width(), -1); + + Init(); + + m_xWidget->connect_focus_in(LINK(this, SvtURLBox, FocusInHdl)); + m_xWidget->connect_focus_out(LINK(this, SvtURLBox, FocusOutHdl)); + m_xWidget->connect_changed(LINK(this, SvtURLBox, ChangedHdl)); + + aChangedIdle.SetInvokeHandler(LINK(this, SvtURLBox, TryAutoComplete)); + aChangedIdle.SetDebugName("svtools::URLBox aChangedIdle"); +} + +void SvtURLBox::Init() +{ + pImpl.reset( new SvtURLBox_Impl ); + + m_xWidget->set_entry_completion(false); + + UpdatePicklistForSmartProtocol_Impl(); +} + +SvtURLBox::~SvtURLBox() +{ + if (pCtx.is()) + { + pCtx->Stop(); + pCtx->join(); + } +} + +void SvtURLBox::SetSmartProtocol(INetProtocol eProt) +{ + if ( eSmartProtocol != eProt ) + { + eSmartProtocol = eProt; + UpdatePicklistForSmartProtocol_Impl(); + } +} + +void SvtURLBox::UpdatePicklistForSmartProtocol_Impl() +{ + m_xWidget->clear(); + if ( bHistoryDisabled ) + return; + + if (bHistoryDisabled) + return; + + // read history pick list + const Sequence< Sequence< PropertyValue > > seqPicklist = SvtHistoryOptions().GetList( ePICKLIST ); + INetURLObject aCurObj; + + for( const Sequence< PropertyValue >& rPropertySet : seqPicklist ) + { + auto pProperty = std::find_if(rPropertySet.begin(), rPropertySet.end(), + [](const PropertyValue& rProperty) { return rProperty.Name == HISTORY_PROPERTYNAME_URL; }); + if (pProperty != rPropertySet.end()) + { + OUString sURL; + + pProperty->Value >>= sURL; + aCurObj.SetURL( sURL ); + + if ( !sURL.isEmpty() && ( eSmartProtocol != INetProtocol::NotValid ) ) + { + if( aCurObj.GetProtocol() != eSmartProtocol ) + continue; + } + + OUString aURL( aCurObj.GetMainURL( INetURLObject::DecodeMechanism::WithCharset ) ); + + if ( !aURL.isEmpty() ) + { + bool bFound = aURL.endsWith("/"); + if ( !bFound ) + { + OUString aUpperURL = aURL.toAsciiUpperCase(); + + bFound = ::std::any_of(pImpl->m_aFilters.begin(), + pImpl->m_aFilters.end(), + FilterMatch( aUpperURL ) ); + } + if ( bFound ) + { + OUString aFile; + if (osl::FileBase::getSystemPathFromFileURL(aURL, aFile) == osl::FileBase::E_None) + m_xWidget->append_text(aFile); + else + m_xWidget->append_text(aURL); + } + } + } + } +} + +IMPL_LINK_NOARG(SvtURLBox, ChangedHdl, weld::ComboBox&, void) +{ + aChangeHdl.Call(*m_xWidget); + aChangedIdle.Start(); //launch this to happen on idle after cursor position will have been set +} + +IMPL_LINK_NOARG(SvtURLBox, FocusInHdl, weld::Widget&, void) +{ +#ifndef UNX + // pb: don't select automatically on unix #93251# + m_xWidget->select_entry_region(0, -1); +#endif + aFocusInHdl.Call(*m_xWidget); +} + +IMPL_LINK_NOARG(SvtURLBox, FocusOutHdl, weld::Widget&, void) +{ + if (pCtx.is()) + { + pCtx->Stop(); + pCtx->join(); + pCtx.clear(); + } + aFocusOutHdl.Call(*m_xWidget); +} + +void SvtURLBox::SetOnlyDirectories( bool bDir ) +{ + bOnlyDirectories = bDir; + if ( bOnlyDirectories ) + m_xWidget->clear(); +} + +void SvtURLBox::SetNoURLSelection( bool bSet ) +{ + bNoSelection = bSet; +} + +OUString SvtURLBox::GetURL() +{ + // wait for end of autocompletion + ::osl::MutexGuard aGuard( theSvtMatchContextMutex::get() ); + + OUString aText(m_xWidget->get_active_text()); + if (MatchesPlaceHolder(aText)) + return aPlaceHolder; + + // try to get the right case preserving URL from the list of URLs + for(std::vector<OUString>::iterator i = pImpl->aCompletions.begin(), j = pImpl->aURLs.begin(); i != pImpl->aCompletions.end() && j != pImpl->aURLs.end(); ++i, ++j) + { + if((*i) == aText) + return *j; + } + +#ifdef _WIN32 + // erase trailing spaces on Windows since they are invalid on this OS and + // most of the time they are inserted by accident via copy / paste + aText = comphelper::string::stripEnd(aText, ' '); + if ( aText.isEmpty() ) + return aText; + // #i9739# +#endif + + INetURLObject aObj( aText ); + if( aText.indexOf( '*' ) != -1 || aText.indexOf( '?' ) != -1 ) + { + // no autocompletion for wildcards + INetURLObject aTempObj; + if ( eSmartProtocol != INetProtocol::NotValid ) + aTempObj.SetSmartProtocol( eSmartProtocol ); + if ( aTempObj.SetSmartURL( aText ) ) + return aTempObj.GetMainURL( INetURLObject::DecodeMechanism::NONE ); + else + return aText; + } + + if ( aObj.GetProtocol() == INetProtocol::NotValid ) + { + OUString aName = ParseSmart( aText, aBaseURL ); + aObj.SetURL(aName); + OUString aURL( aObj.GetMainURL( INetURLObject::DecodeMechanism::NONE ) ); + if ( aURL.isEmpty() ) + // aText itself is invalid, and even together with aBaseURL, it could not + // made valid -> no chance + return aText; + + bool bSlash = aObj.hasFinalSlash(); + { + const OUString aPropName("CasePreservingURL"); + + OUString aFileURL; + + Any aAny = UCBContentHelper::GetProperty(aURL, aPropName); + bool success = (aAny >>= aFileURL); + OUString aTitle; + if(success) + aTitle = INetURLObject(aFileURL).getName( + INetURLObject::LAST_SEGMENT, + true, + INetURLObject::DecodeMechanism::WithCharset ); + else + success = + UCBContentHelper::GetTitle(aURL,&aTitle); + + if( success && aTitle != "/" && aTitle != "." ) + { + aObj.setName( aTitle ); + if ( bSlash ) + aObj.setFinalSlash(); + } + } + } + + return aObj.GetMainURL( INetURLObject::DecodeMechanism::NONE ); +} + +void SvtURLBox::SetBaseURL( const OUString& rURL ) +{ + ::osl::MutexGuard aGuard( theSvtMatchContextMutex::get() ); + + // Reset match lists + pImpl->aCompletions.clear(); + pImpl->aURLs.clear(); + + aBaseURL = rURL; +} + +void SvtURLBox::DisableHistory() +{ + bHistoryDisabled = true; + UpdatePicklistForSmartProtocol_Impl(); +} + +void SvtURLBox::SetFilter(const OUString& _sFilter) +{ + pImpl->m_aFilters.clear(); + FilterMatch::createWildCardFilterList(_sFilter,pImpl->m_aFilters); +} + +void FilterMatch::createWildCardFilterList(const OUString& _rFilterList,::std::vector< WildCard >& _rFilters) +{ + if( _rFilterList.getLength() ) + { + // filter is given + sal_Int32 nIndex = 0; + OUString sToken; + do + { + sToken = _rFilterList.getToken( 0, ';', nIndex ); + if ( !sToken.isEmpty() ) + { + _rFilters.emplace_back( sToken.toAsciiUpperCase() ); + } + } + while ( nIndex >= 0 ); + } + else + { + // no filter is given -> match all + _rFilters.emplace_back("*" ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/control/managedmenubutton.cxx b/svtools/source/control/managedmenubutton.cxx new file mode 100644 index 000000000..45e9d98ca --- /dev/null +++ b/svtools/source/control/managedmenubutton.cxx @@ -0,0 +1,122 @@ +/* -*- 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 <comphelper/processfactory.hxx> +#include <comphelper/propertyvalue.hxx> +#include <toolkit/awt/vclxmenu.hxx> +#include <vcl/builderfactory.hxx> +#include <vcl/menu.hxx> +#include <vcl/menubtn.hxx> + +#include <com/sun/star/frame/theDesktop.hpp> +#include <com/sun/star/frame/ModuleManager.hpp> +#include <com/sun/star/frame/thePopupMenuControllerFactory.hpp> +#include <com/sun/star/frame/XPopupMenuController.hpp> + +namespace { + +class ManagedMenuButton : public MenuButton +{ +public: + ManagedMenuButton(vcl::Window* pParent, WinBits nStyle); + ~ManagedMenuButton() override; + + void Activate() override; + void dispose() override; + +private: + rtl::Reference<VCLXPopupMenu> m_xPopupMenu; + css::uno::Reference<css::frame::XPopupMenuController> m_xPopupController; +}; + +ManagedMenuButton::ManagedMenuButton(vcl::Window* pParent, WinBits nStyle) + : MenuButton(pParent, nStyle) +{ + SetImageAlign(ImageAlign::Left); +} + +ManagedMenuButton::~ManagedMenuButton() +{ + disposeOnce(); +} + +void ManagedMenuButton::dispose() +{ + css::uno::Reference<css::lang::XComponent> xComponent(m_xPopupController, css::uno::UNO_QUERY); + if (xComponent.is()) + xComponent->dispose(); + + m_xPopupMenu.clear(); + m_xPopupController.clear(); + MenuButton::dispose(); +} + +void ManagedMenuButton::Activate() +{ + if (!GetPopupMenu()) + SetPopupMenu(VclPtr<PopupMenu>::Create()); + + MenuButton::Activate(); + + if (m_xPopupController.is()) + { + m_xPopupController->updatePopupMenu(); + return; + } + + if (!m_xPopupMenu.is()) + m_xPopupMenu.set(new VCLXPopupMenu(GetPopupMenu())); + + // FIXME: get the frame from the parent VclBuilder. + css::uno::Reference<css::uno::XComponentContext> xContext(comphelper::getProcessComponentContext()); + css::uno::Reference<css::frame::XDesktop2> xDesktop(css::frame::theDesktop::get(xContext)); + css::uno::Reference<css::frame::XFrame> xFrame(xDesktop->getActiveFrame()); + if (!xFrame.is()) + return; + + OUString aModuleName; + try + { + css::uno::Reference<css::frame::XModuleManager> xModuleManager(css::frame::ModuleManager::create(xContext)); + aModuleName = xModuleManager->identify(xFrame); + } + catch( const css::uno::Exception& ) + {} + + css::uno::Sequence<css::uno::Any> aArgs { + css::uno::makeAny(comphelper::makePropertyValue("ModuleIdentifier", aModuleName)), + css::uno::makeAny(comphelper::makePropertyValue("Frame", css::uno::makeAny(xFrame))), + css::uno::makeAny(comphelper::makePropertyValue("InToolbar", css::uno::makeAny(true))) + }; + + const OUString aCommand(GetCommand()); + if (!aCommand.isEmpty() && GetPopupMenu()->GetItemCount() == 0) + { + css::uno::Reference<css::frame::XUIControllerFactory> xPopupMenuControllerFactory = + css::frame::thePopupMenuControllerFactory::get(xContext); + + if (xPopupMenuControllerFactory->hasController(aCommand, aModuleName)) + m_xPopupController.set(xPopupMenuControllerFactory->createInstanceWithArgumentsAndContext( + aCommand, aArgs, xContext), css::uno::UNO_QUERY); + } + + // No registered controller found, use one the can handle arbitrary menus (e.g. defined in .ui file). + if (!m_xPopupController.is()) + m_xPopupController.set(xContext->getServiceManager()->createInstanceWithArgumentsAndContext( + "com.sun.star.comp.framework.ResourceMenuController", aArgs, xContext), css::uno::UNO_QUERY); + + if (m_xPopupController.is()) + m_xPopupController->setPopupMenu(m_xPopupMenu.get()); +} + +} + +VCL_BUILDER_FACTORY_ARGS(ManagedMenuButton, WB_CLIPCHILDREN|WB_CENTER|WB_VCENTER|WB_FLATBUTTON) + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/svtools/source/control/ruler.cxx b/svtools/source/control/ruler.cxx new file mode 100644 index 000000000..8608adc3b --- /dev/null +++ b/svtools/source/control/ruler.cxx @@ -0,0 +1,2774 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <tools/debug.hxx> +#include <tools/poly.hxx> +#include <vcl/event.hxx> +#include <vcl/settings.hxx> +#include <vcl/vcllayout.hxx> +#include <vcl/virdev.hxx> +#include <vcl/ptrstyle.hxx> +#include <sal/log.hxx> + +#include <svtools/ruler.hxx> +#include <svtools/svtresid.hxx> +#include <svtools/strings.hrc> +#include <svtools/colorcfg.hxx> +#include "accessibleruler.hxx" + +#include <memory> +#include <vector> + +using namespace std; +using namespace ::com::sun::star; +using namespace ::com::sun::star::uno; +using namespace ::com::sun::star::lang; +using namespace ::com::sun::star::accessibility; + +#define RULER_OFF 3 +#define RULER_RESIZE_OFF 4 +#define RULER_MIN_SIZE 3 + +#define RULER_VAR_SIZE 8 + +#define RULER_UPDATE_LINES 0x01 + +#define RULER_CLIP 150 + +#define RULER_UNIT_MM 0 +#define RULER_UNIT_CM 1 +#define RULER_UNIT_M 2 +#define RULER_UNIT_KM 3 +#define RULER_UNIT_INCH 4 +#define RULER_UNIT_FOOT 5 +#define RULER_UNIT_MILE 6 +#define RULER_UNIT_POINT 7 +#define RULER_UNIT_PICA 8 +#define RULER_UNIT_CHAR 9 +#define RULER_UNIT_LINE 10 +#define RULER_UNIT_COUNT 11 + +namespace +{ +/** + * Pre-calculates glyph items for rText on rRenderContext. Subsequent calls + * avoid the calculation and just return a pointer to rTextGlyphs. + */ +SalLayoutGlyphs* lcl_GetRulerTextGlyphs(const vcl::RenderContext& rRenderContext, const OUString& rText, + SalLayoutGlyphs& rTextGlyphs) +{ + if (rTextGlyphs.IsValid()) + // Use pre-calculated result. + return &rTextGlyphs; + + // Calculate glyph items. + + std::unique_ptr<SalLayout> pLayout = rRenderContext.ImplLayout( + rText, 0, rText.getLength(), Point(0, 0), 0, nullptr, SalLayoutFlags::GlyphItemsOnly); + if (!pLayout) + return nullptr; + + const SalLayoutGlyphs* pGlyphs = pLayout->GetGlyphs(); + if (!pGlyphs) + return nullptr; + + // Remember the calculation result. + rTextGlyphs = *pGlyphs; + + return &rTextGlyphs; +} +} + +class ImplRulerData +{ + friend class Ruler; + +private: + vector<RulerLine> pLines; + vector<RulerBorder> pBorders; + vector<RulerIndent> pIndents; + vector<RulerTab> pTabs; + + long nNullVirOff; + long nRulVirOff; + long nRulWidth; + long nPageOff; + long nPageWidth; + long nNullOff; + long nMargin1; + long nMargin2; + // In this context, "frame margin" means paragraph margins (indents) + long nLeftFrameMargin; + long nRightFrameMargin; + RulerMarginStyle nMargin1Style; + RulerMarginStyle nMargin2Style; + bool bAutoPageWidth; + bool bTextRTL; + +public: + ImplRulerData(); +}; + +ImplRulerData::ImplRulerData() : + nNullVirOff (0), + nRulVirOff (0), + nRulWidth (0), + nPageOff (0), + nPageWidth (0), + nNullOff (0), + nMargin1 (0), + nMargin2 (0), + nLeftFrameMargin (0), + nRightFrameMargin (0), + nMargin1Style (RulerMarginStyle::NONE), + nMargin2Style (RulerMarginStyle::NONE), + bAutoPageWidth (true), // Page width == EditWin width + bTextRTL (false) +{ +} + +static const RulerUnitData aImplRulerUnitTab[RULER_UNIT_COUNT] = +{ +{ MapUnit::Map100thMM, 100, 25.0, 25.0, 50.0, 100.0, " mm" }, // MM +{ MapUnit::Map100thMM, 1000, 100.0, 500.0, 1000.0, 1000.0, " cm" }, // CM +{ MapUnit::MapMM, 1000, 10.0, 250.0, 500.0, 1000.0, " m" }, // M +{ MapUnit::MapCM, 100000, 12500.0, 25000.0, 50000.0, 100000.0, " km" }, // KM +{ MapUnit::Map1000thInch, 1000, 62.5, 125.0, 500.0, 1000.0, "\"" }, // INCH +{ MapUnit::Map100thInch, 1200, 120.0, 120.0, 600.0, 1200.0, "'" }, // FOOT +{ MapUnit::Map10thInch, 633600, 63360.0, 63360.0, 316800.0, 633600.0, " miles" }, // MILE +{ MapUnit::MapPoint, 1, 12.0, 12.0, 12.0, 36.0, " pt" }, // POINT +{ MapUnit::Map100thMM, 423, 423.0, 423.0, 423.0, 846.0, " pc" }, // PICA +{ MapUnit::Map100thMM, 371, 371.0, 371.0, 371.0, 743.0, " ch" }, // CHAR +{ MapUnit::Map100thMM, 551, 551.0, 551.0, 551.0, 1102.0, " li" } // LINE +}; + +static RulerTabData ruler_tab = +{ + 0, // DPIScaleFactor to be set + 7, // ruler_tab_width + 6, // ruler_tab_height + 2, // ruler_tab_height2 + 2, // ruler_tab_width2 + 8, // ruler_tab_cwidth + 4, // ruler_tab_cwidth2 + 4, // ruler_tab_cwidth3 + 2, // ruler_tab_cwidth4 + 4, // ruler_tab_dheight + 1, // ruler_tab_dheight2 + 5, // ruler_tab_dwidth + 3, // ruler_tab_dwidth2 + 3, // ruler_tab_dwidth3 + 1, // ruler_tab_dwidth4 + 5 // ruler_tab_textoff +}; + +void Ruler::ImplInit( WinBits nWinBits ) +{ + // Set default WinBits + if ( !(nWinBits & WB_VERT) ) + { + nWinBits |= WB_HORZ; + + // RTL: no UI mirroring for horizontal rulers, because + // the document is also not mirrored + EnableRTL( false ); + } + + // Initialize variables + mnWinStyle = nWinBits; // Window-Style + mnBorderOff = 0; // Border-Offset + mnWinOff = 0; // EditWinOffset + mnWinWidth = 0; // EditWinWidth + mnWidth = 0; // Window width + mnHeight = 0; // Window height + mnVirOff = 0; // Offset of VirtualDevice from top-left corner + mnVirWidth = 0; // width or height from VirtualDevice + mnVirHeight = 0; // height of width from VirtualDevice + mnDragPos = 0; // Drag-Position (Null point) + mnDragAryPos = 0; // Drag-Array-Index + mnDragSize = RulerDragSize::Move; // Did size change at dragging + mnDragModifier = 0; // Modifier key at dragging + mnExtraStyle = 0; // Style of Extra field + mnCharWidth = 371; + mnLineHeight = 551; + mbCalc = true; // Should recalculate page width + mbFormat = true; // Should redraw + mbDrag = false; // Currently at dragging + mbDragDelete = false; // Has mouse left the dragging area + mbDragCanceled = false; // Dragging cancelled? + mbAutoWinWidth = true; // EditWinWidth == RulerWidth + mbActive = true; // Is ruler active + mnUpdateFlags = 0; // What needs to be updated + mpData = mpSaveData.get(); // Pointer to normal data + meExtraType = RulerExtra::DontKnow; // What is in extra field + meDragType = RulerType::DontKnow; // Which element is dragged + + // Initialize Units + mnUnitIndex = RULER_UNIT_CM; + meUnit = FieldUnit::CM; + maZoom = Fraction( 1, 1 ); + + // Recalculate border widths + if ( nWinBits & WB_BORDER ) + mnBorderWidth = 1; + else + mnBorderWidth = 0; + + // Settings + ImplInitSettings( true, true, true ); + + // Setup the default size + tools::Rectangle aRect; + GetTextBoundRect( aRect, "0123456789" ); + long nDefHeight = aRect.GetHeight() + RULER_OFF * 2 + ruler_tab.textoff * 2 + mnBorderWidth; + + Size aDefSize; + if ( nWinBits & WB_HORZ ) + aDefSize.setHeight( nDefHeight ); + else + aDefSize.setWidth( nDefHeight ); + SetOutputSizePixel( aDefSize ); + SetType(WindowType::RULER); +} + +Ruler::Ruler( vcl::Window* pParent, WinBits nWinStyle ) : + Window( pParent, nWinStyle & WB_3DLOOK ), + maVirDev( VclPtr<VirtualDevice>::Create(*this) ), + maMapMode( MapUnit::Map100thMM ), + mpSaveData(new ImplRulerData), + mpData(nullptr), + mpDragData(new ImplRulerData) +{ + // Check to see if the ruler constructor has + // already been called before otherwise + // we end up with over-scaled elements + if (ruler_tab.DPIScaleFactor == 0) + { + ruler_tab.DPIScaleFactor = GetDPIScaleFactor(); + ruler_tab.width *= ruler_tab.DPIScaleFactor; + ruler_tab.height *= ruler_tab.DPIScaleFactor; + ruler_tab.height2 *= ruler_tab.DPIScaleFactor; + ruler_tab.width2 *= ruler_tab.DPIScaleFactor; + ruler_tab.cwidth *= ruler_tab.DPIScaleFactor; + ruler_tab.cwidth2 *= ruler_tab.DPIScaleFactor; + ruler_tab.cwidth3 *= ruler_tab.DPIScaleFactor; + ruler_tab.cwidth4 *= ruler_tab.DPIScaleFactor; + ruler_tab.dheight *= ruler_tab.DPIScaleFactor; + ruler_tab.dheight2 *= ruler_tab.DPIScaleFactor; + ruler_tab.dwidth *= ruler_tab.DPIScaleFactor; + ruler_tab.dwidth2 *= ruler_tab.DPIScaleFactor; + ruler_tab.dwidth3 *= ruler_tab.DPIScaleFactor; + ruler_tab.dwidth4 *= ruler_tab.DPIScaleFactor; + ruler_tab.textoff *= ruler_tab.DPIScaleFactor; + } + + + ImplInit( nWinStyle ); +} + +Ruler::~Ruler() +{ + disposeOnce(); +} + +void Ruler::dispose() +{ + mpSaveData.reset(); + mpDragData.reset(); + mxAccContext.clear(); + Window::dispose(); +} + +void Ruler::ImplVDrawLine(vcl::RenderContext& rRenderContext, long nX1, long nY1, long nX2, long nY2) +{ + if ( nX1 < -RULER_CLIP ) + { + nX1 = -RULER_CLIP; + if ( nX2 < -RULER_CLIP ) + return; + } + long nClip = mnVirWidth + RULER_CLIP; + if ( nX2 > nClip ) + { + nX2 = nClip; + if ( nX1 > nClip ) + return; + } + + if ( mnWinStyle & WB_HORZ ) + rRenderContext.DrawLine( Point( nX1, nY1 ), Point( nX2, nY2 ) ); + else + rRenderContext.DrawLine( Point( nY1, nX1 ), Point( nY2, nX2 ) ); +} + +void Ruler::ImplVDrawRect(vcl::RenderContext& rRenderContext, long nX1, long nY1, long nX2, long nY2) +{ + if ( nX1 < -RULER_CLIP ) + { + nX1 = -RULER_CLIP; + if ( nX2 < -RULER_CLIP ) + return; + } + long nClip = mnVirWidth + RULER_CLIP; + if ( nX2 > nClip ) + { + nX2 = nClip; + if ( nX1 > nClip ) + return; + } + + if ( mnWinStyle & WB_HORZ ) + rRenderContext.DrawRect(tools::Rectangle(nX1, nY1, nX2, nY2)); + else + rRenderContext.DrawRect(tools::Rectangle(nY1, nX1, nY2, nX2)); +} + +void Ruler::ImplVDrawText(vcl::RenderContext& rRenderContext, long nX, long nY, const OUString& rText, long nMin, long nMax) +{ + tools::Rectangle aRect; + SalLayoutGlyphs* pTextLayout + = lcl_GetRulerTextGlyphs(rRenderContext, rText, maTextGlyphs[rText]); + rRenderContext.GetTextBoundRect(aRect, rText, 0, 0, -1, 0, nullptr, pTextLayout); + + long nShiftX = ( aRect.GetWidth() / 2 ) + aRect.Left(); + long nShiftY = ( aRect.GetHeight() / 2 ) + aRect.Top(); + + if ( (nX > -RULER_CLIP) && (nX < mnVirWidth + RULER_CLIP) && ( nX < nMax - nShiftX ) && ( nX > nMin + nShiftX ) ) + { + if ( mnWinStyle & WB_HORZ ) + rRenderContext.DrawText(Point(nX - nShiftX, nY - nShiftY), rText, 0, -1, nullptr, + nullptr, pTextLayout); + else + rRenderContext.DrawText(Point(nY - nShiftX, nX - nShiftY), rText, 0, -1, nullptr, + nullptr, pTextLayout); + } +} + +void Ruler::ImplInvertLines(vcl::RenderContext& rRenderContext) +{ + // Position lines + if (!(!mpData->pLines.empty() && mbActive && !mbDrag && !mbFormat && !(mnUpdateFlags & RULER_UPDATE_LINES)) ) + return; + + long nNullWinOff = mpData->nNullVirOff + mnVirOff; + long nRulX1 = mpData->nRulVirOff + mnVirOff; + long nRulX2 = nRulX1 + mpData->nRulWidth; + long nY = (RULER_OFF * 2) + mnVirHeight - 1; + + // Calculate rectangle + tools::Rectangle aRect; + if (mnWinStyle & WB_HORZ) + aRect.SetBottom( nY ); + else + aRect.SetRight( nY ); + + // Draw lines + for (const RulerLine & rLine : mpData->pLines) + { + const long n = rLine.nPos + nNullWinOff; + if ((n >= nRulX1) && (n < nRulX2)) + { + if (mnWinStyle & WB_HORZ ) + { + aRect.SetLeft( n ); + aRect.SetRight( n ); + } + else + { + aRect.SetTop( n ); + aRect.SetBottom( n ); + } + tools::Rectangle aTempRect = aRect; + + if (mnWinStyle & WB_HORZ) + aTempRect.SetBottom( RULER_OFF - 1 ); + else + aTempRect.SetRight( RULER_OFF - 1 ); + + rRenderContext.Erase(aTempRect); + + if (mnWinStyle & WB_HORZ) + { + aTempRect.SetBottom( aRect.Bottom() ); + aTempRect.SetTop( aTempRect.Bottom() - RULER_OFF + 1 ); + } + else + { + aTempRect.SetRight( aRect.Right() ); + aTempRect.SetLeft( aTempRect.Right() - RULER_OFF + 1 ); + } + rRenderContext.Erase(aTempRect); + Invert(aRect); + } + } + mnUpdateFlags = 0; +} + +void Ruler::ImplDrawTicks(vcl::RenderContext& rRenderContext, long nMin, long nMax, long nStart, long nTop, long nBottom) +{ + double nCenter = nTop + ((nBottom - nTop) / 2); + + long nTickLength3 = (nBottom - nTop) * 0.5; + long nTickLength2 = nTickLength3 * 0.66; + long nTickLength1 = nTickLength2 * 0.66; + + long nScale = ruler_tab.DPIScaleFactor; + long DPIOffset = nScale - 1; + + double nTick4 = aImplRulerUnitTab[mnUnitIndex].nTick4; + double nTick2 = 0; + double nTickCount = aImplRulerUnitTab[mnUnitIndex].nTick1 / nScale; + double nTickUnit = 0; + long nTickWidth; + bool bNoTicks = false; + + Size aPixSize = rRenderContext.LogicToPixel(Size(nTick4, nTick4), maMapMode); + + if (mnUnitIndex == RULER_UNIT_CHAR) + { + if (mnCharWidth == 0) + mnCharWidth = 371; + nTick4 = mnCharWidth * 2; + nTick2 = mnCharWidth; + nTickCount = mnCharWidth; + nTickUnit = mnCharWidth; + } + else if (mnUnitIndex == RULER_UNIT_LINE) + { + if (mnLineHeight == 0) + mnLineHeight = 551; + nTick4 = mnLineHeight * 2; + nTick2 = mnLineHeight; + nTickUnit = mnLineHeight; + nTickCount = mnLineHeight; + } + + if (mnWinStyle & WB_HORZ) + { + nTickWidth = aPixSize.Width(); + } + else + { + vcl::Font aFont = rRenderContext.GetFont(); + if (mnWinStyle & WB_RIGHT_ALIGNED) + aFont.SetOrientation(2700); + else + aFont.SetOrientation(900); + rRenderContext.SetFont(aFont); + nTickWidth = aPixSize.Height(); + } + + long nMaxWidth = rRenderContext.PixelToLogic(Size(mpData->nPageWidth, 0), maMapMode).Width(); + if (nMaxWidth < 0) + nMaxWidth = -nMaxWidth; + + if ((mnUnitIndex == RULER_UNIT_CHAR) || (mnUnitIndex == RULER_UNIT_LINE)) + nMaxWidth /= nTickUnit; + else + nMaxWidth /= aImplRulerUnitTab[mnUnitIndex].nTickUnit; + + OUString aNumString = OUString::number(nMaxWidth); + long nTxtWidth = rRenderContext.GetTextWidth( aNumString ); + const long nTextOff = 4; + + // Determine the number divider for ruler drawn numbers - means which numbers + // should be shown on the ruler and which should be skipped because the ruler + // is not big enough to draw them + if (nTickWidth < nTxtWidth + nTextOff) + { + // Calculate the scale of the ruler + long nMulti = 1; + long nOrgTick4 = nTick4; + + while (nTickWidth < nTxtWidth + nTextOff) + { + long nOldMulti = nMulti; + if (nTickWidth == 0) + nMulti *= 10; + else if (nMulti < 10) + nMulti++; + else if (nMulti < 100) + nMulti += 10; + else if (nMulti < 1000) + nMulti += 100; + else + nMulti += 1000; + + // Overflow - in this case don't draw ticks and exit + if (nMulti < nOldMulti) + { + bNoTicks = true; + break; + } + + nTick4 = nOrgTick4 * nMulti; + aPixSize = rRenderContext.LogicToPixel(Size(nTick4, nTick4), maMapMode); + if (mnWinStyle & WB_HORZ) + nTickWidth = aPixSize.Width(); + else + nTickWidth = aPixSize.Height(); + } + nTickCount = nTick4; + } + else + { + rRenderContext.SetLineColor(rRenderContext.GetSettings().GetStyleSettings().GetShadowColor()); + } + + if (bNoTicks) + return; + + long n = 0; + double nTick = 0.0; + double nTick3 = 0; + + if ((mnUnitIndex != RULER_UNIT_CHAR) && (mnUnitIndex != RULER_UNIT_LINE)) + { + nTick2 = aImplRulerUnitTab[mnUnitIndex].nTick2; + nTick3 = aImplRulerUnitTab[mnUnitIndex].nTick3; + } + + Size nTickGapSize; + + nTickGapSize = rRenderContext.LogicToPixel(Size(nTickCount, nTickCount), maMapMode); + long nTickGap1 = mnWinStyle & WB_HORZ ? nTickGapSize.Width() : nTickGapSize.Height(); + nTickGapSize = rRenderContext.LogicToPixel(Size(nTick2, nTick2), maMapMode); + long nTickGap2 = mnWinStyle & WB_HORZ ? nTickGapSize.Width() : nTickGapSize.Height(); + nTickGapSize = rRenderContext.LogicToPixel(Size(nTick3, nTick3), maMapMode); + long nTickGap3 = mnWinStyle & WB_HORZ ? nTickGapSize.Width() : nTickGapSize.Height(); + + while (((nStart - n) >= nMin) || ((nStart + n) <= nMax)) + { + // Null point + if (nTick == 0.0) + { + if (nStart > nMin) + { + // 0 is only painted when Margin1 is not equal to zero + if ((mpData->nMargin1Style & RulerMarginStyle::Invisible) || (mpData->nMargin1 != 0)) + { + aNumString = "0"; + ImplVDrawText(rRenderContext, nStart, nCenter, aNumString); + } + } + } + else + { + aPixSize = rRenderContext.LogicToPixel(Size(nTick, nTick), maMapMode); + + if (mnWinStyle & WB_HORZ) + n = aPixSize.Width(); + else + n = aPixSize.Height(); + + // Tick4 - Output (Text) + double aStep = nTick / nTick4; + double aRest = std::abs(aStep - std::floor(aStep)); + double nAcceptanceDelta = 0.0001; + + if (aRest < nAcceptanceDelta) + { + if ((mnUnitIndex == RULER_UNIT_CHAR) || (mnUnitIndex == RULER_UNIT_LINE)) + aNumString = OUString::number(nTick / nTickUnit); + else + aNumString = OUString::number(nTick / aImplRulerUnitTab[mnUnitIndex].nTickUnit); + + long nHorizontalLocation = nStart + n; + ImplVDrawText(rRenderContext, nHorizontalLocation, nCenter, aNumString, nMin, nMax); + + if (nMin < nHorizontalLocation && nHorizontalLocation < nMax) + { + ImplVDrawRect(rRenderContext, nHorizontalLocation, nBottom - 1 * nScale, nHorizontalLocation + DPIOffset, nBottom); + ImplVDrawRect(rRenderContext, nHorizontalLocation, nTop, nHorizontalLocation + DPIOffset, nTop + 1 * nScale); + } + + nHorizontalLocation = nStart - n; + ImplVDrawText(rRenderContext, nHorizontalLocation, nCenter, aNumString, nMin, nMax); + + if (nMin < nHorizontalLocation && nHorizontalLocation < nMax) + { + ImplVDrawRect(rRenderContext, nHorizontalLocation, nBottom, + nHorizontalLocation + DPIOffset, nBottom - 1 * nScale); + ImplVDrawRect(rRenderContext, nHorizontalLocation, nTop, + nHorizontalLocation + DPIOffset, nTop + 1 * nScale); + } + } + // Tick/Tick2 - Output (Strokes) + else + { + long nTickLength = nTickLength1; + + aStep = (nTick / nTick2); + aRest = std::abs(aStep - std::floor(aStep)); + if (aRest < nAcceptanceDelta) + nTickLength = nTickLength2; + + aStep = (nTick / nTick3); + aRest = std::abs(aStep - std::floor(aStep)); + if (aRest < nAcceptanceDelta ) + nTickLength = nTickLength3; + + if ((nTickLength == nTickLength1 && nTickGap1 > 6) || + (nTickLength == nTickLength2 && nTickGap2 > 6) || + (nTickLength == nTickLength3 && nTickGap3 > 6)) + { + long nT1 = nCenter - (nTickLength / 2.0); + long nT2 = nT1 + nTickLength - 1; + long nT; + + nT = nStart + n; + + if (nT < nMax) + ImplVDrawRect(rRenderContext, nT, nT1, nT + DPIOffset, nT2); + nT = nStart - n; + if (nT > nMin) + ImplVDrawRect(rRenderContext, nT, nT1, nT + DPIOffset, nT2); + } + } + } + nTick += nTickCount; + } +} + +void Ruler::ImplDrawBorders(vcl::RenderContext& rRenderContext, long nMin, long nMax, long nVirTop, long nVirBottom) +{ + const StyleSettings& rStyleSettings = rRenderContext.GetSettings().GetStyleSettings(); + long n; + long n1; + long n2; + long nTemp1; + long nTemp2; + + for (std::vector<RulerBorder>::size_type i = 0; i < mpData->pBorders.size(); i++) + { + if (mpData->pBorders[i].nStyle & RulerBorderStyle::Invisible) + continue; + + n1 = mpData->pBorders[i].nPos + mpData->nNullVirOff; + n2 = n1 + mpData->pBorders[i].nWidth; + + if (((n1 >= nMin) && (n1 <= nMax)) || ((n2 >= nMin) && (n2 <= nMax))) + { + if ((n2 - n1) > 3) + { + rRenderContext.SetLineColor(); + rRenderContext.SetFillColor(rStyleSettings.GetFaceColor()); + ImplVDrawRect(rRenderContext, n1, nVirTop, n2, nVirBottom); + + rRenderContext.SetLineColor(rStyleSettings.GetLightColor()); + ImplVDrawLine(rRenderContext, n1 + 1, nVirTop, n1 + 1, nVirBottom); + ImplVDrawLine(rRenderContext, n1, nVirTop, n2, nVirTop); + + rRenderContext.SetLineColor(rStyleSettings.GetShadowColor()); + ImplVDrawLine(rRenderContext, n1, nVirTop, n1, nVirBottom); + ImplVDrawLine(rRenderContext, n1, nVirBottom, n2, nVirBottom); + ImplVDrawLine(rRenderContext, n2 - 1, nVirTop, n2 - 1, nVirBottom); + + rRenderContext.SetLineColor(rStyleSettings.GetDarkShadowColor()); + ImplVDrawLine(rRenderContext, n2, nVirTop, n2, nVirBottom); + + if (mpData->pBorders[i].nStyle & RulerBorderStyle::Variable) + { + if (n2 - n1 > RULER_VAR_SIZE + 4) + { + nTemp1 = n1 + (((n2 - n1 + 1) - RULER_VAR_SIZE) / 2); + nTemp2 = nVirTop + (((nVirBottom - nVirTop + 1) - RULER_VAR_SIZE) / 2); + long nTemp3 = nTemp1 + RULER_VAR_SIZE - 1; + long nTemp4 = nTemp2 + RULER_VAR_SIZE - 1; + long nTempY = nTemp2; + + rRenderContext.SetLineColor(rStyleSettings.GetLightColor()); + while (nTempY <= nTemp4) + { + ImplVDrawLine(rRenderContext, nTemp1, nTempY, nTemp3, nTempY); + nTempY += 2; + } + + nTempY = nTemp2 + 1; + rRenderContext.SetLineColor(rStyleSettings.GetShadowColor()); + while (nTempY <= nTemp4) + { + ImplVDrawLine(rRenderContext, nTemp1, nTempY, nTemp3, nTempY); + nTempY += 2; + } + } + } + + if (mpData->pBorders[i].nStyle & RulerBorderStyle::Sizeable) + { + if (n2 - n1 > RULER_VAR_SIZE + 10) + { + rRenderContext.SetLineColor(rStyleSettings.GetShadowColor()); + ImplVDrawLine(rRenderContext, n1 + 4, nVirTop + 3, n1 + 4, nVirBottom - 3); + ImplVDrawLine(rRenderContext, n2 - 5, nVirTop + 3, n2 - 5, nVirBottom - 3); + rRenderContext.SetLineColor(rStyleSettings.GetLightColor()); + ImplVDrawLine(rRenderContext, n1 + 5, nVirTop + 3, n1 + 5, nVirBottom - 3); + ImplVDrawLine(rRenderContext, n2 - 4, nVirTop + 3, n2 - 4, nVirBottom - 3); + } + } + } + else + { + n = n1 + ((n2 - n1) / 2); + rRenderContext.SetLineColor(rStyleSettings.GetShadowColor()); + + ImplVDrawLine(rRenderContext, n - 1, nVirTop, n - 1, nVirBottom); + ImplVDrawLine(rRenderContext, n + 1, nVirTop, n + 1, nVirBottom); + rRenderContext.SetLineColor(); + rRenderContext.SetFillColor(rStyleSettings.GetWindowColor()); + ImplVDrawRect(rRenderContext, n, nVirTop, n, nVirBottom); + } + } + } +} + +void Ruler::ImplDrawIndent(vcl::RenderContext& rRenderContext, const tools::Polygon& rPoly, bool bIsHit) +{ + const StyleSettings& rStyleSettings = rRenderContext.GetSettings().GetStyleSettings(); + + rRenderContext.SetLineColor(rStyleSettings.GetDarkShadowColor()); + rRenderContext.SetFillColor(bIsHit ? rStyleSettings.GetDarkShadowColor() : rStyleSettings.GetWorkspaceColor()); + tools::Polygon aPolygon(rPoly); + aPolygon.Optimize(PolyOptimizeFlags::CLOSE); + rRenderContext.DrawPolygon(aPolygon); +} + +void Ruler::ImplDrawIndents(vcl::RenderContext& rRenderContext, long nMin, long nMax, long nVirTop, long nVirBottom) +{ + long n; + long nIndentHeight = (mnVirHeight / 2) - 1; + long nIndentWidth2 = nIndentHeight-3; + + tools::Polygon aPoly(5); + + for (std::vector<RulerIndent>::size_type j = 0; j < mpData->pIndents.size(); j++) + { + if (mpData->pIndents[j].bInvisible) + continue; + + RulerIndentStyle nIndentStyle = mpData->pIndents[j].nStyle; + + n = mpData->pIndents[j].nPos+mpData->nNullVirOff; + + if ((n >= nMin) && (n <= nMax)) + { + if (nIndentStyle == RulerIndentStyle::Bottom) + { + aPoly.SetPoint(Point(n + 0, nVirBottom - nIndentHeight), 0); + aPoly.SetPoint(Point(n - nIndentWidth2, nVirBottom - 3), 1); + aPoly.SetPoint(Point(n - nIndentWidth2, nVirBottom), 2); + aPoly.SetPoint(Point(n + nIndentWidth2, nVirBottom), 3); + aPoly.SetPoint(Point(n + nIndentWidth2, nVirBottom - 3), 4); + } + else + { + aPoly.SetPoint(Point(n + 0, nVirTop + nIndentHeight), 0); + aPoly.SetPoint(Point(n - nIndentWidth2, nVirTop + 3), 1); + aPoly.SetPoint(Point(n - nIndentWidth2, nVirTop), 2); + aPoly.SetPoint(Point(n + nIndentWidth2, nVirTop), 3); + aPoly.SetPoint(Point(n + nIndentWidth2, nVirTop + 3), 4); + } + + if (0 == (mnWinStyle & WB_HORZ)) + { + Point aTmp; + for (sal_uInt16 i = 0; i < 5; i++) + { + aTmp = aPoly[i]; + Point aSet(nVirBottom - aTmp.Y(), aTmp.X()); + aPoly[i] = aSet; + } + } + bool bIsHit = false; + if (mxCurrentHitTest != nullptr && mxCurrentHitTest->eType == RulerType::Indent) + { + bIsHit = mxCurrentHitTest->nAryPos == j; + } + else if(mbDrag && meDragType == RulerType::Indent) + { + bIsHit = mnDragAryPos == j; + } + ImplDrawIndent(rRenderContext, aPoly, bIsHit); + } + } +} + +static void ImplCenterTabPos(Point& rPos, sal_uInt16 nTabStyle) +{ + bool bRTL = 0 != (nTabStyle & RULER_TAB_RTL); + nTabStyle &= RULER_TAB_STYLE; + rPos.AdjustY(ruler_tab.height/2 ); + + if ( (!bRTL && nTabStyle == RULER_TAB_LEFT) || + ( bRTL && nTabStyle == RULER_TAB_RIGHT) ) + { + rPos.AdjustX( -(ruler_tab.width / 2) ); + } + else if ( (!bRTL && nTabStyle == RULER_TAB_RIGHT) || + ( bRTL && nTabStyle == RULER_TAB_LEFT) ) + { + rPos.AdjustX(ruler_tab.width / 2 ); + } +} + +static void lcl_RotateRect_Impl(tools::Rectangle& rRect, const long nReference, bool bRightAligned) +{ + if (rRect.IsEmpty()) + return; + + tools::Rectangle aTmp(rRect); + rRect.SetTop( aTmp.Left() ); + rRect.SetBottom( aTmp.Right() ); + rRect.SetLeft( aTmp.Top() ); + rRect.SetRight( aTmp.Bottom() ); + + if (bRightAligned) + { + long nRef = 2 * nReference; + rRect.SetLeft( nRef - rRect.Left() ); + rRect.SetRight( nRef - rRect.Right() ); + } +} + +static void ImplDrawRulerTab(vcl::RenderContext& rRenderContext, const Point& rPos, + sal_uInt16 nStyle, WinBits nWinBits) +{ + if (nStyle & RULER_STYLE_INVISIBLE) + return; + + sal_uInt16 nTabStyle = nStyle & RULER_TAB_STYLE; + bool bRTL = 0 != (nStyle & RULER_TAB_RTL); + + // Scale by the screen DPI scaling factor + // However when doing this some of the rectangles + // drawn become asymmetric due to the +1 offsets + sal_uInt16 DPIOffset = rRenderContext.GetDPIScaleFactor() - 1; + + tools::Rectangle aRect1; + tools::Rectangle aRect2; + tools::Rectangle aRect3; + + aRect3.SetEmpty(); + + if (nTabStyle == RULER_TAB_DEFAULT) + { + aRect1.SetLeft( rPos.X() - ruler_tab.dwidth2 + 1 ); + aRect1.SetTop( rPos.Y() - ruler_tab.dheight2 + 1 ); + aRect1.SetRight( rPos.X() - ruler_tab.dwidth2 + ruler_tab.dwidth + DPIOffset ); + aRect1.SetBottom( rPos.Y() ); + + aRect2.SetLeft( rPos.X() - ruler_tab.dwidth2 + ruler_tab.dwidth3 ); + aRect2.SetTop( rPos.Y() - ruler_tab.dheight + 1 ); + aRect2.SetRight( rPos.X() - ruler_tab.dwidth2 + ruler_tab.dwidth3 + ruler_tab.dwidth4 - 1 ); + aRect2.SetBottom( rPos.Y() ); + + } + else if ((!bRTL && nTabStyle == RULER_TAB_LEFT) || (bRTL && nTabStyle == RULER_TAB_RIGHT)) + { + aRect1.SetLeft( rPos.X() ); + aRect1.SetTop( rPos.Y() - ruler_tab.height2 + 1 ); + aRect1.SetRight( rPos.X() + ruler_tab.width - 1 ); + aRect1.SetBottom( rPos.Y() ); + + aRect2.SetLeft( rPos.X() ); + aRect2.SetTop( rPos.Y() - ruler_tab.height + 1 ); + aRect2.SetRight( rPos.X() + ruler_tab.width2 - 1 ); + aRect2.SetBottom( rPos.Y() ); + } + else if ((!bRTL && nTabStyle == RULER_TAB_RIGHT) || (bRTL && nTabStyle == RULER_TAB_LEFT)) + { + aRect1.SetLeft( rPos.X() - ruler_tab.width + 1 ); + aRect1.SetTop( rPos.Y() - ruler_tab.height2 + 1 ); + aRect1.SetRight( rPos.X() ); + aRect1.SetBottom( rPos.Y() ); + + aRect2.SetLeft( rPos.X() - ruler_tab.width2 + 1 ); + aRect2.SetTop( rPos.Y() - ruler_tab.height + 1 ); + aRect2.SetRight( rPos.X() ); + aRect2.SetBottom( rPos.Y() ); + } + else + { + aRect1.SetLeft( rPos.X() - ruler_tab.cwidth2 + 1 ); + aRect1.SetTop( rPos.Y() - ruler_tab.height2 + 1 ); + aRect1.SetRight( rPos.X() - ruler_tab.cwidth2 + ruler_tab.cwidth + DPIOffset ); + aRect1.SetBottom( rPos.Y() ); + + aRect2.SetLeft( rPos.X() - ruler_tab.cwidth2 + ruler_tab.cwidth3 ); + aRect2.SetTop( rPos.Y() - ruler_tab.height + 1 ); + aRect2.SetRight( rPos.X() - ruler_tab.cwidth2 + ruler_tab.cwidth3 + ruler_tab.cwidth4 - 1 ); + aRect2.SetBottom( rPos.Y() ); + + if (nTabStyle == RULER_TAB_DECIMAL) + { + aRect3.SetLeft( rPos.X() - ruler_tab.cwidth2 + ruler_tab.cwidth - 1 ); + aRect3.SetTop( rPos.Y() - ruler_tab.height + 1 + 1 - DPIOffset ); + aRect3.SetRight( rPos.X() - ruler_tab.cwidth2 + ruler_tab.cwidth + DPIOffset ); + aRect3.SetBottom( rPos.Y() - ruler_tab.height + 1 + 2 ); + } + } + if (0 == (nWinBits & WB_HORZ)) + { + bool bRightAligned = 0 != (nWinBits & WB_RIGHT_ALIGNED); + lcl_RotateRect_Impl(aRect1, rPos.Y(), bRightAligned); + lcl_RotateRect_Impl(aRect2, rPos.Y(), bRightAligned); + lcl_RotateRect_Impl(aRect3, rPos.Y(), bRightAligned); + } + rRenderContext.DrawRect(aRect1); + rRenderContext.DrawRect(aRect2); + + if (!aRect3.IsEmpty()) + rRenderContext.DrawRect(aRect3); +} + +void Ruler::ImplDrawTab(vcl::RenderContext& rRenderContext, const Point& rPos, sal_uInt16 nStyle) +{ + if (nStyle & RULER_STYLE_INVISIBLE) + return; + + rRenderContext.SetLineColor(); + + if (nStyle & RULER_STYLE_DONTKNOW) + rRenderContext.SetFillColor(rRenderContext.GetSettings().GetStyleSettings().GetFaceColor()); + else + rRenderContext.SetFillColor(rRenderContext.GetSettings().GetStyleSettings().GetDarkShadowColor()); + + if (mpData->bTextRTL) + nStyle |= RULER_TAB_RTL; + + ImplDrawRulerTab(rRenderContext, rPos, nStyle, GetStyle()); +} + +void Ruler::ImplDrawTabs(vcl::RenderContext& rRenderContext, long nMin, long nMax, long nVirTop, long nVirBottom) +{ + for (const RulerTab & rTab : mpData->pTabs) + { + if (rTab.nStyle & RULER_STYLE_INVISIBLE) + continue; + + long aPosition; + aPosition = rTab.nPos; + aPosition += +mpData->nNullVirOff; + long nTopBottom = (GetStyle() & WB_RIGHT_ALIGNED) ? nVirTop : nVirBottom; + if (nMin <= aPosition && aPosition <= nMax) + ImplDrawTab(rRenderContext, Point( aPosition, nTopBottom ), rTab.nStyle); + } +} + +static int adjustSize(int nOrig) +{ + if (nOrig <= 0) + return 0; + + // make sure we return an odd number, that looks better in the ruler + return ( (3*nOrig) / 8) * 2 + 1; +} + +void Ruler::ApplySettings(vcl::RenderContext& rRenderContext) +{ + const StyleSettings& rStyleSettings = rRenderContext.GetSettings().GetStyleSettings(); + + vcl::Font aFont = rStyleSettings.GetToolFont(); + // make the font a bit smaller than default + Size aSize(adjustSize(aFont.GetFontSize().Width()), adjustSize(aFont.GetFontSize().Height())); + aFont.SetFontSize(aSize); + + ApplyControlFont(rRenderContext, aFont); + + ApplyControlForeground(*this, rStyleSettings.GetDarkShadowColor()); + SetTextFillColor(); + + Color aColor; + svtools::ColorConfig aColorConfig; + aColor = aColorConfig.GetColorValue(svtools::APPBACKGROUND).nColor; + ApplyControlBackground(rRenderContext, aColor); +} + +void Ruler::ImplInitSettings(bool bFont, bool bForeground, bool bBackground) +{ + const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings(); + + if (bFont) + { + vcl::Font aFont = rStyleSettings.GetToolFont(); + // make the font a bit smaller than default + Size aSize(adjustSize(aFont.GetFontSize().Width()), adjustSize(aFont.GetFontSize().Height())); + aFont.SetFontSize(aSize); + + ApplyControlFont(*this, aFont); + } + + if (bForeground || bFont) + { + ApplyControlForeground(*this, rStyleSettings.GetDarkShadowColor()); + SetTextFillColor(); + } + + if (bBackground) + { + Color aColor; + svtools::ColorConfig aColorConfig; + aColor = aColorConfig.GetColorValue(svtools::APPBACKGROUND).nColor; + ApplyControlBackground(*this, aColor); + } + + maVirDev->SetSettings( GetSettings() ); + maVirDev->SetBackground( GetBackground() ); + vcl::Font aFont = GetFont(); + + if (mnWinStyle & WB_VERT) + aFont.SetOrientation(900); + + maVirDev->SetFont(aFont); + maVirDev->SetTextColor(GetTextColor()); + maVirDev->SetTextFillColor(GetTextFillColor()); +} + +void Ruler::ImplCalc() +{ + // calculate offset + mpData->nRulVirOff = mnWinOff + mpData->nPageOff; + if ( mpData->nRulVirOff > mnVirOff ) + mpData->nRulVirOff -= mnVirOff; + else + mpData->nRulVirOff = 0; + long nRulWinOff = mpData->nRulVirOff+mnVirOff; + + // calculate non-visual part of the page + long nNotVisPageWidth; + if ( mpData->nPageOff < 0 ) + { + nNotVisPageWidth = -(mpData->nPageOff); + if ( nRulWinOff < mnWinOff ) + nNotVisPageWidth -= mnWinOff-nRulWinOff; + } + else + nNotVisPageWidth = 0; + + // calculate width + if ( mnWinStyle & WB_HORZ ) + { + if ( mbAutoWinWidth ) + mnWinWidth = mnWidth - mnVirOff; + if ( mpData->bAutoPageWidth ) + mpData->nPageWidth = mnWinWidth; + mpData->nRulWidth = std::min( mnWinWidth, mpData->nPageWidth-nNotVisPageWidth ); + if ( nRulWinOff+mpData->nRulWidth > mnWidth ) + mpData->nRulWidth = mnWidth-nRulWinOff; + } + else + { + if ( mbAutoWinWidth ) + mnWinWidth = mnHeight - mnVirOff; + if ( mpData->bAutoPageWidth ) + mpData->nPageWidth = mnWinWidth; + mpData->nRulWidth = std::min( mnWinWidth, mpData->nPageWidth-nNotVisPageWidth ); + if ( nRulWinOff+mpData->nRulWidth > mnHeight ) + mpData->nRulWidth = mnHeight-nRulWinOff; + } + + mbCalc = false; +} + +void Ruler::ImplFormat(vcl::RenderContext const & rRenderContext) +{ + // if already formatted, don't do it again + if (!mbFormat) + return; + + // don't do anything if the window still has no size + if (!mnVirWidth) + return; + + const StyleSettings& rStyleSettings = rRenderContext.GetSettings().GetStyleSettings(); + long nP1; // pixel position of Page1 + long nP2; // pixel position of Page2 + long nM1; // pixel position of Margin1 + long nM2; // pixel position of Margin2 + long nVirTop; // top/left corner + long nVirBottom; // bottom/right corner + long nVirLeft; // left/top corner + long nVirRight; // right/bottom corner + long nNullVirOff; // for faster calculation + + // calculate values + if (mbCalc) + ImplCalc(); + + mpData->nNullVirOff = mnWinOff + mpData->nPageOff + mpData->nNullOff - mnVirOff; + + nNullVirOff = mpData->nNullVirOff; + nVirLeft = mpData->nRulVirOff; + nVirRight = nVirLeft + mpData->nRulWidth - 1; + nVirTop = 0; + nVirBottom = mnVirHeight - 1; + + if (!IsReallyVisible()) + return; + + Size aVirDevSize; + + // initialize VirtualDevice + if (mnWinStyle & WB_HORZ) + { + aVirDevSize.setWidth( mnVirWidth ); + aVirDevSize.setHeight( mnVirHeight ); + } + else + { + aVirDevSize.setHeight( mnVirWidth ); + aVirDevSize.setWidth( mnVirHeight ); + } + if (aVirDevSize != maVirDev->GetOutputSizePixel()) + maVirDev->SetOutputSizePixel(aVirDevSize); + else + maVirDev->Erase(); + + // calculate margins + if (!(mpData->nMargin1Style & RulerMarginStyle::Invisible)) + { + nM1 = mpData->nMargin1 + nNullVirOff; + if (mpData->bAutoPageWidth) + { + nP1 = nVirLeft; + if (nM1 < nVirLeft) + nP1--; + } + else + nP1 = nNullVirOff - mpData->nNullOff; + } + else + { + nM1 = nVirLeft-1; + nP1 = nM1; + } + if (!(mpData->nMargin2Style & RulerMarginStyle::Invisible)) + { + nM2 = mpData->nMargin2 + nNullVirOff; + if (mpData->bAutoPageWidth) + { + nP2 = nVirRight; + if (nM2 > nVirRight) + nP2++; + } + else + nP2 = nNullVirOff - mpData->nNullOff + mpData->nPageWidth; + if (nM2 > nP2) + nM2 = nP2; + } + else + { + nM2 = nVirRight+1; + nP2 = nM2; + } + + // top/bottom border + maVirDev->SetLineColor(rStyleSettings.GetShadowColor()); + ImplVDrawLine(*maVirDev, nVirLeft, nVirTop + 1, nM1, nVirTop + 1); //top left line + ImplVDrawLine(*maVirDev, nM2, nVirTop + 1, nP2 - 1, nVirTop + 1); //top right line + + nVirTop++; + nVirBottom--; + + // draw margin1, margin2 and in-between + maVirDev->SetLineColor(); + maVirDev->SetFillColor(rStyleSettings.GetDialogColor()); + if (nM1 > nVirLeft) + ImplVDrawRect(*maVirDev, nP1, nVirTop + 1, nM1, nVirBottom); //left gray rectangle + if (nM2 < nP2) + ImplVDrawRect(*maVirDev, nM2, nVirTop + 1, nP2, nVirBottom); //right gray rectangle + if (nM2 - nM1 > 0) + { + maVirDev->SetFillColor(rStyleSettings.GetWindowColor()); + ImplVDrawRect(*maVirDev, nM1 + 1, nVirTop, nM2 - 1, nVirBottom); //center rectangle + } + maVirDev->SetLineColor(rStyleSettings.GetShadowColor()); + if (nM1 > nVirLeft) + { + ImplVDrawLine(*maVirDev, nM1, nVirTop + 1, nM1, nVirBottom); //right line of the left rectangle + ImplVDrawLine(*maVirDev, nP1, nVirBottom, nM1, nVirBottom); //bottom line of the left rectangle + if (nP1 >= nVirLeft) + { + ImplVDrawLine(*maVirDev, nP1, nVirTop + 1, nP1, nVirBottom); //left line of the left rectangle + ImplVDrawLine(*maVirDev, nP1, nVirBottom, nP1 + 1, nVirBottom); //? + } + } + if (nM2 < nP2) + { + ImplVDrawLine(*maVirDev, nM2, nVirBottom, nP2 - 1, nVirBottom); //bottom line of the right rectangle + ImplVDrawLine(*maVirDev, nM2, nVirTop + 1, nM2, nVirBottom); //left line of the right rectangle + if (nP2 <= nVirRight + 1) + ImplVDrawLine(*maVirDev, nP2 - 1, nVirTop + 1, nP2 - 1, nVirBottom); //right line of the right rectangle + } + + long nMin = nVirLeft; + long nMax = nP2; + long nStart = 0; + + if (mpData->bTextRTL) + nStart = mpData->nRightFrameMargin + nNullVirOff; + else + nStart = mpData->nLeftFrameMargin + nNullVirOff; + + if (nP1 > nVirLeft) + nMin++; + + if (nP2 < nVirRight) + nMax--; + + // Draw captions + ImplDrawTicks(*maVirDev, nMin, nMax, nStart, nVirTop, nVirBottom); + + // Draw borders + if (!mpData->pBorders.empty()) + ImplDrawBorders(*maVirDev, nVirLeft, nP2, nVirTop, nVirBottom); + + // Draw indents + if (!mpData->pIndents.empty()) + ImplDrawIndents(*maVirDev, nVirLeft, nP2, nVirTop - 1, nVirBottom + 1); + + // Tabs + if (!mpData->pTabs.empty()) + ImplDrawTabs(*maVirDev, nVirLeft, nP2, nVirTop-1, nVirBottom + 1); + + mbFormat = false; +} + +void Ruler::ImplInitExtraField( bool bUpdate ) +{ + Size aWinSize = GetOutputSizePixel(); + + // extra field evaluate + if ( mnWinStyle & WB_EXTRAFIELD ) + { + maExtraRect.SetLeft( RULER_OFF ); + maExtraRect.SetTop( RULER_OFF ); + maExtraRect.SetRight( RULER_OFF + mnVirHeight - 1 ); + maExtraRect.SetBottom( RULER_OFF + mnVirHeight - 1 ); + if(mpData->bTextRTL) + { + if(mnWinStyle & WB_HORZ) + maExtraRect.Move(aWinSize.Width() - maExtraRect.GetWidth() - maExtraRect.Left(), 0); + else + maExtraRect.Move(0, aWinSize.Height() - maExtraRect.GetHeight() - maExtraRect.Top()); + mnVirOff = 0; + } + else + mnVirOff = maExtraRect.Right()+1; + + } + else + { + maExtraRect.SetEmpty(); + mnVirOff = 0; + } + + // mnVirWidth depends on mnVirOff + if ( (mnVirWidth > RULER_MIN_SIZE) || + ((aWinSize.Width() > RULER_MIN_SIZE) && (aWinSize.Height() > RULER_MIN_SIZE)) ) + { + if ( mnWinStyle & WB_HORZ ) + mnVirWidth = aWinSize.Width()-mnVirOff; + else + mnVirWidth = aWinSize.Height()-mnVirOff; + + if ( mnVirWidth < RULER_MIN_SIZE ) + mnVirWidth = 0; + } + + if ( bUpdate ) + { + mbCalc = true; + mbFormat = true; + Invalidate(); + } +} + +void Ruler::ImplDraw(vcl::RenderContext& rRenderContext) +{ + if (mbFormat) + { + ImplFormat(rRenderContext); + } + + if (!IsReallyVisible()) + return; + + // output the ruler to the virtual device + Point aOffPos; + Size aVirDevSize = maVirDev->GetOutputSizePixel(); + + if (mnWinStyle & WB_HORZ) + { + aOffPos.setX( mnVirOff ); + if (mpData->bTextRTL) + aVirDevSize.AdjustWidth( -(maExtraRect.GetWidth()) ); + + aOffPos.setY( RULER_OFF ); + } + else + { + aOffPos.setX( RULER_OFF ); + aOffPos.setY( mnVirOff ); + } + rRenderContext.DrawOutDev(aOffPos, aVirDevSize, Point(), aVirDevSize, *maVirDev); + + // redraw positionlines + ImplInvertLines(rRenderContext); +} + +void Ruler::ImplDrawExtra(vcl::RenderContext& rRenderContext) +{ + const StyleSettings& rStyleSettings = rRenderContext.GetSettings().GetStyleSettings(); + tools::Rectangle aRect = maExtraRect; + bool bEraseRect = false; + + aRect.AdjustLeft(2 ); + aRect.AdjustTop(2 ); + aRect.AdjustRight( -2 ); + aRect.AdjustBottom( -2 ); + + if (mnExtraStyle & RULER_STYLE_HIGHLIGHT) + { + rRenderContext.SetFillColor(rStyleSettings.GetCheckedColor()); + bEraseRect = true; + } + + if (bEraseRect) + { + rRenderContext.SetLineColor(); + rRenderContext.DrawRect(aRect); + } + + // output content + if (meExtraType == RulerExtra::NullOffset) + { + rRenderContext.SetLineColor(rStyleSettings.GetButtonTextColor()); + rRenderContext.DrawLine(Point(aRect.Left() + 1, aRect.Top() + 4), + Point(aRect.Right() - 1, aRect.Top() + 4)); + rRenderContext.DrawLine(Point(aRect.Left() + 4, aRect.Top() + 1), + Point(aRect.Left() + 4, aRect.Bottom() - 1)); + } + else if (meExtraType == RulerExtra::Tab) + { + sal_uInt16 nTabStyle = mnExtraStyle & RULER_TAB_STYLE; + if (mpData->bTextRTL) + nTabStyle |= RULER_TAB_RTL; + Point aCenter = aRect.Center(); + Point aDraw(aCenter); + ImplCenterTabPos(aDraw, nTabStyle); + WinBits nWinBits = GetStyle(); + if (0 == (nWinBits & WB_HORZ)) + { + if ((nWinBits & WB_RIGHT_ALIGNED) != 0) + aDraw.setY( 2 * aCenter.Y() - aDraw.Y() ); + + if (mpData->bTextRTL) + { + long nTemp = aDraw.X(); + aDraw.setX( aDraw.Y() ); + aDraw.setY( nTemp ); + } + } + ImplDrawTab(rRenderContext, aDraw, nTabStyle); + } +} + +void Ruler::ImplUpdate( bool bMustCalc ) +{ + // clear lines in this place so they aren't considered at recalculation + if (!mbFormat) + Invalidate(InvalidateFlags::NoErase); + + // set flags + if (bMustCalc) + mbCalc = true; + mbFormat = true; + + // abort if we are dragging as drag-handler will update the ruler after drag is finished + if (mbDrag) + return; + + // otherwise trigger update + if (IsReallyVisible() && IsUpdateMode()) + { + Invalidate(InvalidateFlags::NoErase); + } +} + +bool Ruler::ImplHitTest( const Point& rPos, RulerSelection* pHitTest, + bool bRequireStyle, RulerIndentStyle nRequiredStyle ) const +{ + sal_Int32 i; + sal_uInt16 nStyle; + long nHitBottom; + long nX; + long nY; + long n1; + + if ( !mbActive ) + return false; + + // determine positions + bool bIsHori = 0 != (mnWinStyle & WB_HORZ); + if ( bIsHori ) + { + nX = rPos.X(); + nY = rPos.Y(); + } + else + { + nX = rPos.Y(); + nY = rPos.X(); + } + nHitBottom = mnVirHeight + (RULER_OFF * 2); + + // #i32608# + pHitTest->nAryPos = 0; + pHitTest->mnDragSize = RulerDragSize::Move; + pHitTest->bSize = false; + pHitTest->bSizeBar = false; + + // so that leftover tabs and indents are taken into account + long nXExtraOff; + if ( !mpData->pTabs.empty() || !mpData->pIndents.empty() ) + nXExtraOff = (mnVirHeight / 2) - 4; + else + nXExtraOff = 0; + + // test if outside + nX -= mnVirOff; + if ( (nX < mpData->nRulVirOff - nXExtraOff) || + (nX > mpData->nRulVirOff + mpData->nRulWidth + nXExtraOff) || + (nY < 0) || + (nY > nHitBottom) ) + { + pHitTest->nPos = 0; + pHitTest->eType = RulerType::Outside; + return false; + } + + nX -= mpData->nNullVirOff; + pHitTest->nPos = nX; + pHitTest->eType = RulerType::DontKnow; + + // first test the tabs + tools::Rectangle aRect; + if ( !mpData->pTabs.empty() ) + { + aRect.SetBottom( nHitBottom ); + aRect.SetTop( aRect.Bottom() - ruler_tab.height - RULER_OFF ); + + for ( i = mpData->pTabs.size() - 1; i >= 0; i-- ) + { + nStyle = mpData->pTabs[i].nStyle; + if ( !(nStyle & RULER_STYLE_INVISIBLE) ) + { + nStyle &= RULER_TAB_STYLE; + + // default tabs are only shown (no action) + if ( nStyle != RULER_TAB_DEFAULT ) + { + n1 = mpData->pTabs[i].nPos; + + if ( nStyle == RULER_TAB_LEFT ) + { + aRect.SetLeft( n1 ); + aRect.SetRight( n1 + ruler_tab.width - 1 ); + } + else if ( nStyle == RULER_TAB_RIGHT ) + { + aRect.SetRight( n1 ); + aRect.SetLeft( n1 - ruler_tab.width - 1 ); + } + else + { + aRect.SetLeft( n1 - ruler_tab.cwidth2 + 1 ); + aRect.SetRight( n1 - ruler_tab.cwidth2 + ruler_tab.cwidth ); + } + + if ( aRect.IsInside( Point( nX, nY ) ) ) + { + pHitTest->eType = RulerType::Tab; + pHitTest->nAryPos = i; + return true; + } + } + } + } + } + + // Indents + if ( !mpData->pIndents.empty() ) + { + long nIndentHeight = (mnVirHeight / 2) - 1; + long nIndentWidth2 = nIndentHeight - 3; + + for ( i = mpData->pIndents.size(); i; i-- ) + { + RulerIndentStyle nIndentStyle = mpData->pIndents[i-1].nStyle; + if ( (! bRequireStyle || nIndentStyle == nRequiredStyle) && + !mpData->pIndents[i-1].bInvisible ) + { + n1 = mpData->pIndents[i-1].nPos; + + if ( (nIndentStyle == RulerIndentStyle::Bottom) != !bIsHori ) + { + aRect.SetLeft( n1-nIndentWidth2 ); + aRect.SetRight( n1+nIndentWidth2 ); + aRect.SetTop( nHitBottom-nIndentHeight-RULER_OFF+1 ); + aRect.SetBottom( nHitBottom ); + } + else + { + aRect.SetLeft( n1-nIndentWidth2 ); + aRect.SetRight( n1+nIndentWidth2 ); + aRect.SetTop( 0 ); + aRect.SetBottom( nIndentHeight+RULER_OFF-1 ); + } + + if ( aRect.IsInside( Point( nX, nY ) ) ) + { + pHitTest->eType = RulerType::Indent; + pHitTest->nAryPos = i-1; + return true; + } + } + } + } + + // test the borders + int nBorderTolerance = 1; + if(pHitTest->bExpandTest) + { + nBorderTolerance++; + } + + for ( i = mpData->pBorders.size(); i; i-- ) + { + n1 = mpData->pBorders[i-1].nPos; + long n2 = n1 + mpData->pBorders[i-1].nWidth; + + // borders have at least 3 pixel padding + if ( !mpData->pBorders[i-1].nWidth ) + { + n1 -= nBorderTolerance; + n2 += nBorderTolerance; + + } + + if ( (nX >= n1) && (nX <= n2) ) + { + RulerBorderStyle nBorderStyle = mpData->pBorders[i-1].nStyle; + if ( !(nBorderStyle & RulerBorderStyle::Invisible) ) + { + pHitTest->eType = RulerType::Border; + pHitTest->nAryPos = i-1; + + if ( !(nBorderStyle & RulerBorderStyle::Sizeable) ) + { + if ( nBorderStyle & RulerBorderStyle::Moveable ) + { + pHitTest->bSizeBar = true; + pHitTest->mnDragSize = RulerDragSize::Move; + } + } + else + { + long nMOff = RULER_MOUSE_BORDERWIDTH; + while ( nMOff*2 >= (n2-n1-RULER_MOUSE_BORDERMOVE) ) + { + if ( nMOff < 2 ) + { + nMOff = 0; + break; + } + else + nMOff--; + } + + if ( nX <= n1+nMOff ) + { + pHitTest->bSize = true; + pHitTest->mnDragSize = RulerDragSize::N1; + } + else if ( nX >= n2-nMOff ) + { + pHitTest->bSize = true; + pHitTest->mnDragSize = RulerDragSize::N2; + } + else + { + if ( nBorderStyle & RulerBorderStyle::Moveable ) + { + pHitTest->bSizeBar = true; + pHitTest->mnDragSize = RulerDragSize::Move; + } + } + } + + return true; + } + } + } + + // Margins + int nMarginTolerance = pHitTest->bExpandTest ? nBorderTolerance : RULER_MOUSE_MARGINWIDTH; + + if ( (mpData->nMargin1Style & (RulerMarginStyle::Sizeable | RulerMarginStyle::Invisible)) == RulerMarginStyle::Sizeable ) + { + n1 = mpData->nMargin1; + if ( (nX >= n1 - nMarginTolerance) && (nX <= n1 + nMarginTolerance) ) + { + pHitTest->eType = RulerType::Margin1; + pHitTest->bSize = true; + return true; + } + } + if ( (mpData->nMargin2Style & (RulerMarginStyle::Sizeable | RulerMarginStyle::Invisible)) == RulerMarginStyle::Sizeable ) + { + n1 = mpData->nMargin2; + if ( (nX >= n1 - nMarginTolerance) && (nX <= n1 + nMarginTolerance) ) + { + pHitTest->eType = RulerType::Margin2; + pHitTest->bSize = true; + return true; + } + } + + // test tabs again + if ( !mpData->pTabs.empty() ) + { + aRect.SetTop( RULER_OFF ); + aRect.SetBottom( nHitBottom ); + + for ( i = mpData->pTabs.size() - 1; i >= 0; i-- ) + { + nStyle = mpData->pTabs[i].nStyle; + if ( !(nStyle & RULER_STYLE_INVISIBLE) ) + { + nStyle &= RULER_TAB_STYLE; + + // default tabs are only shown (no action) + if ( nStyle != RULER_TAB_DEFAULT ) + { + n1 = mpData->pTabs[i].nPos; + + if ( nStyle == RULER_TAB_LEFT ) + { + aRect.SetLeft( n1 ); + aRect.SetRight( n1 + ruler_tab.width - 1 ); + } + else if ( nStyle == RULER_TAB_RIGHT ) + { + aRect.SetRight( n1 ); + aRect.SetLeft( n1 - ruler_tab.width - 1 ); + } + else + { + aRect.SetLeft( n1 - ruler_tab.cwidth2 + 1 ); + aRect.SetRight( n1 - ruler_tab.cwidth2 + ruler_tab.cwidth ); + } + + aRect.AdjustLeft( -1 ); + aRect.AdjustRight( 1 ); + + if ( aRect.IsInside( Point( nX, nY ) ) ) + { + pHitTest->eType = RulerType::Tab; + pHitTest->nAryPos = i; + return true; + } + } + } + } + } + + return false; +} + +bool Ruler::ImplDocHitTest( const Point& rPos, RulerType eDragType, + RulerSelection* pHitTest ) const +{ + Point aPos = rPos; + bool bRequiredStyle = false; + RulerIndentStyle nRequiredStyle = RulerIndentStyle::Top; + + if (eDragType == RulerType::Indent) + { + bRequiredStyle = true; + nRequiredStyle = RulerIndentStyle::Bottom; + } + + if ( mnWinStyle & WB_HORZ ) + aPos.AdjustX(mnWinOff ); + else + aPos.AdjustY(mnWinOff ); + + if ( (eDragType == RulerType::Indent) || (eDragType == RulerType::DontKnow) ) + { + if ( mnWinStyle & WB_HORZ ) + aPos.setY( RULER_OFF + 1 ); + else + aPos.setX( RULER_OFF + 1 ); + + if ( ImplHitTest( aPos, pHitTest, bRequiredStyle, nRequiredStyle ) ) + { + if ( (pHitTest->eType == eDragType) || (eDragType == RulerType::DontKnow) ) + return true; + } + } + + if ( (eDragType == RulerType::Indent) || + (eDragType == RulerType::Tab) || + (eDragType == RulerType::DontKnow) ) + { + if ( mnWinStyle & WB_HORZ ) + aPos.setY( mnHeight - RULER_OFF - 1 ); + else + aPos.setX( mnWidth - RULER_OFF - 1 ); + + if ( ImplHitTest( aPos, pHitTest, bRequiredStyle, nRequiredStyle ) ) + { + if ( (pHitTest->eType == eDragType) || (eDragType == RulerType::DontKnow) ) + return true; + } + } + + if ( (eDragType == RulerType::Margin1) || (eDragType == RulerType::Margin2) || + (eDragType == RulerType::Border) || (eDragType == RulerType::DontKnow) ) + { + if ( mnWinStyle & WB_HORZ ) + aPos.setY( RULER_OFF + (mnVirHeight / 2) ); + else + aPos.setX( RULER_OFF + (mnVirHeight / 2) ); + + if ( ImplHitTest( aPos, pHitTest ) ) + { + if ( (pHitTest->eType == eDragType) || (eDragType == RulerType::DontKnow) ) + return true; + } + } + + pHitTest->eType = RulerType::DontKnow; + + return false; +} + +bool Ruler::ImplStartDrag( RulerSelection const * pHitTest, sal_uInt16 nModifier ) +{ + // don't trigger drag if a border that was clicked can not be changed + if ( (pHitTest->eType == RulerType::Border) && + !pHitTest->bSize && !pHitTest->bSizeBar ) + return false; + + // Set drag data + meDragType = pHitTest->eType; + mnDragPos = pHitTest->nPos; + mnDragAryPos = pHitTest->nAryPos; + mnDragSize = pHitTest->mnDragSize; + mnDragModifier = nModifier; + *mpDragData = *mpSaveData; + mpData = mpDragData.get(); + + // call handler + if (StartDrag()) + { + // if the handler allows dragging, initialize dragging + mbDrag = true; + mnStartDragPos = mnDragPos; + StartTracking(); + Invalidate(InvalidateFlags::NoErase); + return true; + } + else + { + // otherwise reset the data + meDragType = RulerType::DontKnow; + mnDragPos = 0; + mnDragAryPos = 0; + mnDragSize = RulerDragSize::Move; + mnDragModifier = 0; + mpData = mpSaveData.get(); + } + + return false; +} + +void Ruler::ImplDrag( const Point& rPos ) +{ + long nX; + long nY; + long nOutHeight; + + if ( mnWinStyle & WB_HORZ ) + { + nX = rPos.X(); + nY = rPos.Y(); + nOutHeight = mnHeight; + } + else + { + nX = rPos.Y(); + nY = rPos.X(); + nOutHeight = mnWidth; + } + + // calculate and fit X + nX -= mnVirOff; + if ( nX < mpData->nRulVirOff ) + { + nX = mpData->nRulVirOff; + } + else if ( nX > mpData->nRulVirOff+mpData->nRulWidth ) + { + nX = mpData->nRulVirOff+mpData->nRulWidth; + } + nX -= mpData->nNullVirOff; + + // if upper or left from ruler, then consider old values + mbDragDelete = false; + if ( nY < 0 ) + { + if ( !mbDragCanceled ) + { + // reset the data + mbDragCanceled = true; + ImplRulerData aTempData = *mpDragData; + *mpDragData = *mpSaveData; + mbCalc = true; + mbFormat = true; + + // call handler + mnDragPos = mnStartDragPos; + Drag(); + + // and redraw + Invalidate(InvalidateFlags::NoErase); + + // reset the data as before cancel + *mpDragData = aTempData; + } + } + else + { + mbDragCanceled = false; + + // +2, so the tabs are not cleared too quickly + if ( nY > nOutHeight + 2 ) + mbDragDelete = true; + + mnDragPos = nX; + + // call handler + Drag(); + + // redraw + if (mbFormat) + Invalidate(InvalidateFlags::NoErase); + } +} + +void Ruler::ImplEndDrag() +{ + // get values + if ( mbDragCanceled ) + *mpDragData = *mpSaveData; + else + *mpSaveData = *mpDragData; + + mpData = mpSaveData.get(); + mbDrag = false; + + // call handler + EndDrag(); + + // reset drag values + meDragType = RulerType::DontKnow; + mnDragPos = 0; + mnDragAryPos = 0; + mnDragSize = RulerDragSize::Move; + mbDragCanceled = false; + mbDragDelete = false; + mnDragModifier = 0; + mnStartDragPos = 0; + + // redraw + Invalidate(InvalidateFlags::NoErase); +} + +void Ruler::MouseButtonDown( const MouseEvent& rMEvt ) +{ + if ( !(rMEvt.IsLeft() && !IsTracking()) ) + return; + + Point aMousePos = rMEvt.GetPosPixel(); + sal_uInt16 nMouseClicks = rMEvt.GetClicks(); + sal_uInt16 nMouseModifier = rMEvt.GetModifier(); + + // update ruler + if ( mbFormat ) + { + Invalidate(InvalidateFlags::NoErase); + } + + if ( maExtraRect.IsInside( aMousePos ) ) + { + ExtraDown(); + } + else + { + std::unique_ptr<RulerSelection> pHitTest(new RulerSelection); + bool bHitTestResult = ImplHitTest(aMousePos, pHitTest.get()); + + if ( nMouseClicks == 1 ) + { + if ( bHitTestResult ) + { + ImplStartDrag( pHitTest.get(), nMouseModifier ); + } + else + { + // calculate position inside of ruler area + if ( pHitTest->eType == RulerType::DontKnow ) + { + mnDragPos = pHitTest->nPos; + Click(); + mnDragPos = 0; + + // call HitTest again as a click, for example, could set a new tab + if ( ImplHitTest(aMousePos, pHitTest.get()) ) + ImplStartDrag(pHitTest.get(), nMouseModifier); + } + } + } + else + { + if (bHitTestResult) + { + mnDragPos = pHitTest->nPos; + mnDragAryPos = pHitTest->nAryPos; + } + meDragType = pHitTest->eType; + + DoubleClick(); + + meDragType = RulerType::DontKnow; + mnDragPos = 0; + mnDragAryPos = 0; + } + } +} + +void Ruler::MouseMove( const MouseEvent& rMEvt ) +{ + PointerStyle ePtrStyle = PointerStyle::Arrow; + + mxPreviousHitTest.swap(mxCurrentHitTest); + + mxCurrentHitTest.reset(new RulerSelection); + + maHoverSelection.eType = RulerType::DontKnow; + + if (ImplHitTest( rMEvt.GetPosPixel(), mxCurrentHitTest.get() )) + { + maHoverSelection = *mxCurrentHitTest; + + if (mxCurrentHitTest->bSize) + { + if (mnWinStyle & WB_HORZ) + { + if (mxCurrentHitTest->mnDragSize == RulerDragSize::N1) + ePtrStyle = PointerStyle::TabSelectW; + else if (mxCurrentHitTest->mnDragSize == RulerDragSize::N2) + ePtrStyle = PointerStyle::TabSelectE; + else + ePtrStyle = PointerStyle::ESize; + } + else + { + if (mxCurrentHitTest->mnDragSize == RulerDragSize::N1) + ePtrStyle = PointerStyle::WindowNSize; + else if (mxCurrentHitTest->mnDragSize == RulerDragSize::N2) + ePtrStyle = PointerStyle::WindowSSize; + else + ePtrStyle = PointerStyle::SSize; + } + } + else if (mxCurrentHitTest->bSizeBar) + { + if (mnWinStyle & WB_HORZ) + ePtrStyle = PointerStyle::HSizeBar; + else + ePtrStyle = PointerStyle::VSizeBar; + } + } + + if (mxPreviousHitTest != nullptr && mxPreviousHitTest->eType != mxCurrentHitTest->eType) + { + mbFormat = true; + } + + SetPointer( ePtrStyle ); + + if (mbFormat) + { + Invalidate(InvalidateFlags::NoErase); + } +} + +void Ruler::Tracking( const TrackingEvent& rTEvt ) +{ + if ( rTEvt.IsTrackingEnded() ) + { + // reset the old state at cancel + if ( rTEvt.IsTrackingCanceled() ) + { + mbDragCanceled = true; + mbFormat = true; + } + + ImplEndDrag(); + } + else + ImplDrag( rTEvt.GetMouseEvent().GetPosPixel() ); +} + +void Ruler::Paint(vcl::RenderContext& rRenderContext, const tools::Rectangle&) +{ + ImplDraw(rRenderContext); + + // consider extra field + if (mnWinStyle & WB_EXTRAFIELD) + ImplDrawExtra(rRenderContext); +} + +void Ruler::Resize() +{ + Size aWinSize = GetOutputSizePixel(); + + long nNewHeight; + if ( mnWinStyle & WB_HORZ ) + { + if ( aWinSize.Height() != mnHeight ) + nNewHeight = aWinSize.Height(); + else + nNewHeight = 0; + } + else + { + if ( aWinSize.Width() != mnWidth ) + nNewHeight = aWinSize.Width(); + else + nNewHeight = 0; + } + + mbFormat = true; + + // clear lines + bool bVisible = IsReallyVisible(); + if ( bVisible && !mpData->pLines.empty() ) + { + mnUpdateFlags |= RULER_UPDATE_LINES; + Invalidate(InvalidateFlags::NoErase); + } + + // recalculate some values if the height/width changes + // extra field should always be updated + ImplInitExtraField( mpData->bTextRTL ); + if ( nNewHeight ) + { + mbCalc = true; + mnVirHeight = nNewHeight - mnBorderWidth - ( RULER_OFF * 2 ); + } + else + { + if ( mpData->bAutoPageWidth ) + ImplUpdate( true ); + else if ( mbAutoWinWidth ) + mbCalc = true; + } + + // clear part of the border + if ( bVisible ) + { + if ( nNewHeight ) + Invalidate(InvalidateFlags::NoErase); + else if ( mpData->bAutoPageWidth ) + { + // only at AutoPageWidth do we need to redraw + tools::Rectangle aRect; + + if ( mnWinStyle & WB_HORZ ) + { + if ( mnWidth < aWinSize.Width() ) + aRect.SetLeft( mnWidth - RULER_RESIZE_OFF ); + else + aRect.SetLeft( aWinSize.Width() - RULER_RESIZE_OFF ); + aRect.SetRight( aRect.Left() + RULER_RESIZE_OFF ); + aRect.SetTop( RULER_OFF ); + aRect.SetBottom( RULER_OFF + mnVirHeight ); + } + else + { + if ( mnHeight < aWinSize.Height() ) + aRect.SetTop( mnHeight-RULER_RESIZE_OFF ); + else + aRect.SetTop( aWinSize.Height()-RULER_RESIZE_OFF ); + aRect.SetBottom( aRect.Top() + RULER_RESIZE_OFF ); + aRect.SetLeft( RULER_OFF ); + aRect.SetRight( RULER_OFF + mnVirHeight ); + } + + Invalidate(aRect, InvalidateFlags::NoErase); + } + } + + mnWidth = aWinSize.Width(); + mnHeight = aWinSize.Height(); +} + +void Ruler::StateChanged( StateChangedType nType ) +{ + Window::StateChanged( nType ); + + if ( nType == StateChangedType::InitShow ) + Invalidate(); + else if ( nType == StateChangedType::UpdateMode ) + { + if ( IsReallyVisible() && IsUpdateMode() ) + Invalidate(); + } + else if ( (nType == StateChangedType::Zoom) || + (nType == StateChangedType::ControlFont) ) + { + ImplInitSettings( true, false, false ); + Invalidate(); + } + else if ( nType == StateChangedType::ControlForeground ) + { + ImplInitSettings( false, true, false ); + Invalidate(); + } + else if ( nType == StateChangedType::ControlBackground ) + { + ImplInitSettings( false, false, true ); + Invalidate(); + } +} + +void Ruler::DataChanged( const DataChangedEvent& rDCEvt ) +{ + Window::DataChanged( rDCEvt ); + + if ( (rDCEvt.GetType() == DataChangedEventType::FONTS) || + (rDCEvt.GetType() == DataChangedEventType::DISPLAY) || + (rDCEvt.GetType() == DataChangedEventType::FONTSUBSTITUTION) || + ((rDCEvt.GetType() == DataChangedEventType::SETTINGS) && + (rDCEvt.GetFlags() & AllSettingsFlags::STYLE)) ) + { + mbFormat = true; + ImplInitSettings( true, true, true ); + Invalidate(); + } +} + +bool Ruler::StartDrag() +{ + return false; +} + +void Ruler::Drag() +{ +} + +void Ruler::EndDrag() +{ +} + +void Ruler::Click() +{ +} + +void Ruler::DoubleClick() +{ + maDoubleClickHdl.Call( this ); +} + +void Ruler::ExtraDown() +{ +} + +void Ruler::Activate() +{ + mbActive = true; + + // update positionlines - draw is delayed + mnUpdateFlags |= RULER_UPDATE_LINES; + Invalidate(InvalidateFlags::NoErase); +} + +void Ruler::Deactivate() +{ + // clear positionlines + Invalidate(InvalidateFlags::NoErase); + + mbActive = false; +} + +bool Ruler::StartDocDrag( const MouseEvent& rMEvt, RulerType eDragType ) +{ + if ( !mbDrag ) + { + Point aMousePos = rMEvt.GetPosPixel(); + sal_uInt16 nMouseClicks = rMEvt.GetClicks(); + sal_uInt16 nMouseModifier = rMEvt.GetModifier(); + RulerSelection aHitTest; + + if(eDragType != RulerType::DontKnow) + aHitTest.bExpandTest = true; + + // update ruler + if ( mbFormat ) + { + if (!IsReallyVisible()) + { + // set mpData for ImplDocHitTest() + ImplFormat(*this); + } + + Invalidate(InvalidateFlags::NoErase); + } + + if ( nMouseClicks == 1 ) + { + if ( ImplDocHitTest( aMousePos, eDragType, &aHitTest ) ) + { + PointerStyle aPtr = PointerStyle::Arrow; + + if ( aHitTest.bSize ) + { + if ( mnWinStyle & WB_HORZ ) + aPtr = PointerStyle::ESize; + else + aPtr = PointerStyle::SSize; + } + else if ( aHitTest.bSizeBar ) + { + if ( mnWinStyle & WB_HORZ ) + aPtr = PointerStyle::HSizeBar; + else + aPtr = PointerStyle::VSizeBar; + } + SetPointer( aPtr ); + return ImplStartDrag( &aHitTest, nMouseModifier ); + } + } + else if ( nMouseClicks == 2 ) + { + if ( ImplDocHitTest( aMousePos, eDragType, &aHitTest ) ) + { + mnDragPos = aHitTest.nPos; + mnDragAryPos = aHitTest.nAryPos; + } + + DoubleClick(); + + mnDragPos = 0; + mnDragAryPos = 0; + + return true; + } + } + + return false; +} + +void Ruler::CancelDrag() +{ + if ( mbDrag ) + { + ImplDrag( Point( -1, -1 ) ); + ImplEndDrag(); + } +} + +RulerType Ruler::GetType( const Point& rPos, sal_uInt16* pAryPos ) +{ + RulerSelection aHitTest; + + // update ruler + if ( IsReallyVisible() && mbFormat ) + { + Invalidate(InvalidateFlags::NoErase); + } + + (void)ImplHitTest(rPos, &aHitTest); + + // return values + if ( pAryPos ) + *pAryPos = aHitTest.nAryPos; + return aHitTest.eType; +} + +void Ruler::SetWinPos( long nNewOff, long nNewWidth ) +{ + // should widths be automatically calculated + if ( !nNewWidth ) + mbAutoWinWidth = true; + else + mbAutoWinWidth = false; + + mnWinOff = nNewOff; + mnWinWidth = nNewWidth; + ImplUpdate( true ); +} + +void Ruler::SetPagePos( long nNewOff, long nNewWidth ) +{ + // should we do anything? + if ( (mpData->nPageOff == nNewOff) && (mpData->nPageWidth == nNewWidth) ) + return; + + // should widths be automatically calculated + if ( !nNewWidth ) + mpData->bAutoPageWidth = true; + else + mpData->bAutoPageWidth = false; + + mpData->nPageOff = nNewOff; + mpData->nPageWidth = nNewWidth; + ImplUpdate( true ); +} + +void Ruler::SetBorderPos( long nOff ) +{ + if ( mnWinStyle & WB_BORDER ) + { + if ( mnBorderOff != nOff ) + { + mnBorderOff = nOff; + + if ( IsReallyVisible() && IsUpdateMode() ) + Invalidate(InvalidateFlags::NoErase); + } + } +} + +void Ruler::SetUnit( FieldUnit eNewUnit ) +{ + if ( meUnit == eNewUnit ) + return; + + meUnit = eNewUnit; + switch ( meUnit ) + { + case FieldUnit::MM: + mnUnitIndex = RULER_UNIT_MM; + break; + case FieldUnit::CM: + mnUnitIndex = RULER_UNIT_CM; + break; + case FieldUnit::M: + mnUnitIndex = RULER_UNIT_M; + break; + case FieldUnit::KM: + mnUnitIndex = RULER_UNIT_KM; + break; + case FieldUnit::INCH: + mnUnitIndex = RULER_UNIT_INCH; + break; + case FieldUnit::FOOT: + mnUnitIndex = RULER_UNIT_FOOT; + break; + case FieldUnit::MILE: + mnUnitIndex = RULER_UNIT_MILE; + break; + case FieldUnit::POINT: + mnUnitIndex = RULER_UNIT_POINT; + break; + case FieldUnit::PICA: + mnUnitIndex = RULER_UNIT_PICA; + break; + case FieldUnit::CHAR: + mnUnitIndex = RULER_UNIT_CHAR; + break; + case FieldUnit::LINE: + mnUnitIndex = RULER_UNIT_LINE; + break; + default: + SAL_WARN( "svtools.control", "Ruler::SetUnit() - Wrong Unit" ); + break; + } + + maMapMode.SetMapUnit( aImplRulerUnitTab[mnUnitIndex].eMapUnit ); + ImplUpdate(); +} + +void Ruler::SetZoom( const Fraction& rNewZoom ) +{ + DBG_ASSERT( rNewZoom.GetNumerator(), "Ruler::SetZoom() with scale 0 is not allowed" ); + + if ( maZoom != rNewZoom ) + { + maZoom = rNewZoom; + maMapMode.SetScaleX( maZoom ); + maMapMode.SetScaleY( maZoom ); + ImplUpdate(); + } +} + +void Ruler::SetExtraType( RulerExtra eNewExtraType, sal_uInt16 nStyle ) +{ + if ( mnWinStyle & WB_EXTRAFIELD ) + { + meExtraType = eNewExtraType; + mnExtraStyle = nStyle; + if (IsReallyVisible() && IsUpdateMode()) + Invalidate(); + } +} + +void Ruler::SetNullOffset( long nPos ) +{ + if ( mpData->nNullOff != nPos ) + { + mpData->nNullVirOff += nPos - mpData->nNullOff; + mpData->nNullOff = nPos; + ImplUpdate(); + } +} + +void Ruler::SetLeftFrameMargin( long nPos ) +{ + if ( mpData->nLeftFrameMargin != nPos ) + { + mpData->nLeftFrameMargin = nPos; + ImplUpdate(); + } +} + +void Ruler::SetRightFrameMargin( long nPos ) +{ + if ( mpData->nRightFrameMargin != nPos ) + { + mpData->nRightFrameMargin = nPos; + ImplUpdate(); + } +} + +void Ruler::SetMargin1( long nPos, RulerMarginStyle nMarginStyle ) +{ + if ( (mpData->nMargin1 != nPos) || (mpData->nMargin1Style != nMarginStyle) ) + { + mpData->nMargin1 = nPos; + mpData->nMargin1Style = nMarginStyle; + ImplUpdate(); + } +} + +void Ruler::SetMargin2( long nPos, RulerMarginStyle nMarginStyle ) +{ + DBG_ASSERT( (nPos >= mpData->nMargin1) || + (mpData->nMargin1Style & RulerMarginStyle::Invisible) || + (mpData->nMargin2Style & RulerMarginStyle::Invisible), + "Ruler::SetMargin2() - Margin2 < Margin1" ); + + if ( (mpData->nMargin2 != nPos) || (mpData->nMargin2Style != nMarginStyle) ) + { + mpData->nMargin2 = nPos; + mpData->nMargin2Style = nMarginStyle; + ImplUpdate(); + } +} + +void Ruler::SetLines( sal_uInt32 aLineArraySize, const RulerLine* pLineArray ) +{ + // To determine if what has changed + if ( mpData->pLines.size() == aLineArraySize ) + { + sal_uInt32 i = aLineArraySize; + vector<RulerLine>::const_iterator aItr1 = mpData->pLines.begin(); + const RulerLine* pAry2 = pLineArray; + while ( i ) + { + if ( aItr1->nPos != pAry2->nPos ) + break; + ++aItr1; + ++pAry2; + i--; + } + if ( !i ) + return; + } + + // New values and new share issue + bool bMustUpdate; + bMustUpdate = IsReallyVisible() && IsUpdateMode(); + + // Delete old lines + if ( bMustUpdate ) + Invalidate(InvalidateFlags::NoErase); + + // New data set + if ( !aLineArraySize || !pLineArray ) + { + if ( mpData->pLines.empty() ) + return; + mpData->pLines.clear(); + } + else + { + if ( mpData->pLines.size() != aLineArraySize ) + { + mpData->pLines.resize(aLineArraySize); + } + + std::copy( pLineArray, + pLineArray + aLineArraySize, + mpData->pLines.begin() ); + + if ( bMustUpdate ) + Invalidate(InvalidateFlags::NoErase); + } +} + +void Ruler::SetBorders( sal_uInt32 aBorderArraySize, const RulerBorder* pBorderArray ) +{ + if ( !aBorderArraySize || !pBorderArray ) + { + if ( mpData->pBorders.empty() ) + return; + mpData->pBorders.clear(); + } + else + { + if ( mpData->pBorders.size() != aBorderArraySize ) + { + mpData->pBorders.resize(aBorderArraySize); + } + else + { + sal_uInt32 i = aBorderArraySize; + const RulerBorder* pAry1 = mpData->pBorders.data(); + const RulerBorder* pAry2 = pBorderArray; + while ( i ) + { + if ( (pAry1->nPos != pAry2->nPos) || + (pAry1->nWidth != pAry2->nWidth) || + (pAry1->nStyle != pAry2->nStyle) ) + break; + pAry1++; + pAry2++; + i--; + } + if ( !i ) + return; + } + std::copy( pBorderArray, + pBorderArray + aBorderArraySize, + mpData->pBorders.begin() ); + } + + ImplUpdate(); +} + +void Ruler::SetIndents( sal_uInt32 aIndentArraySize, const RulerIndent* pIndentArray ) +{ + + if ( !aIndentArraySize || !pIndentArray ) + { + if ( mpData->pIndents.empty() ) + return; + mpData->pIndents.clear(); + } + else + { + if ( mpData->pIndents.size() != aIndentArraySize ) + { + mpData->pIndents.resize(aIndentArraySize); + } + else + { + sal_uInt32 i = aIndentArraySize; + const RulerIndent* pAry1 = mpData->pIndents.data(); + const RulerIndent* pAry2 = pIndentArray; + while ( i ) + { + if ( (pAry1->nPos != pAry2->nPos) || + (pAry1->nStyle != pAry2->nStyle) ) + break; + pAry1++; + pAry2++; + i--; + } + if ( !i ) + return; + } + + std::copy( pIndentArray, + pIndentArray + aIndentArraySize, + mpData->pIndents.begin() ); + } + + ImplUpdate(); +} + +void Ruler::SetTabs( sal_uInt32 aTabArraySize, const RulerTab* pTabArray ) +{ + if ( aTabArraySize == 0 || pTabArray == nullptr ) + { + if ( mpData->pTabs.empty() ) + return; + mpData->pTabs.clear(); + } + else + { + if ( mpData->pTabs.size() != aTabArraySize ) + { + mpData->pTabs.resize(aTabArraySize); + } + else + { + sal_uInt32 i = aTabArraySize; + vector<RulerTab>::iterator aTabIterator = mpData->pTabs.begin(); + const RulerTab* pInputArray = pTabArray; + while ( i ) + { + RulerTab& aCurrent = *aTabIterator; + if ( aCurrent.nPos != pInputArray->nPos || + aCurrent.nStyle != pInputArray->nStyle ) + { + break; + } + ++aTabIterator; + pInputArray++; + i--; + } + if ( !i ) + return; + } + std::copy(pTabArray, pTabArray + aTabArraySize, mpData->pTabs.begin()); + } + + ImplUpdate(); +} + +const std::vector<RulerTab>& Ruler::GetTabs() const +{ + return mpData->pTabs; +} + +void Ruler::SetStyle( WinBits nStyle ) +{ + if ( mnWinStyle != nStyle ) + { + mnWinStyle = nStyle; + ImplInitExtraField( true ); + } +} + +void Ruler::DrawTab(vcl::RenderContext& rRenderContext, const Color &rFillColor, const Point& rPos, sal_uInt16 nStyle) +{ + Point aPos(rPos); + sal_uInt16 nTabStyle = nStyle & (RULER_TAB_STYLE | RULER_TAB_RTL); + + rRenderContext.Push(PushFlags::LINECOLOR | PushFlags::FILLCOLOR); + rRenderContext.SetLineColor(); + rRenderContext.SetFillColor(rFillColor); + ImplCenterTabPos(aPos, nTabStyle); + ImplDrawRulerTab(rRenderContext, aPos, nTabStyle, nStyle); + rRenderContext.Pop(); +} + +void Ruler::SetTextRTL(bool bRTL) +{ + if(mpData->bTextRTL != bRTL) + { + mpData->bTextRTL = bRTL; + if ( IsReallyVisible() && IsUpdateMode() ) + ImplInitExtraField( true ); + } + +} + +long Ruler::GetPageOffset() const +{ + return mpData->nPageOff; +} + +long Ruler::GetNullOffset() const +{ + return mpData->nNullOff; +} + +long Ruler::GetMargin1() const +{ + return mpData->nMargin1; +} + +long Ruler::GetMargin2() const +{ + return mpData->nMargin2; +} + + +bool Ruler::GetTextRTL() const +{ + return mpData->bTextRTL; +} + +const RulerUnitData& Ruler::GetCurrentRulerUnit() const +{ + return aImplRulerUnitTab[mnUnitIndex]; +} + +void Ruler::DrawTicks() +{ + mbFormat = true; + Invalidate(InvalidateFlags::NoErase); +} + +uno::Reference< XAccessible > Ruler::CreateAccessible() +{ + vcl::Window* pParent = GetAccessibleParentWindow(); + OSL_ENSURE( pParent, "-SvxRuler::CreateAccessible(): No Parent!" ); + uno::Reference< XAccessible > xAccParent = pParent->GetAccessible(); + if( xAccParent.is() ) + { + // MT: Fixed compiler issue because the address from a temporary object was used. + // BUT: Should it really be a Pointer, instead of const&??? + OUString aStr; + if ( mnWinStyle & WB_HORZ ) + { + aStr = SvtResId(STR_SVT_ACC_RULER_HORZ_NAME); + } + else + { + aStr = SvtResId(STR_SVT_ACC_RULER_VERT_NAME); + } + mxAccContext = new SvtRulerAccessible( xAccParent, *this, aStr ); + SetAccessible(mxAccContext.get()); + return mxAccContext.get(); + } + else + return uno::Reference< XAccessible >(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/control/scriptedtext.cxx b/svtools/source/control/scriptedtext.cxx new file mode 100644 index 000000000..4c7155dea --- /dev/null +++ b/svtools/source/control/scriptedtext.cxx @@ -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 . + */ + +#include <svtools/scriptedtext.hxx> +#include <vector> +#include <rtl/ustring.hxx> +#include <vcl/outdev.hxx> +#include <vcl/font.hxx> +#include <tools/debug.hxx> +#include <tools/gen.hxx> +#include <com/sun/star/i18n/ScriptType.hpp> +#include <com/sun/star/i18n/XBreakIterator.hpp> + + +using namespace ::std; +using namespace ::com::sun::star; + + +class SvtScriptedTextHelper_Impl +{ +private: + OutputDevice& mrOutDevice; /// The output device for drawing the text. + vcl::Font maLatinFont; /// The font for latin text portions. + vcl::Font maAsianFont; /// The font for asian text portions. + vcl::Font maCmplxFont; /// The font for complex text portions. + vcl::Font maDefltFont; /// The default font of the output device. + OUString maText; /// The text. + + vector< sal_Int32 > maPosVec; /// The start position of each text portion. + vector< sal_Int16 > maScriptVec; /// The script type of each text portion. + vector< sal_Int32 > maWidthVec; /// The output width of each text portion. + Size maTextSize; /// The size the text will take in the current output device. + + /** Gets the font of the given script type. */ + const vcl::Font& GetFont( sal_uInt16 _nScript ) const; + /** Sets a font on the output device depending on the script type. */ + void SetOutDevFont( sal_uInt16 _nScript ) + { mrOutDevice.SetFont( GetFont( _nScript ) ); } + /** Fills maPosVec with positions of all changes of script type. + This method expects correctly initialized maPosVec and maScriptVec. */ + void CalculateSizes(); + /** Fills maPosVec with positions of all changes of script type and + maScriptVec with the script type of each portion. */ + void CalculateBreaks( + const uno::Reference< i18n::XBreakIterator >& _xBreakIter ); + +public: + /** This constructor sets an output device and fonts for all script types. */ + explicit SvtScriptedTextHelper_Impl( + OutputDevice& _rOutDevice ); + + /** Sets new fonts and recalculates the text width. */ + void SetFonts( vcl::Font const * _pLatinFont, vcl::Font const * _pAsianFont, vcl::Font const * _pCmplxFont ); + /** Sets a new text and calculates all script breaks and the text width. */ + void SetText( + const OUString& _rText, + const uno::Reference< i18n::XBreakIterator >& _xBreakIter ); + + /** Returns a size struct containing the width and height of the text in the current output device. */ + const Size& GetTextSize() const { return maTextSize;} + + /** Draws the text in the current output device. */ + void DrawText( const Point& _rPos ); +}; + + +SvtScriptedTextHelper_Impl::SvtScriptedTextHelper_Impl( + OutputDevice& _rOutDevice ) : + mrOutDevice( _rOutDevice ), + maLatinFont( _rOutDevice.GetFont() ), + maAsianFont( _rOutDevice.GetFont() ), + maCmplxFont( _rOutDevice.GetFont() ), + maDefltFont( _rOutDevice.GetFont() ) +{ +} + +const vcl::Font& SvtScriptedTextHelper_Impl::GetFont( sal_uInt16 _nScript ) const +{ + switch( _nScript ) + { + case i18n::ScriptType::LATIN: return maLatinFont; + case i18n::ScriptType::ASIAN: return maAsianFont; + case i18n::ScriptType::COMPLEX: return maCmplxFont; + } + return maDefltFont; +} + +void SvtScriptedTextHelper_Impl::CalculateSizes() +{ + maTextSize.setWidth(0); + maTextSize.setHeight(0); + mrOutDevice.Push(PushFlags::FONT | PushFlags::TEXTCOLOR); + + // calculate text portion widths and total width + maWidthVec.clear(); + if( !maPosVec.empty() ) + { + DBG_ASSERT( maPosVec.size() - 1 == maScriptVec.size(), + "SvtScriptedTextHelper_Impl::CalculateWidth - invalid vectors" ); + + sal_Int32 nThisPos = maPosVec[ 0 ]; + sal_Int32 nNextPos; + sal_Int32 nPosVecSize = maPosVec.size(); + sal_Int32 nPosVecIndex = 1; + + sal_Int16 nScript; + sal_Int32 nScriptVecIndex = 0; + + sal_Int32 nCurrWidth; + + while( nPosVecIndex < nPosVecSize ) + { + nNextPos = maPosVec[ nPosVecIndex++ ]; + nScript = maScriptVec[ nScriptVecIndex++ ]; + + SetOutDevFont( nScript ); + nCurrWidth = mrOutDevice.GetTextWidth( maText, nThisPos, nNextPos - nThisPos ); + maWidthVec.push_back( nCurrWidth ); + maTextSize.AdjustWidth(nCurrWidth ); + nThisPos = nNextPos; + } + } + + // calculate maximum font height + SetOutDevFont( i18n::ScriptType::LATIN ); + maTextSize.setHeight( std::max( maTextSize.Height(), mrOutDevice.GetTextHeight() ) ); + SetOutDevFont( i18n::ScriptType::ASIAN ); + maTextSize.setHeight( std::max( maTextSize.Height(), mrOutDevice.GetTextHeight() ) ); + SetOutDevFont( i18n::ScriptType::COMPLEX ); + maTextSize.setHeight( std::max( maTextSize.Height(), mrOutDevice.GetTextHeight() ) ); + + mrOutDevice.Pop(); +} + +void SvtScriptedTextHelper_Impl::CalculateBreaks( const uno::Reference< i18n::XBreakIterator >& _xBreakIter ) +{ + maPosVec.clear(); + maScriptVec.clear(); + + DBG_ASSERT( _xBreakIter.is(), "SvtScriptedTextHelper_Impl::CalculateBreaks - no break iterator" ); + + sal_Int32 nLen = maText.getLength(); + if( nLen ) + { + if( _xBreakIter.is() ) + { + sal_Int32 nThisPos = 0; // first position of this portion + sal_Int32 nNextPos = 0; // first position of next portion + sal_Int16 nPortScript; // script type of this portion + do + { + nPortScript = _xBreakIter->getScriptType( maText, nThisPos ); + nNextPos = _xBreakIter->endOfScript( maText, nThisPos, nPortScript ); + + switch( nPortScript ) + { + case i18n::ScriptType::LATIN: + case i18n::ScriptType::ASIAN: + case i18n::ScriptType::COMPLEX: + maPosVec.push_back( nThisPos ); + maScriptVec.push_back( nPortScript ); + break; + default: + { +/* *** handling of weak characters *** +- first portion is weak: Use OutputDevice::HasGlyphs() to find the correct font +- weak portion follows another portion: Script type of preceding portion is used */ + if( maPosVec.empty() ) + { + sal_Int32 nCharIx = 0; + sal_Int32 nNextCharIx = 0; + sal_Int16 nScript; + do + { + nScript = i18n::ScriptType::LATIN; + while( (nScript != i18n::ScriptType::WEAK) && (nCharIx == nNextCharIx) ) + { + nNextCharIx = mrOutDevice.HasGlyphs( GetFont( nScript ), maText, nCharIx, nNextPos - nCharIx ); + if( nCharIx == nNextCharIx ) + ++nScript; + } + if( nNextCharIx == nCharIx ) + ++nNextCharIx; + + maPosVec.push_back( nCharIx ); + maScriptVec.push_back( nScript ); + nCharIx = nNextCharIx; + } + while( nCharIx < nNextPos && nCharIx != -1 ); + } + // nothing to do for following portions + } + } + nThisPos = nNextPos; + } + while( (0 <= nThisPos) && (nThisPos < nLen) ); + } + else // no break iterator: whole text LATIN + { + maPosVec.push_back( 0 ); + maScriptVec.push_back( i18n::ScriptType::LATIN ); + } + + // push end position of last portion + if( !maPosVec.empty() ) + maPosVec.push_back( nLen ); + } + CalculateSizes(); +} + +void SvtScriptedTextHelper_Impl::SetFonts( vcl::Font const * _pLatinFont, vcl::Font const * _pAsianFont, vcl::Font const * _pCmplxFont ) +{ + maLatinFont = _pLatinFont ? *_pLatinFont : maDefltFont; + maAsianFont = _pAsianFont ? *_pAsianFont : maDefltFont; + maCmplxFont = _pCmplxFont ? *_pCmplxFont : maDefltFont; + CalculateSizes(); +} + +void SvtScriptedTextHelper_Impl::SetText( const OUString& _rText, const uno::Reference< i18n::XBreakIterator >& _xBreakIter ) +{ + maText = _rText; + CalculateBreaks( _xBreakIter ); +} + + +void SvtScriptedTextHelper_Impl::DrawText( const Point& _rPos ) +{ + if( maText.isEmpty() || maPosVec.empty() ) + return; + + DBG_ASSERT( maPosVec.size() - 1 == maScriptVec.size(), "SvtScriptedTextHelper_Impl::DrawText - invalid vectors" ); + DBG_ASSERT( maScriptVec.size() == maWidthVec.size(), "SvtScriptedTextHelper_Impl::DrawText - invalid vectors" ); + + mrOutDevice.Push(PushFlags::FONT | PushFlags::TEXTCOLOR); + + Point aCurrPos( _rPos ); + sal_Int32 nThisPos = maPosVec[ 0 ]; + sal_Int32 nNextPos; + sal_Int32 nPosVecSize = maPosVec.size(); + sal_Int32 nPosVecIndex = 1; + + sal_Int16 nScript; + sal_Int32 nVecIndex = 0; + + while( nPosVecIndex < nPosVecSize ) + { + nNextPos = maPosVec[ nPosVecIndex++ ]; + nScript = maScriptVec[ nVecIndex ]; + + SetOutDevFont( nScript ); + mrOutDevice.DrawText( aCurrPos, maText, nThisPos, nNextPos - nThisPos ); + aCurrPos.AdjustX(maWidthVec[ nVecIndex++ ] ); + aCurrPos.AdjustX(mrOutDevice.GetTextHeight() / 5 ); // add 20% of font height as portion spacing + nThisPos = nNextPos; + } + + mrOutDevice.Pop(); +} + + +SvtScriptedTextHelper::SvtScriptedTextHelper( OutputDevice& _rOutDevice ) : + mpImpl( new SvtScriptedTextHelper_Impl( _rOutDevice ) ) +{ +} + +SvtScriptedTextHelper::SvtScriptedTextHelper( const SvtScriptedTextHelper& _rCopy ) : + mpImpl( new SvtScriptedTextHelper_Impl( *_rCopy.mpImpl ) ) +{ +} + +SvtScriptedTextHelper::~SvtScriptedTextHelper() +{ +} + +void SvtScriptedTextHelper::SetFonts( vcl::Font const * _pLatinFont, vcl::Font const * _pAsianFont, vcl::Font const * _pCmplxFont ) +{ + mpImpl->SetFonts( _pLatinFont, _pAsianFont, _pCmplxFont ); +} + +void SvtScriptedTextHelper::SetDefaultFont() +{ + mpImpl->SetFonts( nullptr, nullptr, nullptr ); +} + +void SvtScriptedTextHelper::SetText( const OUString& _rText, const uno::Reference< i18n::XBreakIterator >& _xBreakIter ) +{ + mpImpl->SetText( _rText, _xBreakIter ); +} + +const Size& SvtScriptedTextHelper::GetTextSize() const +{ + return mpImpl->GetTextSize(); +} + +void SvtScriptedTextHelper::DrawText( const Point& _rPos ) +{ + mpImpl->DrawText( _rPos ); +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/control/scrwin.cxx b/svtools/source/control/scrwin.cxx new file mode 100644 index 000000000..b56fe3db8 --- /dev/null +++ b/svtools/source/control/scrwin.cxx @@ -0,0 +1,345 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <svtools/scrwin.hxx> +#include <vcl/commandevent.hxx> +#include <vcl/event.hxx> +#include <vcl/settings.hxx> +#include <vcl/scrbar.hxx> + +ScrollableWindow::ScrollableWindow( vcl::Window* pParent ) : + Window( pParent, WB_CLIPCHILDREN ), + aVScroll( VclPtr<ScrollBar>::Create(this, WinBits(WB_VSCROLL | WB_DRAG)) ), + aHScroll( VclPtr<ScrollBar>::Create(this, WinBits(WB_HSCROLL | WB_DRAG)) ), + aCornerWin( VclPtr<ScrollBarBox>::Create(this) ) +{ + bScrolling = false; + + // set the handlers for the scrollbars + aVScroll->SetScrollHdl( LINK(this, ScrollableWindow, ScrollHdl) ); + aHScroll->SetScrollHdl( LINK(this, ScrollableWindow, ScrollHdl) ); + aVScroll->SetEndScrollHdl( LINK(this, ScrollableWindow, EndScrollHdl) ); + aHScroll->SetEndScrollHdl( LINK(this, ScrollableWindow, EndScrollHdl) ); + + nColumnPixW = nLinePixH = GetSettings().GetStyleSettings().GetScrollBarSize(); +} + + +ScrollableWindow::~ScrollableWindow() +{ + disposeOnce(); +} + +void ScrollableWindow::dispose() +{ + aVScroll.disposeAndClear(); + aHScroll.disposeAndClear(); + aCornerWin.disposeAndClear(); + Window::dispose(); +} + + +void ScrollableWindow::Command( const CommandEvent& rCEvt ) +{ + if ( (rCEvt.GetCommand() == CommandEventId::Wheel) || + (rCEvt.GetCommand() == CommandEventId::StartAutoScroll) || + (rCEvt.GetCommand() == CommandEventId::AutoScroll) ) + { + ScrollBar* pHScrBar; + ScrollBar* pVScrBar; + if ( aHScroll->IsVisible() ) + pHScrBar = aHScroll.get(); + else + pHScrBar = nullptr; + if ( aVScroll->IsVisible() ) + pVScrBar = aVScroll.get(); + else + pVScrBar = nullptr; + if ( HandleScrollCommand( rCEvt, pHScrBar, pVScrBar ) ) + return; + } + + Window::Command( rCEvt ); +} + + +void ScrollableWindow::DataChanged( const DataChangedEvent& rDCEvt ) +{ + if ( (rDCEvt.GetType() == DataChangedEventType::SETTINGS) && + (rDCEvt.GetFlags() & AllSettingsFlags::STYLE) ) + { + Resize(); + Invalidate(); + } + + Window::DataChanged( rDCEvt ); +} + + +Size ScrollableWindow::GetOutputSizePixel() const +{ + Size aSz( Window::GetOutputSizePixel() ); + + long nTmp = GetSettings().GetStyleSettings().GetScrollBarSize(); + if ( aHScroll->IsVisible() ) + aSz.AdjustHeight( -nTmp ); + if ( aVScroll->IsVisible() ) + aSz.AdjustWidth( -nTmp ); + return aSz; +} + + +IMPL_LINK( ScrollableWindow, EndScrollHdl, ScrollBar *, /*pScroll*/, void ) +{ + // notify the end of scrolling + bScrolling = false; +} + + +IMPL_LINK( ScrollableWindow, ScrollHdl, ScrollBar *, pScroll, void ) +{ + // notify the start of scrolling, if not already scrolling + if ( !bScrolling ) + bScrolling = true; + + // get the delta in logic coordinates + Size aDelta( PixelToLogic( + Size( aHScroll->GetDelta(), aVScroll->GetDelta() ) ) ); + if ( pScroll == aHScroll.get() ) + Scroll( aDelta.Width(), 0 ); + else + Scroll( 0, aDelta.Height() ); +} + + +void ScrollableWindow::Resize() +{ + // get the new output-size in pixel + Size aOutPixSz = Window::GetOutputSizePixel(); + + // determine the size of the output-area and if we need scrollbars + const long nScrSize = GetSettings().GetStyleSettings().GetScrollBarSize(); + bool bVVisible = false; // by default no vertical-ScrollBar + bool bHVisible = false; // by default no horizontal-ScrollBar + bool bChanged; // determines if a visiblility was changed + do + { + bChanged = false; + + // does we need a vertical ScrollBar + if ( aOutPixSz.Width() < aTotPixSz.Width() && !bHVisible ) + { + bHVisible = true; + aOutPixSz.AdjustHeight( -nScrSize ); + bChanged = true; + } + + // does we need a horizontal ScrollBar + if ( aOutPixSz.Height() < aTotPixSz.Height() && !bVVisible ) + { + bVVisible = true; + aOutPixSz.AdjustWidth( -nScrSize ); + bChanged = true; + } + + } + while ( bChanged ); // until no visibility has changed + + // store the old offset and map-mode + MapMode aMap( GetMapMode() ); + Point aOldPixOffset( aPixOffset ); + + // justify (right/bottom borders should never exceed the virtual window) + Size aPixDelta; + if ( aPixOffset.X() < 0 && + aPixOffset.X() + aTotPixSz.Width() < aOutPixSz.Width() ) + aPixDelta.setWidth( + aOutPixSz.Width() - ( aPixOffset.X() + aTotPixSz.Width() ) ); + if ( aPixOffset.Y() < 0 && + aPixOffset.Y() + aTotPixSz.Height() < aOutPixSz.Height() ) + aPixDelta.setHeight( + aOutPixSz.Height() - ( aPixOffset.Y() + aTotPixSz.Height() ) ); + if ( aPixDelta.Width() || aPixDelta.Height() ) + { + aPixOffset.AdjustX(aPixDelta.Width() ); + aPixOffset.AdjustY(aPixDelta.Height() ); + } + + // for axis without scrollbar restore the origin + if ( !bVVisible || !bHVisible ) + { + aPixOffset = Point( + bHVisible + ? aPixOffset.X() + : (aOutPixSz.Width()-aTotPixSz.Width()) / 2, + bVVisible + ? aPixOffset.Y() + : (aOutPixSz.Height()-aTotPixSz.Height()) / 2 ); + } + if ( bHVisible && !aHScroll->IsVisible() ) + aPixOffset.setX( 0 ); + if ( bVVisible && !aVScroll->IsVisible() ) + aPixOffset.setY( 0 ); + + // select the shifted map-mode + if ( aPixOffset != aOldPixOffset ) + { + Window::SetMapMode( MapMode( MapUnit::MapPixel ) ); + Window::Scroll( + aPixOffset.X() - aOldPixOffset.X(), + aPixOffset.Y() - aOldPixOffset.Y() ); + SetMapMode( aMap ); + } + + // show or hide scrollbars + aVScroll->Show( bVVisible ); + aHScroll->Show( bHVisible ); + + // disable painting in the corner between the scrollbars + if ( bVVisible && bHVisible ) + { + aCornerWin->SetPosSizePixel(Point(aOutPixSz.Width(), aOutPixSz.Height()), + Size(nScrSize, nScrSize) ); + aCornerWin->Show(); + } + else + aCornerWin->Hide(); + + // resize scrollbars and set their ranges + if ( bHVisible ) + { + aHScroll->SetPosSizePixel( + Point( 0, aOutPixSz.Height() ), + Size( aOutPixSz.Width(), nScrSize ) ); + aHScroll->SetRange( Range( 0, aTotPixSz.Width() ) ); + aHScroll->SetPageSize( aOutPixSz.Width() ); + aHScroll->SetVisibleSize( aOutPixSz.Width() ); + aHScroll->SetLineSize( nColumnPixW ); + aHScroll->SetThumbPos( -aPixOffset.X() ); + } + if ( bVVisible ) + { + aVScroll->SetPosSizePixel( + Point( aOutPixSz.Width(), 0 ), + Size( nScrSize,aOutPixSz.Height() ) ); + aVScroll->SetRange( Range( 0, aTotPixSz.Height() ) ); + aVScroll->SetPageSize( aOutPixSz.Height() ); + aVScroll->SetVisibleSize( aOutPixSz.Height() ); + aVScroll->SetLineSize( nLinePixH ); + aVScroll->SetThumbPos( -aPixOffset.Y() ); + } +} + + +void ScrollableWindow::SetMapMode( const MapMode& rNewMapMode ) +{ + MapMode aMap( rNewMapMode ); + aMap.SetOrigin( aMap.GetOrigin() + PixelToLogic( aPixOffset, aMap ) ); + Window::SetMapMode( aMap ); +} + + +MapMode ScrollableWindow::GetMapMode() const +{ + MapMode aMap( Window::GetMapMode() ); + aMap.SetOrigin( aMap.GetOrigin() - PixelToLogic( aPixOffset ) ); + return aMap; +} + + +void ScrollableWindow::SetTotalSize( const Size& rNewSize ) +{ + aTotPixSz = LogicToPixel( rNewSize ); + ScrollableWindow::Resize(); +} + + +void ScrollableWindow::Scroll( long nDeltaX, long nDeltaY, ScrollFlags ) +{ + // get the delta in pixel + Size aDeltaPix( LogicToPixel( Size(nDeltaX, nDeltaY) ) ); + Size aOutPixSz( GetOutputSizePixel() ); + MapMode aMap( GetMapMode() ); + Point aNewPixOffset( aPixOffset ); + + // scrolling horizontally? + if ( nDeltaX != 0 ) + { + aNewPixOffset.AdjustX( -(aDeltaPix.Width()) ); + if ( ( aOutPixSz.Width() - aNewPixOffset.X() ) > aTotPixSz.Width() ) + aNewPixOffset.setX( - ( aTotPixSz.Width() - aOutPixSz.Width() ) ); + else if ( aNewPixOffset.X() > 0 ) + aNewPixOffset.setX( 0 ); + } + + // scrolling vertically? + if ( nDeltaY != 0 ) + { + aNewPixOffset.AdjustY( -(aDeltaPix.Height()) ); + if ( ( aOutPixSz.Height() - aNewPixOffset.Y() ) > aTotPixSz.Height() ) + aNewPixOffset.setY( - ( aTotPixSz.Height() - aOutPixSz.Height() ) ); + else if ( aNewPixOffset.Y() > 0 ) + aNewPixOffset.setY( 0 ); + } + + // recompute the logical scroll units + aDeltaPix.setWidth( aPixOffset.X() - aNewPixOffset.X() ); + aDeltaPix.setHeight( aPixOffset.Y() - aNewPixOffset.Y() ); + Size aDelta( PixelToLogic(aDeltaPix) ); + nDeltaX = aDelta.Width(); + nDeltaY = aDelta.Height(); + aPixOffset = aNewPixOffset; + + // scrolling? + if ( nDeltaX != 0 || nDeltaY != 0 ) + { + PaintImmediately(); + + // does the new area overlap the old one? + if ( std::abs( static_cast<int>(aDeltaPix.Height()) ) < aOutPixSz.Height() || + std::abs( static_cast<int>(aDeltaPix.Width()) ) < aOutPixSz.Width() ) + { + // scroll the overlapping area + SetMapMode( aMap ); + + // never scroll the scrollbars itself! + Window::Scroll(-nDeltaX, -nDeltaY, + PixelToLogic( tools::Rectangle( Point(0, 0), aOutPixSz ) ) ); + } + else + { + // repaint all + SetMapMode( aMap ); + Invalidate(); + } + + PaintImmediately(); + } + + if ( !bScrolling ) + { + if ( nDeltaX ) + aHScroll->SetThumbPos( -aPixOffset.X() ); + if ( nDeltaY ) + aVScroll->SetThumbPos( -aPixOffset.Y() ); + } +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/control/tabbar.cxx b/svtools/source/control/tabbar.cxx new file mode 100644 index 000000000..6670f1182 --- /dev/null +++ b/svtools/source/control/tabbar.cxx @@ -0,0 +1,2525 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <svtools/tabbar.hxx> +#include <tools/time.hxx> +#include <tools/poly.hxx> +#include <vcl/svapp.hxx> +#include <vcl/help.hxx> +#include <vcl/decoview.hxx> +#include <vcl/button.hxx> +#include <vcl/edit.hxx> +#include <vcl/event.hxx> +#include <vcl/settings.hxx> +#include <vcl/commandevent.hxx> +#include <vcl/svtaccessiblefactory.hxx> +#include <vcl/accessiblefactory.hxx> +#include <vcl/ptrstyle.hxx> +#include <svtools/svtresid.hxx> +#include <svtools/strings.hrc> +#include <limits> +#include <memory> +#include <utility> +#include <vector> +#include <vcl/idle.hxx> +#include <bitmaps.hlst> + +namespace +{ + +constexpr sal_uInt16 TABBAR_DRAG_SCROLLOFF = 5; +constexpr sal_uInt16 TABBAR_MINSIZE = 5; + +constexpr sal_uInt16 ADDNEWPAGE_AREAWIDTH = 10; +constexpr sal_uInt16 BUTTON_MARGIN = 6; + +class TabDrawer +{ +private: + vcl::RenderContext& mrRenderContext; + const StyleSettings& mrStyleSettings; + + tools::Rectangle maRect; + tools::Rectangle maLineRect; + + Color maSelectedColor; + Color maCustomColor; + +public: + bool mbSelected:1; + bool mbCustomColored:1; + bool mbEnabled:1; + bool mbProtect:1; + + explicit TabDrawer(vcl::RenderContext& rRenderContext) + : mrRenderContext(rRenderContext) + , mrStyleSettings(rRenderContext.GetSettings().GetStyleSettings()) + , mbSelected(false) + , mbCustomColored(false) + , mbEnabled(false) + , mbProtect(false) + { + + } + + void drawOuterFrame() + { + // set correct FillInBrush depending on status + if (mbSelected) + { + // Currently selected Tab + mrRenderContext.SetFillColor(maSelectedColor); + mrRenderContext.SetLineColor(maSelectedColor); + mrRenderContext.DrawRect(maRect); + mrRenderContext.SetLineColor(mrStyleSettings.GetDarkShadowColor()); + } + else if (mbCustomColored) + { + mrRenderContext.SetFillColor(maCustomColor); + mrRenderContext.SetLineColor(maCustomColor); + mrRenderContext.DrawRect(maRect); + mrRenderContext.SetLineColor(mrStyleSettings.GetDarkShadowColor()); + } + } + + void drawText(const OUString& aText) + { + tools::Rectangle aRect = maRect; + long nTextWidth = mrRenderContext.GetTextWidth(aText); + long nTextHeight = mrRenderContext.GetTextHeight(); + Point aPos = aRect.TopLeft(); + aPos.AdjustX((aRect.getWidth() - nTextWidth) / 2 ); + aPos.AdjustY((aRect.getHeight() - nTextHeight) / 2 ); + + if (mbEnabled) + mrRenderContext.DrawText(aPos, aText); + else + mrRenderContext.DrawCtrlText(aPos, aText, 0, aText.getLength(), (DrawTextFlags::Disable | DrawTextFlags::Mnemonic)); + } + + void drawOverTopBorder() + { + Point aTopLeft = maRect.TopLeft() + Point(1, 0); + Point aTopRight = maRect.TopRight() + Point(-1, 0); + + tools::Rectangle aDelRect(aTopLeft, aTopRight); + mrRenderContext.DrawRect(aDelRect); + } + + void drawColorLine() + { + if (mbCustomColored && mbSelected) + { + mrRenderContext.SetFillColor(maCustomColor); + mrRenderContext.SetLineColor(maCustomColor); + mrRenderContext.DrawRect(maLineRect); + } + else if (mbSelected) + { + mrRenderContext.SetFillColor(mrStyleSettings.GetDarkShadowColor()); + mrRenderContext.SetLineColor(mrStyleSettings.GetDarkShadowColor()); + mrRenderContext.DrawRect(maLineRect); + } + } + + void drawTab() + { + drawOuterFrame(); + drawColorLine(); + if (mbProtect) + { + BitmapEx aBitmap(BMP_TAB_LOCK); + Point aPosition = maRect.TopLeft(); + aPosition.AdjustX(2); + aPosition.AdjustY((maRect.getHeight() - aBitmap.GetSizePixel().Height()) / 2); + mrRenderContext.DrawBitmapEx(aPosition, aBitmap); + } + } + + void setRect(const tools::Rectangle& rRect) + { + maLineRect = tools::Rectangle(rRect.BottomLeft(), rRect.BottomRight()); + maLineRect.AdjustTop(-2); + maRect = rRect; + } + + void setSelected(bool bSelected) + { + mbSelected = bSelected; + } + + void setCustomColored(bool bCustomColored) + { + mbCustomColored = bCustomColored; + } + + void setEnabled(bool bEnabled) + { + mbEnabled = bEnabled; + } + + void setSelectedFillColor(const Color& rColor) + { + maSelectedColor = rColor; + } + + void setCustomColor(const Color& rColor) + { + maCustomColor = rColor; + } +}; + +} // anonymous namespace + +struct ImplTabBarItem +{ + sal_uInt16 mnId; + TabBarPageBits mnBits; + OUString maText; + OUString maHelpText; + OUString maAuxiliaryText; // used in LayerTabBar for real layer name + tools::Rectangle maRect; + long mnWidth; + OString maHelpId; + bool mbShort : 1; + bool mbSelect : 1; + bool mbProtect : 1; + Color maTabBgColor; + Color maTabTextColor; + + ImplTabBarItem(sal_uInt16 nItemId, const OUString& rText, TabBarPageBits nPageBits) + : mnId(nItemId) + , mnBits(nPageBits) + , maText(rText) + , mnWidth(0) + , mbShort(false) + , mbSelect(false) + , mbProtect(false) + , maTabBgColor(COL_AUTO) + , maTabTextColor(COL_AUTO) + { + } + + bool IsDefaultTabBgColor() const + { + return maTabBgColor == COL_AUTO; + } + + bool IsSelected(ImplTabBarItem const * pCurItem) const + { + return mbSelect || (pCurItem == this); + } + + OUString const & GetRenderText() const + { + return maText; + } +}; + +class ImplTabButton : public PushButton +{ + bool mbModKey : 1; + +public: + ImplTabButton(TabBar* pParent, WinBits nWinStyle = 0) + : PushButton(pParent, nWinStyle | WB_FLATBUTTON | WB_RECTSTYLE | WB_SMALLSTYLE | WB_NOLIGHTBORDER | WB_NOPOINTERFOCUS) + , mbModKey(false) + {} + + TabBar* GetParent() const + { + return static_cast<TabBar*>(Window::GetParent()); + } + + bool isModKeyPressed() const + { + return mbModKey; + } + + virtual bool PreNotify(NotifyEvent& rNotifyEvent) override; + virtual void MouseButtonDown(const MouseEvent& rMouseEvent) override; + virtual void MouseButtonUp(const MouseEvent& rMouseEvent) override; + virtual void Command(const CommandEvent& rCommandEvent) override; +}; + +void ImplTabButton::MouseButtonDown(const MouseEvent& rMouseEvent) +{ + mbModKey = rMouseEvent.IsMod1(); + PushButton::MouseButtonDown(rMouseEvent); +} + +void ImplTabButton::MouseButtonUp(const MouseEvent& rMouseEvent) +{ + mbModKey = false; + PushButton::MouseButtonUp(rMouseEvent); +} + +void ImplTabButton::Command(const CommandEvent& rCommandEvent) +{ + if (rCommandEvent.GetCommand() == CommandEventId::ContextMenu) + { + TabBar* pParent = GetParent(); + pParent->maScrollAreaContextHdl.Call(rCommandEvent); + } + PushButton::Command(rCommandEvent); +} + +bool ImplTabButton::PreNotify(NotifyEvent& rNotifyEvent) +{ + if (rNotifyEvent.GetType() == MouseNotifyEvent::MOUSEBUTTONDOWN) + { + if (GetParent()->IsInEditMode()) + { + GetParent()->EndEditMode(); + return true; + } + } + + return PushButton::PreNotify(rNotifyEvent); +} + +class ImplTabSizer : public vcl::Window +{ +public: + ImplTabSizer( TabBar* pParent, WinBits nWinStyle ); + + TabBar* GetParent() const { return static_cast<TabBar*>(Window::GetParent()); } + +private: + void ImplTrack( const Point& rScreenPos ); + + virtual void MouseButtonDown( const MouseEvent& rMEvt ) override; + virtual void Tracking( const TrackingEvent& rTEvt ) override; + virtual void Paint( vcl::RenderContext& /*rRenderContext*/, const tools::Rectangle& rRect ) override; + + Point maStartPos; + long mnStartWidth; +}; + +ImplTabSizer::ImplTabSizer( TabBar* pParent, WinBits nWinStyle ) + : Window( pParent, nWinStyle & WB_3DLOOK ) + , mnStartWidth(0) +{ + SetPointer(PointerStyle::HSizeBar); + SetSizePixel(Size(7 * GetDPIScaleFactor(), 0)); +} + +void ImplTabSizer::ImplTrack( const Point& rScreenPos ) +{ + TabBar* pParent = GetParent(); + long nDiff = rScreenPos.X() - maStartPos.X(); + pParent->mnSplitSize = mnStartWidth + (pParent->IsMirrored() ? -nDiff : nDiff); + if ( pParent->mnSplitSize < TABBAR_MINSIZE ) + pParent->mnSplitSize = TABBAR_MINSIZE; + pParent->Split(); + pParent->PaintImmediately(); +} + +void ImplTabSizer::MouseButtonDown( const MouseEvent& rMEvt ) +{ + if ( GetParent()->IsInEditMode() ) + { + GetParent()->EndEditMode(); + return; + } + + if ( rMEvt.IsLeft() ) + { + maStartPos = OutputToScreenPixel( rMEvt.GetPosPixel() ); + mnStartWidth = GetParent()->GetSizePixel().Width(); + StartTracking(); + } +} + +void ImplTabSizer::Tracking( const TrackingEvent& rTEvt ) +{ + if ( rTEvt.IsTrackingEnded() ) + { + if ( rTEvt.IsTrackingCanceled() ) + ImplTrack( maStartPos ); + GetParent()->mnSplitSize = 0; + } + else + ImplTrack( OutputToScreenPixel( rTEvt.GetMouseEvent().GetPosPixel() ) ); +} + +void ImplTabSizer::Paint( vcl::RenderContext& rRenderContext, const tools::Rectangle& ) +{ + DecorationView aDecoView(&rRenderContext); + tools::Rectangle aOutputRect(Point(0, 0), GetOutputSizePixel()); + aDecoView.DrawHandle(aOutputRect); +} + +namespace { + +// Is not named Impl. as it may be both instantiated and derived from +class TabBarEdit : public Edit +{ +private: + Idle maLoseFocusIdle; + bool mbPostEvt; + + DECL_LINK( ImplEndEditHdl, void*, void ); + DECL_LINK( ImplEndTimerHdl, Timer*, void ); + +public: + TabBarEdit( TabBar* pParent, WinBits nWinStyle ); + + TabBar* GetParent() const { return static_cast<TabBar*>(Window::GetParent()); } + + void SetPostEvent() { mbPostEvt = true; } + void ResetPostEvent() { mbPostEvt = false; } + + virtual bool PreNotify( NotifyEvent& rNEvt ) override; + virtual void LoseFocus() override; +}; + +} + +TabBarEdit::TabBarEdit( TabBar* pParent, WinBits nWinStyle ) : + Edit( pParent, nWinStyle ) +{ + mbPostEvt = false; + maLoseFocusIdle.SetPriority( TaskPriority::REPAINT ); + maLoseFocusIdle.SetInvokeHandler( LINK( this, TabBarEdit, ImplEndTimerHdl ) ); + maLoseFocusIdle.SetDebugName( "svtools::TabBarEdit maLoseFocusIdle" ); +} + +bool TabBarEdit::PreNotify( NotifyEvent& rNEvt ) +{ + if ( rNEvt.GetType() == MouseNotifyEvent::KEYINPUT ) + { + const KeyEvent* pKEvt = rNEvt.GetKeyEvent(); + if ( !pKEvt->GetKeyCode().GetModifier() ) + { + if ( pKEvt->GetKeyCode().GetCode() == KEY_RETURN ) + { + if ( !mbPostEvt ) + { + if ( PostUserEvent( LINK( this, TabBarEdit, ImplEndEditHdl ), reinterpret_cast<void*>(false), true ) ) + mbPostEvt = true; + } + return true; + } + else if ( pKEvt->GetKeyCode().GetCode() == KEY_ESCAPE ) + { + if ( !mbPostEvt ) + { + if ( PostUserEvent( LINK( this, TabBarEdit, ImplEndEditHdl ), reinterpret_cast<void*>(true), true ) ) + mbPostEvt = true; + } + return true; + } + } + } + + return Edit::PreNotify( rNEvt ); +} + +void TabBarEdit::LoseFocus() +{ + if ( !mbPostEvt ) + { + if ( PostUserEvent( LINK( this, TabBarEdit, ImplEndEditHdl ), reinterpret_cast<void*>(false), true ) ) + mbPostEvt = true; + } + + Edit::LoseFocus(); +} + +IMPL_LINK( TabBarEdit, ImplEndEditHdl, void*, pCancel, void ) +{ + ResetPostEvent(); + maLoseFocusIdle.Stop(); + + // We need this query, because the edit gets a losefocus event, + // when it shows the context menu or the insert symbol dialog + if ( !HasFocus() && HasChildPathFocus( true ) ) + { + maLoseFocusIdle.Start(); + } + else + GetParent()->EndEditMode( pCancel != nullptr ); +} + +IMPL_LINK_NOARG(TabBarEdit, ImplEndTimerHdl, Timer *, void) +{ + if ( HasFocus() ) + return; + + // We need this query, because the edit gets a losefocus event, + // when it shows the context menu or the insert symbol dialog + if ( HasChildPathFocus( true ) ) + maLoseFocusIdle.Start(); + else + GetParent()->EndEditMode( true ); +} + +struct TabBar_Impl +{ + ScopedVclPtr<ImplTabSizer> mpSizer; + ScopedVclPtr<ImplTabButton> mpFirstButton; + ScopedVclPtr<ImplTabButton> mpPrevButton; + ScopedVclPtr<ImplTabButton> mpNextButton; + ScopedVclPtr<ImplTabButton> mpLastButton; + ScopedVclPtr<ImplTabButton> mpAddButton; + ScopedVclPtr<TabBarEdit> mpEdit; + std::vector<std::unique_ptr<ImplTabBarItem>> mpItemList; + + vcl::AccessibleFactoryAccess maAccessibleFactory; + + sal_uInt16 getItemSize() const + { + return static_cast<sal_uInt16>(mpItemList.size()); + } +}; + +TabBar::TabBar( vcl::Window* pParent, WinBits nWinStyle ) : + Window( pParent, (nWinStyle & WB_3DLOOK) | WB_CLIPCHILDREN ) +{ + ImplInit( nWinStyle ); + maCurrentItemList = 0; +} + +TabBar::~TabBar() +{ + disposeOnce(); +} + +void TabBar::dispose() +{ + EndEditMode( true ); + mpImpl.reset(); + Window::dispose(); +} + +const sal_uInt16 TabBar::APPEND = ::std::numeric_limits<sal_uInt16>::max(); +const sal_uInt16 TabBar::PAGE_NOT_FOUND = ::std::numeric_limits<sal_uInt16>::max(); + +void TabBar::ImplInit( WinBits nWinStyle ) +{ + mpImpl.reset(new TabBar_Impl); + + mnMaxPageWidth = 0; + mnCurMaxWidth = 0; + mnOffX = 0; + mnOffY = 0; + mnLastOffX = 0; + mnSplitSize = 0; + mnSwitchTime = 0; + mnWinStyle = nWinStyle; + mnCurPageId = 0; + mnFirstPos = 0; + mnDropPos = 0; + mnSwitchId = 0; + mnEditId = 0; + mbFormat = true; + mbFirstFormat = true; + mbSizeFormat = true; + mbAutoEditMode = false; + mbEditCanceled = false; + mbDropPos = false; + mbInSelect = false; + mbMirrored = false; + mbScrollAlwaysEnabled = false; + + ImplInitControls(); + + if (mpImpl->mpFirstButton) + mpImpl->mpFirstButton->SetAccessibleName(SvtResId(STR_TABBAR_PUSHBUTTON_MOVET0HOME)); + if (mpImpl->mpPrevButton) + mpImpl->mpPrevButton->SetAccessibleName(SvtResId(STR_TABBAR_PUSHBUTTON_MOVELEFT)); + if (mpImpl->mpNextButton) + mpImpl->mpNextButton->SetAccessibleName(SvtResId(STR_TABBAR_PUSHBUTTON_MOVERIGHT)); + if (mpImpl->mpLastButton) + mpImpl->mpLastButton->SetAccessibleName(SvtResId(STR_TABBAR_PUSHBUTTON_MOVETOEND)); + + if (mpImpl->mpAddButton) + mpImpl->mpAddButton->SetAccessibleName(SvtResId(STR_TABBAR_PUSHBUTTON_ADDTAB)); + + SetSizePixel( Size( 100, CalcWindowSizePixel().Height() ) ); + ImplInitSettings( true, true ); +} + +ImplTabBarItem* TabBar::seek( size_t i ) +{ + if ( i < mpImpl->mpItemList.size() ) + { + maCurrentItemList = i; + return mpImpl->mpItemList[maCurrentItemList].get(); + } + return nullptr; +} + +ImplTabBarItem* TabBar::prev() +{ + if ( maCurrentItemList > 0 ) + { + return mpImpl->mpItemList[--maCurrentItemList].get(); + } + return nullptr; +} + +ImplTabBarItem* TabBar::next() +{ + if ( maCurrentItemList + 1 < mpImpl->mpItemList.size() ) + { + return mpImpl->mpItemList[++maCurrentItemList].get(); + } + return nullptr; +} + +void TabBar::ImplInitSettings( bool bFont, bool bBackground ) +{ + // FIXME RenderContext + + const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings(); + + if (bFont) + { + vcl::Font aToolFont = rStyleSettings.GetToolFont(); + aToolFont.SetWeight( WEIGHT_BOLD ); + ApplyControlFont(*this, aToolFont); + + // Adapt font size if window too small? + while (GetTextHeight() > (GetOutputSizePixel().Height() - 1)) + { + vcl::Font aFont = GetFont(); + if (aFont.GetFontHeight() <= 6) + break; + aFont.SetFontHeight(aFont.GetFontHeight() - 1); + SetFont(aFont); + } + } + + if (bBackground) + { + ApplyControlBackground(*this, rStyleSettings.GetFaceColor()); + } +} + +void TabBar::ImplGetColors(const StyleSettings& rStyleSettings, + Color& rFaceColor, Color& rFaceTextColor, + Color& rSelectColor, Color& rSelectTextColor) +{ + if (IsControlBackground()) + rFaceColor = GetControlBackground(); + else + rFaceColor = rStyleSettings.GetInactiveTabColor(); + if (IsControlForeground()) + rFaceTextColor = GetControlForeground(); + else + rFaceTextColor = rStyleSettings.GetButtonTextColor(); + rSelectColor = rStyleSettings.GetActiveTabColor(); + rSelectTextColor = rStyleSettings.GetWindowTextColor(); +} + +bool TabBar::ImplCalcWidth() +{ + // Sizes should only be retrieved if the text or the font was changed + if (!mbSizeFormat) + return false; + + // retrieve width of tabs with bold font + vcl::Font aFont = GetFont(); + if (aFont.GetWeight() != WEIGHT_BOLD) + { + aFont.SetWeight(WEIGHT_BOLD); + SetFont(aFont); + } + + if (mnMaxPageWidth) + mnCurMaxWidth = mnMaxPageWidth; + else + { + mnCurMaxWidth = mnLastOffX - mnOffX; + if (mnCurMaxWidth < 1) + mnCurMaxWidth = 1; + } + + bool bChanged = false; + for (auto& pItem : mpImpl->mpItemList) + { + long nNewWidth = GetTextWidth(pItem->GetRenderText()); + if (mnCurMaxWidth && (nNewWidth > mnCurMaxWidth)) + { + pItem->mbShort = true; + nNewWidth = mnCurMaxWidth; + } + else + { + pItem->mbShort = false; + } + + // Padding is dependent on font height - bigger font = bigger padding + long nFontWidth = aFont.GetFontHeight(); + if (pItem->mbProtect) + nNewWidth += 24; + nNewWidth += nFontWidth * 2; + + if (pItem->mnWidth != nNewWidth) + { + pItem->mnWidth = nNewWidth; + if (!pItem->maRect.IsEmpty()) + bChanged = true; + } + } + mbSizeFormat = false; + mbFormat = true; + return bChanged; +} + +void TabBar::ImplFormat() +{ + ImplCalcWidth(); + + if (!mbFormat) + return; + + sal_uInt16 nItemIndex = 0; + long x = mnOffX; + for (auto & pItem : mpImpl->mpItemList) + { + // At all non-visible tabs an empty rectangle is set + if ((nItemIndex + 1 < mnFirstPos) || (x > mnLastOffX)) + pItem->maRect.SetEmpty(); + else + { + // Slightly before the tab before the first visible page + // should also be visible + if (nItemIndex + 1 == mnFirstPos) + { + pItem->maRect.SetLeft(x - pItem->mnWidth); + } + else + { + pItem->maRect.SetLeft(x); + x += pItem->mnWidth; + } + pItem->maRect.SetRight(x); + pItem->maRect.SetBottom(maWinSize.Height() - 1); + + if (mbMirrored) + { + long nNewLeft = mnOffX + mnLastOffX - pItem->maRect.Right(); + long nNewRight = mnOffX + mnLastOffX - pItem->maRect.Left(); + pItem->maRect.SetRight(nNewRight); + pItem->maRect.SetLeft(nNewLeft); + } + } + + nItemIndex++; + } + + mbFormat = false; + + // enable/disable button + ImplEnableControls(); +} + +sal_uInt16 TabBar::ImplGetLastFirstPos() +{ + sal_uInt16 nCount = mpImpl->getItemSize(); + if (!nCount || mbSizeFormat || mbFormat) + return 0; + + sal_uInt16 nLastFirstPos = nCount - 1; + long nWinWidth = mnLastOffX - mnOffX - ADDNEWPAGE_AREAWIDTH; + long nWidth = mpImpl->mpItemList[nLastFirstPos]->mnWidth; + + while (nLastFirstPos && (nWidth < nWinWidth)) + { + nLastFirstPos--; + nWidth += mpImpl->mpItemList[nLastFirstPos]->mnWidth; + } + if ((nLastFirstPos != static_cast<sal_uInt16>(mpImpl->mpItemList.size() - 1)) && (nWidth > nWinWidth)) + nLastFirstPos++; + return nLastFirstPos; +} + +void TabBar::ImplInitControls() +{ + if (mnWinStyle & WB_SIZEABLE) + { + if (!mpImpl->mpSizer) + { + mpImpl->mpSizer.disposeAndReset(VclPtr<ImplTabSizer>::Create( this, mnWinStyle & (WB_DRAG | WB_3DLOOK))); + } + mpImpl->mpSizer->Show(); + } + else + { + mpImpl->mpSizer.disposeAndClear(); + } + + if ((mnWinStyle & WB_INSERTTAB) && !mpImpl->mpAddButton) + { + Link<Button*,void> aLink = LINK(this, TabBar, ImplAddClickHandler); + mpImpl->mpAddButton.disposeAndReset(VclPtr<ImplTabButton>::Create(this, WB_REPEAT)); + mpImpl->mpAddButton->SetClickHdl(aLink); + mpImpl->mpAddButton->SetSymbol(SymbolType::PLUS); + mpImpl->mpAddButton->Show(); + } + + + Link<Button*,void> aLink = LINK( this, TabBar, ImplClickHdl ); + + if (mnWinStyle & (WB_MINSCROLL | WB_SCROLL)) + { + if (!mpImpl->mpPrevButton) + { + mpImpl->mpPrevButton.disposeAndReset(VclPtr<ImplTabButton>::Create(this, WB_REPEAT)); + mpImpl->mpPrevButton->SetClickHdl(aLink); + } + mpImpl->mpPrevButton->SetSymbol(mbMirrored ? SymbolType::NEXT : SymbolType::PREV); + mpImpl->mpPrevButton->Show(); + + if (!mpImpl->mpNextButton) + { + mpImpl->mpNextButton.disposeAndReset(VclPtr<ImplTabButton>::Create(this, WB_REPEAT)); + mpImpl->mpNextButton->SetClickHdl(aLink); + } + mpImpl->mpNextButton->SetSymbol(mbMirrored ? SymbolType::PREV : SymbolType::NEXT); + mpImpl->mpNextButton->Show(); + } + else + { + mpImpl->mpPrevButton.disposeAndClear(); + mpImpl->mpNextButton.disposeAndClear(); + } + + if (mnWinStyle & WB_SCROLL) + { + if (!mpImpl->mpFirstButton) + { + mpImpl->mpFirstButton.disposeAndReset(VclPtr<ImplTabButton>::Create(this)); + mpImpl->mpFirstButton->SetClickHdl(aLink); + } + mpImpl->mpFirstButton->SetSymbol(mbMirrored ? SymbolType::LAST : SymbolType::FIRST); + mpImpl->mpFirstButton->Show(); + + if (!mpImpl->mpLastButton) + { + mpImpl->mpLastButton.disposeAndReset(VclPtr<ImplTabButton>::Create(this)); + mpImpl->mpLastButton->SetClickHdl(aLink); + } + mpImpl->mpLastButton->SetSymbol(mbMirrored ? SymbolType::FIRST : SymbolType::LAST); + mpImpl->mpLastButton->Show(); + } + else + { + mpImpl->mpFirstButton.disposeAndClear(); + mpImpl->mpLastButton.disposeAndClear(); + } +} + +void TabBar::ImplEnableControls() +{ + if (mbSizeFormat || mbFormat) + return; + + // enable/disable buttons + bool bEnableBtn = mbScrollAlwaysEnabled || mnFirstPos > 0; + if (mpImpl->mpFirstButton) + mpImpl->mpFirstButton->Enable(bEnableBtn); + if (mpImpl->mpPrevButton) + mpImpl->mpPrevButton->Enable(bEnableBtn); + + bEnableBtn = mbScrollAlwaysEnabled || mnFirstPos < ImplGetLastFirstPos(); + if (mpImpl->mpNextButton) + mpImpl->mpNextButton->Enable(bEnableBtn); + if (mpImpl->mpLastButton) + mpImpl->mpLastButton->Enable(bEnableBtn); +} + +void TabBar::SetScrollAlwaysEnabled(bool bScrollAlwaysEnabled) +{ + mbScrollAlwaysEnabled = bScrollAlwaysEnabled; + ImplEnableControls(); +} + +void TabBar::ImplShowPage( sal_uInt16 nPos ) +{ + if (nPos >= mpImpl->getItemSize()) + return; + + // calculate width + long nWidth = GetOutputSizePixel().Width(); + + auto& pItem = mpImpl->mpItemList[nPos]; + if (nPos < mnFirstPos) + SetFirstPageId( pItem->mnId ); + else if (pItem->maRect.Right() > nWidth) + { + while (pItem->maRect.Right() > nWidth) + { + sal_uInt16 nNewPos = mnFirstPos + 1; + SetFirstPageId(GetPageId(nNewPos)); + ImplFormat(); + if (nNewPos != mnFirstPos) + break; + } + } +} + +IMPL_LINK( TabBar, ImplClickHdl, Button*, pButton, void ) +{ + ImplTabButton* pBtn = static_cast<ImplTabButton*>(pButton); + EndEditMode(); + + sal_uInt16 nNewPos = mnFirstPos; + + if (pBtn == mpImpl->mpFirstButton.get() || (pBtn == mpImpl->mpPrevButton.get() && pBtn->isModKeyPressed())) + { + nNewPos = 0; + } + else if (pBtn == mpImpl->mpLastButton.get() || (pBtn == mpImpl->mpNextButton.get() && pBtn->isModKeyPressed())) + { + sal_uInt16 nCount = GetPageCount(); + if (nCount) + nNewPos = nCount - 1; + } + else if (pBtn == mpImpl->mpPrevButton.get()) + { + if (mnFirstPos) + nNewPos = mnFirstPos - 1; + } + else if (pBtn == mpImpl->mpNextButton.get()) + { + sal_uInt16 nCount = GetPageCount(); + if (mnFirstPos < nCount) + nNewPos = mnFirstPos+1; + } + else + { + return; + } + + if (nNewPos != mnFirstPos) + SetFirstPageId(GetPageId(nNewPos)); +} + +IMPL_LINK_NOARG(TabBar, ImplAddClickHandler, Button*, void) +{ + AddTabClick(); +} + +void TabBar::MouseMove(const MouseEvent& rMEvt) +{ + if (rMEvt.IsLeaveWindow()) + mbInSelect = false; + + Window::MouseMove(rMEvt); +} + +void TabBar::MouseButtonDown(const MouseEvent& rMEvt) +{ + // Only terminate EditMode and do not execute click + // if clicked inside our window, + if (IsInEditMode()) + { + EndEditMode(); + return; + } + + sal_uInt16 nSelId = GetPageId(rMEvt.GetPosPixel()); + + if (!rMEvt.IsLeft()) + { + Window::MouseButtonDown(rMEvt); + if (nSelId > 0 && nSelId != mnCurPageId) + { + if (ImplDeactivatePage()) + { + SetCurPageId(nSelId); + PaintImmediately(); + ImplActivatePage(); + ImplSelect(); + } + mbInSelect = true; + } + return; + } + + if (rMEvt.IsMod2() && mbAutoEditMode && nSelId) + { + if (StartEditMode(nSelId)) + return; + } + + if ((rMEvt.GetMode() & (MouseEventModifiers::MULTISELECT | MouseEventModifiers::RANGESELECT)) && (rMEvt.GetClicks() == 1)) + { + if (nSelId) + { + sal_uInt16 nPos = GetPagePos(nSelId); + + bool bSelectTab = false; + + if ((rMEvt.GetMode() & MouseEventModifiers::MULTISELECT) && (mnWinStyle & WB_MULTISELECT)) + { + if (nSelId != mnCurPageId) + { + SelectPage(nSelId, !IsPageSelected(nSelId)); + bSelectTab = true; + } + } + else if (mnWinStyle & (WB_MULTISELECT | WB_RANGESELECT)) + { + bSelectTab = true; + sal_uInt16 n; + bool bSelect; + sal_uInt16 nCurPos = GetPagePos(mnCurPageId); + if (nPos <= nCurPos) + { + // Deselect all tabs till the clicked tab + // and select all tabs from the clicked tab + // 'till the actual position + n = 0; + while (n < nCurPos) + { + auto& pItem = mpImpl->mpItemList[n]; + bSelect = n >= nPos; + + if (pItem->mbSelect != bSelect) + { + pItem->mbSelect = bSelect; + if (!pItem->maRect.IsEmpty()) + Invalidate(pItem->maRect); + } + + n++; + } + } + + if (nPos >= nCurPos) + { + // Select all tabs from the actual position till the clicked tab + // and deselect all tabs from the actual position + // till the last tab + sal_uInt16 nCount = mpImpl->getItemSize(); + n = nCurPos; + while (n < nCount) + { + auto& pItem = mpImpl->mpItemList[n]; + + bSelect = n <= nPos; + + if (pItem->mbSelect != bSelect) + { + pItem->mbSelect = bSelect; + if (!pItem->maRect.IsEmpty()) + Invalidate(pItem->maRect); + } + + n++; + } + } + } + + // scroll the selected tab if required + if (bSelectTab) + { + ImplShowPage(nPos); + PaintImmediately(); + ImplSelect(); + } + + mbInSelect = true; + + return; + } + } + else if (rMEvt.GetClicks() == 2) + { + // call double-click-handler if required + if (!rMEvt.GetModifier() && (!nSelId || (nSelId == mnCurPageId))) + { + sal_uInt16 nOldCurId = mnCurPageId; + mnCurPageId = nSelId; + DoubleClick(); + // check, as actual page could be switched inside + // the doubleclick-handler + if (mnCurPageId == nSelId) + mnCurPageId = nOldCurId; + } + + return; + } + else + { + if (nSelId) + { + // execute Select if not actual page + if (nSelId != mnCurPageId) + { + sal_uInt16 nPos = GetPagePos(nSelId); + auto& pItem = mpImpl->mpItemList[nPos]; + + if (!pItem->mbSelect) + { + // make not valid + bool bUpdate = false; + if (IsReallyVisible() && IsUpdateMode()) + bUpdate = true; + + // deselect all selected items + for (auto& xItem : mpImpl->mpItemList) + { + if (xItem->mbSelect || (xItem->mnId == mnCurPageId)) + { + xItem->mbSelect = false; + if (bUpdate) + Invalidate(xItem->maRect); + } + } + } + + if (ImplDeactivatePage()) + { + SetCurPageId(nSelId); + PaintImmediately(); + ImplActivatePage(); + ImplSelect(); + } + + mbInSelect = true; + } + + return; + } + } + + Window::MouseButtonDown(rMEvt); +} + +void TabBar::MouseButtonUp(const MouseEvent& rMEvt) +{ + mbInSelect = false; + Window::MouseButtonUp(rMEvt); +} + +void TabBar::Paint(vcl::RenderContext& rRenderContext, const tools::Rectangle& rect) +{ + if (rRenderContext.IsNativeControlSupported(ControlType::WindowBackground,ControlPart::Entire)) + { + rRenderContext.DrawNativeControl(ControlType::WindowBackground,ControlPart::Entire,rect, + ControlState::ENABLED,ImplControlValue(0),OUString()); + } + // calculate items and emit + sal_uInt16 nItemCount = mpImpl->getItemSize(); + if (!nItemCount) + return; + + ImplPrePaint(); + + Color aFaceColor, aSelectColor, aFaceTextColor, aSelectTextColor; + const StyleSettings& rStyleSettings = rRenderContext.GetSettings().GetStyleSettings(); + ImplGetColors(rStyleSettings, aFaceColor, aFaceTextColor, aSelectColor, aSelectTextColor); + + rRenderContext.Push(PushFlags::FONT | PushFlags::CLIPREGION); + rRenderContext.SetClipRegion(vcl::Region(GetPageArea())); + + // select font + vcl::Font aFont = rRenderContext.GetFont(); + vcl::Font aLightFont = aFont; + aLightFont.SetWeight(WEIGHT_NORMAL); + + TabDrawer aDrawer(rRenderContext); + + aDrawer.setSelectedFillColor(aSelectColor); + + // Now, start drawing the tabs. + + ImplTabBarItem* pItem = ImplGetLastTabBarItem(nItemCount); + ImplTabBarItem* pCurItem = nullptr; + while (pItem) + { + // emit CurrentItem last, as it covers all others + if (!pCurItem && (pItem->mnId == mnCurPageId)) + { + pCurItem = pItem; + pItem = prev(); + if (!pItem) + pItem = pCurItem; + continue; + } + + bool bCurrent = pItem == pCurItem; + + if (!pItem->maRect.IsEmpty()) + { + tools::Rectangle aRect = pItem->maRect; + bool bSelected = pItem->IsSelected(pCurItem); + // We disable custom background color in high contrast mode. + bool bCustomBgColor = !pItem->IsDefaultTabBgColor() && !rStyleSettings.GetHighContrastMode(); + OUString aText = pItem->mbShort ? + rRenderContext.GetEllipsisString(pItem->GetRenderText(), mnCurMaxWidth) : + pItem->GetRenderText(); + + aDrawer.setRect(aRect); + aDrawer.setSelected(bSelected); + aDrawer.setCustomColored(bCustomBgColor); + aDrawer.setEnabled(true); + aDrawer.setCustomColor(pItem->maTabBgColor); + aDrawer.mbProtect = pItem->mbProtect; + aDrawer.drawTab(); + + // actual page is drawn using a bold font + rRenderContext.SetFont(aLightFont); + + // Set the correct FillInBrush depending on status + + if (bSelected) + rRenderContext.SetTextColor(aSelectTextColor); + else if (bCustomBgColor) + rRenderContext.SetTextColor(pItem->maTabTextColor); + else + rRenderContext.SetTextColor(aFaceTextColor); + + // Special display of tab name depending on page bits + + if (pItem->mnBits & TabBarPageBits::Blue) + { + rRenderContext.SetTextColor(COL_LIGHTBLUE); + } + if (pItem->mnBits & TabBarPageBits::Italic) + { + vcl::Font aSpecialFont = rRenderContext.GetFont(); + aSpecialFont.SetItalic(FontItalic::ITALIC_NORMAL); + rRenderContext.SetFont(aSpecialFont); + } + if (pItem->mnBits & TabBarPageBits::Underline) + { + vcl::Font aSpecialFont = rRenderContext.GetFont(); + aSpecialFont.SetUnderline(LINESTYLE_SINGLE); + rRenderContext.SetFont(aSpecialFont); + } + + aDrawer.drawText(aText); + + if (bCurrent) + { + rRenderContext.SetLineColor(); + rRenderContext.SetFillColor(aSelectColor); + aDrawer.drawOverTopBorder(); + break; + } + + pItem = prev(); + } + else + { + if (bCurrent) + break; + + pItem = nullptr; + } + + if (!pItem) + pItem = pCurItem; + } + rRenderContext.Pop(); +} + +void TabBar::Resize() +{ + Size aNewSize = GetOutputSizePixel(); + + long nSizerWidth = 0; + long nButtonWidth = 0; + + // order the Sizer + if ( mpImpl->mpSizer ) + { + Size aSizerSize = mpImpl->mpSizer->GetSizePixel(); + Point aNewSizerPos( mbMirrored ? 0 : (aNewSize.Width()-aSizerSize.Width()), 0 ); + Size aNewSizerSize( aSizerSize.Width(), aNewSize.Height() ); + mpImpl->mpSizer->SetPosSizePixel( aNewSizerPos, aNewSizerSize ); + nSizerWidth = aSizerSize.Width(); + } + + // order the scroll buttons + long const nHeight = aNewSize.Height(); + // adapt font height? + ImplInitSettings( true, false ); + + long nButtonMargin = BUTTON_MARGIN * GetDPIScaleFactor(); + + long nX = mbMirrored ? (aNewSize.Width() - nHeight - nButtonMargin) : nButtonMargin; + long const nXDiff = mbMirrored ? -nHeight : nHeight; + + nButtonWidth += nButtonMargin; + + Size const aBtnSize( nHeight, nHeight ); + auto setButton = [aBtnSize, nXDiff, nHeight, &nX, &nButtonWidth]( + ScopedVclPtr<ImplTabButton> const & button) + { + if (button) { + button->SetPosSizePixel(Point(nX, 0), aBtnSize); + nX += nXDiff; + nButtonWidth += nHeight; + } + }; + + setButton(mpImpl->mpFirstButton); + setButton(mpImpl->mpPrevButton); + setButton(mpImpl->mpNextButton); + setButton(mpImpl->mpLastButton); + + nButtonWidth += nButtonMargin; + nX += mbMirrored ? -nButtonMargin : nButtonMargin; + + setButton(mpImpl->mpAddButton); + + nButtonWidth += nButtonMargin; + + // store size + maWinSize = aNewSize; + + if( mbMirrored ) + { + mnOffX = nSizerWidth; + mnLastOffX = maWinSize.Width() - nButtonWidth - 1; + } + else + { + mnOffX = nButtonWidth; + mnLastOffX = maWinSize.Width() - nSizerWidth - 1; + } + + // reformat + mbSizeFormat = true; + if ( IsReallyVisible() ) + { + if ( ImplCalcWidth() ) + Invalidate(); + + ImplFormat(); + + // Ensure as many tabs as possible are visible: + sal_uInt16 nLastFirstPos = ImplGetLastFirstPos(); + if ( mnFirstPos > nLastFirstPos ) + { + mnFirstPos = nLastFirstPos; + mbFormat = true; + Invalidate(); + } + // Ensure the currently selected page is visible + ImplShowPage(GetPagePos(mnCurPageId)); + + ImplFormat(); + } + + // enable/disable button + ImplEnableControls(); +} + +bool TabBar::PreNotify(NotifyEvent& rNEvt) +{ + if (rNEvt.GetType() == MouseNotifyEvent::COMMAND) + { + if (rNEvt.GetCommandEvent()->GetCommand() == CommandEventId::Wheel) + { + const CommandWheelData* pData = rNEvt.GetCommandEvent()->GetWheelData(); + sal_uInt16 nNewPos = mnFirstPos; + if (pData->GetNotchDelta() > 0) + { + if (mnFirstPos) + nNewPos = mnFirstPos - 1; + } + else if (pData->GetNotchDelta() < 0) + { + sal_uInt16 nCount = GetPageCount(); + if (mnFirstPos < nCount) + nNewPos = mnFirstPos + 1; + } + if (nNewPos != mnFirstPos) + SetFirstPageId(GetPageId(nNewPos)); + } + } + return Window::PreNotify(rNEvt); +} + +void TabBar::RequestHelp(const HelpEvent& rHEvt) +{ + sal_uInt16 nItemId = GetPageId(ScreenToOutputPixel(rHEvt.GetMousePosPixel())); + if (nItemId) + { + if (rHEvt.GetMode() & HelpEventMode::BALLOON) + { + OUString aStr = GetHelpText(nItemId); + if (!aStr.isEmpty()) + { + tools::Rectangle aItemRect = GetPageRect(nItemId); + Point aPt = OutputToScreenPixel(aItemRect.TopLeft()); + aItemRect.SetLeft( aPt.X() ); + aItemRect.SetTop( aPt.Y() ); + aPt = OutputToScreenPixel(aItemRect.BottomRight()); + aItemRect.SetRight( aPt.X() ); + aItemRect.SetBottom( aPt.Y() ); + Help::ShowBalloon(this, aItemRect.Center(), aItemRect, aStr); + return; + } + } + + // show text for quick- or balloon-help + // if this is isolated or not fully visible + if (rHEvt.GetMode() & (HelpEventMode::QUICK | HelpEventMode::BALLOON)) + { + sal_uInt16 nPos = GetPagePos(nItemId); + auto& pItem = mpImpl->mpItemList[nPos]; + if (pItem->mbShort || (pItem->maRect.Right() - 5 > mnLastOffX)) + { + tools::Rectangle aItemRect = GetPageRect(nItemId); + Point aPt = OutputToScreenPixel(aItemRect.TopLeft()); + aItemRect.SetLeft( aPt.X() ); + aItemRect.SetTop( aPt.Y() ); + aPt = OutputToScreenPixel(aItemRect.BottomRight()); + aItemRect.SetRight( aPt.X() ); + aItemRect.SetBottom( aPt.Y() ); + OUString aStr = mpImpl->mpItemList[nPos]->maText; + if (!aStr.isEmpty()) + { + if (rHEvt.GetMode() & HelpEventMode::BALLOON) + Help::ShowBalloon(this, aItemRect.Center(), aItemRect, aStr); + else + Help::ShowQuickHelp(this, aItemRect, aStr); + return; + } + } + } + } + + Window::RequestHelp(rHEvt); +} + +void TabBar::StateChanged(StateChangedType nType) +{ + Window::StateChanged(nType); + + if (nType == StateChangedType::InitShow) + { + if ( (mbSizeFormat || mbFormat) && !mpImpl->mpItemList.empty() ) + ImplFormat(); + } + else if (nType == StateChangedType::Zoom || + nType == StateChangedType::ControlFont) + { + ImplInitSettings(true, false); + Invalidate(); + } + else if (nType == StateChangedType::ControlForeground) + Invalidate(); + else if (nType == StateChangedType::ControlBackground) + { + ImplInitSettings(false, true); + Invalidate(); + } + else if (nType == StateChangedType::Mirroring) + { + // reacts on calls of EnableRTL, have to mirror all child controls + if (mpImpl->mpFirstButton) + mpImpl->mpFirstButton->EnableRTL(IsRTLEnabled()); + if (mpImpl->mpPrevButton) + mpImpl->mpPrevButton->EnableRTL(IsRTLEnabled()); + if (mpImpl->mpNextButton) + mpImpl->mpNextButton->EnableRTL(IsRTLEnabled()); + if (mpImpl->mpLastButton) + mpImpl->mpLastButton->EnableRTL(IsRTLEnabled()); + if (mpImpl->mpSizer) + mpImpl->mpSizer->EnableRTL(IsRTLEnabled()); + if (mpImpl->mpAddButton) + mpImpl->mpAddButton->EnableRTL(IsRTLEnabled()); + if (mpImpl->mpEdit) + mpImpl->mpEdit->EnableRTL(IsRTLEnabled()); + } +} + +void TabBar::DataChanged(const DataChangedEvent& rDCEvt) +{ + Window::DataChanged(rDCEvt); + + if (rDCEvt.GetType() == DataChangedEventType::FONTS + || rDCEvt.GetType() == DataChangedEventType::FONTSUBSTITUTION + || (rDCEvt.GetType() == DataChangedEventType::SETTINGS + && rDCEvt.GetFlags() & AllSettingsFlags::STYLE)) + { + ImplInitSettings(true, true); + Invalidate(); + } +} + +void TabBar::ImplSelect() +{ + Select(); + CallEventListeners(VclEventId::TabbarPageSelected, reinterpret_cast<void*>(sal::static_int_cast<sal_IntPtr>(mnCurPageId))); +} + +void TabBar::Select() +{ + maSelectHdl.Call(this); +} + +void TabBar::DoubleClick() +{ +} + +void TabBar::Split() +{ + maSplitHdl.Call(this); +} + +void TabBar::ImplActivatePage() +{ + ActivatePage(); + + CallEventListeners(VclEventId::TabbarPageActivated, reinterpret_cast<void*>(sal::static_int_cast<sal_IntPtr>(mnCurPageId))); +} + +void TabBar::ActivatePage() +{} + +bool TabBar::ImplDeactivatePage() +{ + bool bRet = DeactivatePage(); + + CallEventListeners(VclEventId::TabbarPageDeactivated, reinterpret_cast<void*>(sal::static_int_cast<sal_IntPtr>(mnCurPageId))); + + return bRet; +} + +void TabBar::ImplPrePaint() +{ + sal_uInt16 nItemCount = mpImpl->getItemSize(); + if (!nItemCount) + return; + + // tabbar should be formatted + ImplFormat(); + + // assure the actual tabpage becomes visible at first format + if (!mbFirstFormat) + return; + + mbFirstFormat = false; + + if (!(mnCurPageId && (mnFirstPos == 0) && !mbDropPos)) + return; + + auto& pItem = mpImpl->mpItemList[GetPagePos(mnCurPageId)]; + if (pItem->maRect.IsEmpty()) + { + // set mbDropPos (or misuse) to prevent Invalidate() + mbDropPos = true; + SetFirstPageId(mnCurPageId); + mbDropPos = false; + if (mnFirstPos != 0) + ImplFormat(); + } +} + +ImplTabBarItem* TabBar::ImplGetLastTabBarItem( sal_uInt16 nItemCount ) +{ + // find last visible entry + sal_uInt16 n = mnFirstPos + 1; + if (n >= nItemCount) + n = nItemCount-1; + ImplTabBarItem* pItem = seek(n); + while (pItem) + { + if (!pItem->maRect.IsEmpty()) + { + n++; + pItem = next(); + } + else + break; + } + + // draw all tabs (from back to front and actual last) + if (pItem) + n--; + else if (n >= nItemCount) + n = nItemCount-1; + pItem = seek(n); + return pItem; +} + +bool TabBar::DeactivatePage() +{ + return true; +} + +bool TabBar::StartRenaming() +{ + return true; +} + +TabBarAllowRenamingReturnCode TabBar::AllowRenaming() +{ + return TABBAR_RENAMING_YES; +} + +void TabBar::EndRenaming() +{ +} + +void TabBar::Mirror() +{ + +} + +void TabBar::AddTabClick() +{ + +} + +void TabBar::InsertPage(sal_uInt16 nPageId, const OUString& rText, + TabBarPageBits nBits, sal_uInt16 nPos) +{ + assert (nPageId && "TabBar::InsertPage(): PageId must not be 0"); + assert ((GetPagePos(nPageId) == PAGE_NOT_FOUND) && "TabBar::InsertPage(): Page already exists"); + assert ((nBits <= TPB_DISPLAY_NAME_ALLFLAGS) && "TabBar::InsertPage(): Invalid flag set in nBits"); + + // create PageItem and insert in the item list + std::unique_ptr<ImplTabBarItem> pItem(new ImplTabBarItem( nPageId, rText, nBits )); + if (nPos < mpImpl->mpItemList.size()) + { + auto it = mpImpl->mpItemList.begin(); + it += nPos; + mpImpl->mpItemList.insert(it, std::move(pItem)); + } + else + { + mpImpl->mpItemList.push_back(std::move(pItem)); + } + mbSizeFormat = true; + + // set CurPageId if required + if (!mnCurPageId) + mnCurPageId = nPageId; + + // redraw bar + if (IsReallyVisible() && IsUpdateMode()) + Invalidate(); + + CallEventListeners(VclEventId::TabbarPageInserted, reinterpret_cast<void*>(sal::static_int_cast<sal_IntPtr>(nPageId))); +} + +Color TabBar::GetTabBgColor(sal_uInt16 nPageId) const +{ + sal_uInt16 nPos = GetPagePos(nPageId); + + if (nPos != PAGE_NOT_FOUND) + return mpImpl->mpItemList[nPos]->maTabBgColor; + else + return COL_AUTO; +} + +void TabBar::SetTabBgColor(sal_uInt16 nPageId, const Color& aTabBgColor) +{ + sal_uInt16 nPos = GetPagePos(nPageId); + if (nPos == PAGE_NOT_FOUND) + return; + + auto& pItem = mpImpl->mpItemList[nPos]; + if (aTabBgColor != COL_AUTO) + { + pItem->maTabBgColor = aTabBgColor; + if (aTabBgColor.GetLuminance() <= 128) //Do not use aTabBgColor.IsDark(), because that threshold is way too low... + pItem->maTabTextColor = COL_WHITE; + else + pItem->maTabTextColor = COL_BLACK; + } + else + { + pItem->maTabBgColor = COL_AUTO; + pItem->maTabTextColor = COL_AUTO; + } +} + +void TabBar::RemovePage(sal_uInt16 nPageId) +{ + sal_uInt16 nPos = GetPagePos(nPageId); + + // does item exist + if (nPos == PAGE_NOT_FOUND) + return; + + if (mnCurPageId == nPageId) + mnCurPageId = 0; + + // check if first visible page should be moved + if (mnFirstPos > nPos) + mnFirstPos--; + + // delete item data + auto it = mpImpl->mpItemList.begin(); + it += nPos; + mpImpl->mpItemList.erase(it); + + // redraw bar + if (IsReallyVisible() && IsUpdateMode()) + Invalidate(); + + CallEventListeners(VclEventId::TabbarPageRemoved, reinterpret_cast<void*>(sal::static_int_cast<sal_IntPtr>(nPageId))); +} + +void TabBar::MovePage(sal_uInt16 nPageId, sal_uInt16 nNewPos) +{ + sal_uInt16 nPos = GetPagePos(nPageId); + Pair aPair(nPos, nNewPos); + + if (nPos < nNewPos) + nNewPos--; + + if (nPos == nNewPos) + return; + + // does item exit + if (nPos == PAGE_NOT_FOUND) + return; + + // move tabbar item in the list + auto it = mpImpl->mpItemList.begin(); + it += nPos; + std::unique_ptr<ImplTabBarItem> pItem = std::move(*it); + mpImpl->mpItemList.erase(it); + if (nNewPos < mpImpl->mpItemList.size()) + { + it = mpImpl->mpItemList.begin(); + it += nNewPos; + mpImpl->mpItemList.insert(it, std::move(pItem)); + } + else + { + mpImpl->mpItemList.push_back(std::move(pItem)); + } + + // redraw bar + if (IsReallyVisible() && IsUpdateMode()) + Invalidate(); + + CallEventListeners( VclEventId::TabbarPageMoved, static_cast<void*>(&aPair) ); +} + +void TabBar::Clear() +{ + // delete all items + mpImpl->mpItemList.clear(); + + // remove items from the list + mbSizeFormat = true; + mnCurPageId = 0; + mnFirstPos = 0; + maCurrentItemList = 0; + + // redraw bar + if (IsReallyVisible() && IsUpdateMode()) + Invalidate(); + + CallEventListeners(VclEventId::TabbarPageRemoved, reinterpret_cast<void*>(sal::static_int_cast<sal_IntPtr>(PAGE_NOT_FOUND))); +} + +bool TabBar::IsPageEnabled(sal_uInt16 nPageId) const +{ + sal_uInt16 nPos = GetPagePos(nPageId); + + return nPos != PAGE_NOT_FOUND; +} + +void TabBar::SetPageBits(sal_uInt16 nPageId, TabBarPageBits nBits) +{ + sal_uInt16 nPos = GetPagePos(nPageId); + + if (nPos == PAGE_NOT_FOUND) + return; + + auto& pItem = mpImpl->mpItemList[nPos]; + + if (pItem->mnBits != nBits) + { + pItem->mnBits = nBits; + + // redraw bar + if (IsReallyVisible() && IsUpdateMode()) + Invalidate(pItem->maRect); + } +} + +TabBarPageBits TabBar::GetPageBits(sal_uInt16 nPageId) const +{ + sal_uInt16 nPos = GetPagePos(nPageId); + + if (nPos != PAGE_NOT_FOUND) + return mpImpl->mpItemList[nPos]->mnBits; + else + return TabBarPageBits::NONE; +} + +sal_uInt16 TabBar::GetPageCount() const +{ + return mpImpl->getItemSize(); +} + +sal_uInt16 TabBar::GetPageId(sal_uInt16 nPos) const +{ + return nPos < mpImpl->mpItemList.size() ? mpImpl->mpItemList[nPos]->mnId : 0; +} + +sal_uInt16 TabBar::GetPagePos(sal_uInt16 nPageId) const +{ + for (size_t i = 0; i < mpImpl->mpItemList.size(); ++i) + { + if (mpImpl->mpItemList[i]->mnId == nPageId) + { + return static_cast<sal_uInt16>(i); + } + } + return PAGE_NOT_FOUND; +} + +sal_uInt16 TabBar::GetPageId(const Point& rPos) const +{ + for (const auto& pItem : mpImpl->mpItemList) + { + if (pItem->maRect.IsInside(rPos)) + return pItem->mnId; + } + + return 0; +} + +tools::Rectangle TabBar::GetPageRect(sal_uInt16 nPageId) const +{ + sal_uInt16 nPos = GetPagePos(nPageId); + + if (nPos != PAGE_NOT_FOUND) + return mpImpl->mpItemList[nPos]->maRect; + else + return tools::Rectangle(); +} + +void TabBar::SetCurPageId(sal_uInt16 nPageId) +{ + sal_uInt16 nPos = GetPagePos(nPageId); + + // do nothing if item does not exit + if (nPos == PAGE_NOT_FOUND) + return; + + // do nothing if the actual page did not change + if (nPageId == mnCurPageId) + return; + + // make invalid + bool bUpdate = false; + if (IsReallyVisible() && IsUpdateMode()) + bUpdate = true; + + auto& pItem = mpImpl->mpItemList[nPos]; + ImplTabBarItem* pOldItem; + + if (mnCurPageId) + pOldItem = mpImpl->mpItemList[GetPagePos(mnCurPageId)].get(); + else + pOldItem = nullptr; + + // deselect previous page if page was not selected, if this is the + // only selected page + if (!pItem->mbSelect && pOldItem) + { + sal_uInt16 nSelPageCount = GetSelectPageCount(); + if (nSelPageCount == 1) + pOldItem->mbSelect = false; + pItem->mbSelect = true; + } + + mnCurPageId = nPageId; + mbFormat = true; + + // assure the actual page becomes visible + if (IsReallyVisible()) + { + if (nPos < mnFirstPos) + SetFirstPageId(nPageId); + else + { + // calculate visible width + long nWidth = mnLastOffX; + if (nWidth > ADDNEWPAGE_AREAWIDTH) + nWidth -= ADDNEWPAGE_AREAWIDTH; + + if (pItem->maRect.IsEmpty()) + ImplFormat(); + + while ((mbMirrored ? (pItem->maRect.Left() < mnOffX) : (pItem->maRect.Right() > nWidth)) || + pItem->maRect.IsEmpty()) + { + sal_uInt16 nNewPos = mnFirstPos + 1; + // assure at least the actual tabpages are visible as first tabpage + if (nNewPos >= nPos) + { + SetFirstPageId(nPageId); + break; + } + else + SetFirstPageId(GetPageId(nNewPos)); + ImplFormat(); + // abort if first page is not forwarded + if (nNewPos != mnFirstPos) + break; + } + } + } + + // redraw bar + if (bUpdate) + { + Invalidate(pItem->maRect); + if (pOldItem) + Invalidate(pOldItem->maRect); + } +} + +void TabBar::MakeVisible(sal_uInt16 nPageId) +{ + if (!IsReallyVisible()) + return; + + sal_uInt16 nPos = GetPagePos(nPageId); + + // do nothing if item does not exist + if (nPos == PAGE_NOT_FOUND) + return; + + if (nPos < mnFirstPos) + SetFirstPageId(nPageId); + else + { + auto& pItem = mpImpl->mpItemList[nPos]; + + // calculate visible area + long nWidth = mnLastOffX; + + if (mbFormat || pItem->maRect.IsEmpty()) + { + mbFormat = true; + ImplFormat(); + } + + while ((pItem->maRect.Right() > nWidth) || + pItem->maRect.IsEmpty()) + { + sal_uInt16 nNewPos = mnFirstPos+1; + // assure at least the actual tabpages are visible as first tabpage + if (nNewPos >= nPos) + { + SetFirstPageId(nPageId); + break; + } + else + SetFirstPageId(GetPageId(nNewPos)); + ImplFormat(); + // abort if first page is not forwarded + if (nNewPos != mnFirstPos) + break; + } + } +} + +void TabBar::SetFirstPageId(sal_uInt16 nPageId) +{ + sal_uInt16 nPos = GetPagePos(nPageId); + + // return false if item does not exist + if (nPos == PAGE_NOT_FOUND) + return; + + if (nPos == mnFirstPos) + return; + + // assure as much pages are visible as possible + ImplFormat(); + sal_uInt16 nLastFirstPos = ImplGetLastFirstPos(); + sal_uInt16 nNewPos; + if (nPos > nLastFirstPos) + nNewPos = nLastFirstPos; + else + nNewPos = nPos; + + if (nNewPos != mnFirstPos) + { + mnFirstPos = nNewPos; + mbFormat = true; + + // redraw bar (attention: check mbDropPos, + // as if this flag was set, we do not re-paint immediately + if (IsReallyVisible() && IsUpdateMode() && !mbDropPos) + Invalidate(); + } +} + +void TabBar::SelectPage(sal_uInt16 nPageId, bool bSelect) +{ + sal_uInt16 nPos = GetPagePos(nPageId); + + if (nPos == PAGE_NOT_FOUND) + return; + + auto& pItem = mpImpl->mpItemList[nPos]; + + if (pItem->mbSelect != bSelect) + { + pItem->mbSelect = bSelect; + + // redraw bar + if (IsReallyVisible() && IsUpdateMode()) + Invalidate(pItem->maRect); + } +} + +sal_uInt16 TabBar::GetSelectPageCount() const +{ + sal_uInt16 nSelected = 0; + for (const auto& pItem : mpImpl->mpItemList) + { + if (pItem->mbSelect) + nSelected++; + } + + return nSelected; +} + +bool TabBar::IsPageSelected(sal_uInt16 nPageId) const +{ + sal_uInt16 nPos = GetPagePos(nPageId); + if (nPos != PAGE_NOT_FOUND) + return mpImpl->mpItemList[nPos]->mbSelect; + else + return false; +} + +void TabBar::SetProtectionSymbol(sal_uInt16 nPageId, bool bProtection) +{ + sal_uInt16 nPos = GetPagePos(nPageId); + if (nPos != PAGE_NOT_FOUND) + { + if (mpImpl->mpItemList[nPos]->mbProtect != bProtection) + { + mpImpl->mpItemList[nPos]->mbProtect = bProtection; + mbSizeFormat = true; // render text width changes, thus bar width + + // redraw bar + if (IsReallyVisible() && IsUpdateMode()) + Invalidate(); + } + } +} + +bool TabBar::StartEditMode(sal_uInt16 nPageId) +{ + sal_uInt16 nPos = GetPagePos( nPageId ); + if (mpImpl->mpEdit || (nPos == PAGE_NOT_FOUND) || (mnLastOffX < 8)) + return false; + + mnEditId = nPageId; + if (StartRenaming()) + { + ImplShowPage(nPos); + ImplFormat(); + PaintImmediately(); + + mpImpl->mpEdit.disposeAndReset(VclPtr<TabBarEdit>::Create(this, WB_CENTER)); + tools::Rectangle aRect = GetPageRect( mnEditId ); + long nX = aRect.Left(); + long nWidth = aRect.GetWidth(); + if (mnEditId != GetCurPageId()) + nX += 1; + if (nX + nWidth > mnLastOffX) + nWidth = mnLastOffX-nX; + if (nWidth < 3) + { + nX = aRect.Left(); + nWidth = aRect.GetWidth(); + } + mpImpl->mpEdit->SetText(GetPageText(mnEditId)); + mpImpl->mpEdit->setPosSizePixel(nX, aRect.Top() + mnOffY + 1, nWidth, aRect.GetHeight() - 3); + vcl::Font aFont = GetPointFont(*this); // FIXME RenderContext + + Color aForegroundColor; + Color aBackgroundColor; + Color aFaceColor; + Color aSelectColor; + Color aFaceTextColor; + Color aSelectTextColor; + + ImplGetColors(Application::GetSettings().GetStyleSettings(), aFaceColor, aFaceTextColor, aSelectColor, aSelectTextColor); + + if (mnEditId != GetCurPageId()) + { + aFont.SetWeight(WEIGHT_LIGHT); + } + if (IsPageSelected(mnEditId) || mnEditId == GetCurPageId()) + { + aForegroundColor = aSelectTextColor; + aBackgroundColor = aSelectColor; + } + else + { + aForegroundColor = aFaceTextColor; + aBackgroundColor = aFaceColor; + } + if (GetPageBits( mnEditId ) & TabBarPageBits::Blue) + { + aForegroundColor = COL_LIGHTBLUE; + } + mpImpl->mpEdit->SetControlFont(aFont); + mpImpl->mpEdit->SetControlForeground(aForegroundColor); + mpImpl->mpEdit->SetControlBackground(aBackgroundColor); + mpImpl->mpEdit->GrabFocus(); + mpImpl->mpEdit->SetSelection(Selection(0, mpImpl->mpEdit->GetText().getLength())); + mpImpl->mpEdit->Show(); + return true; + } + else + { + mnEditId = 0; + return false; + } +} + +bool TabBar::IsInEditMode() const +{ + return mpImpl->mpEdit.get() != nullptr; +} + +void TabBar::EndEditMode(bool bCancel) +{ + if (!mpImpl->mpEdit) + return; + + // call hdl + bool bEnd = true; + mbEditCanceled = bCancel; + maEditText = mpImpl->mpEdit->GetText(); + mpImpl->mpEdit->SetPostEvent(); + if (!bCancel) + { + TabBarAllowRenamingReturnCode nAllowRenaming = AllowRenaming(); + if (nAllowRenaming == TABBAR_RENAMING_YES) + SetPageText(mnEditId, maEditText); + else if (nAllowRenaming == TABBAR_RENAMING_NO) + bEnd = false; + else // nAllowRenaming == TABBAR_RENAMING_CANCEL + mbEditCanceled = true; + } + + // renaming not allowed, then reset edit data + if (!bEnd) + { + mpImpl->mpEdit->ResetPostEvent(); + mpImpl->mpEdit->GrabFocus(); + } + else + { + // close edit and call end hdl + mpImpl->mpEdit.disposeAndClear(); + + EndRenaming(); + mnEditId = 0; + } + + // reset + maEditText.clear(); + mbEditCanceled = false; +} + +void TabBar::SetMirrored(bool bMirrored) +{ + if (mbMirrored != bMirrored) + { + mbMirrored = bMirrored; + mbSizeFormat = true; + ImplInitControls(); // for button images + Resize(); // recalculates control positions + Mirror(); + } +} + +void TabBar::SetEffectiveRTL(bool bRTL) +{ + SetMirrored( bRTL != AllSettings::GetLayoutRTL() ); +} + +bool TabBar::IsEffectiveRTL() const +{ + return IsMirrored() != AllSettings::GetLayoutRTL(); +} + +void TabBar::SetMaxPageWidth(long nMaxWidth) +{ + if (mnMaxPageWidth != nMaxWidth) + { + mnMaxPageWidth = nMaxWidth; + mbSizeFormat = true; + + // redraw bar + if (IsReallyVisible() && IsUpdateMode()) + Invalidate(); + } +} + +void TabBar::SetPageText(sal_uInt16 nPageId, const OUString& rText) +{ + sal_uInt16 nPos = GetPagePos(nPageId); + if (nPos != PAGE_NOT_FOUND) + { + mpImpl->mpItemList[nPos]->maText = rText; + mbSizeFormat = true; + + // redraw bar + if (IsReallyVisible() && IsUpdateMode()) + Invalidate(); + + CallEventListeners(VclEventId::TabbarPageTextChanged, reinterpret_cast<void*>(sal::static_int_cast<sal_IntPtr>(nPageId))); + } +} + +OUString TabBar::GetPageText(sal_uInt16 nPageId) const +{ + sal_uInt16 nPos = GetPagePos(nPageId); + if (nPos != PAGE_NOT_FOUND) + return mpImpl->mpItemList[nPos]->maText; + return OUString(); +} + +OUString TabBar::GetAuxiliaryText(sal_uInt16 nPageId) const +{ + sal_uInt16 nPos = GetPagePos(nPageId); + if (nPos != PAGE_NOT_FOUND) + return mpImpl->mpItemList[nPos]->maAuxiliaryText; + return OUString(); +} + +void TabBar::SetAuxiliaryText(sal_uInt16 nPageId, const OUString& rText ) +{ + sal_uInt16 nPos = GetPagePos(nPageId); + if (nPos != PAGE_NOT_FOUND) + { + mpImpl->mpItemList[nPos]->maAuxiliaryText = rText; + // no redraw bar, no CallEventListener, internal use in LayerTabBar + } +} + +OUString TabBar::GetHelpText(sal_uInt16 nPageId) const +{ + sal_uInt16 nPos = GetPagePos(nPageId); + if (nPos != PAGE_NOT_FOUND) + { + auto& pItem = mpImpl->mpItemList[nPos]; + if (pItem->maHelpText.isEmpty() && !pItem->maHelpId.isEmpty()) + { + Help* pHelp = Application::GetHelp(); + if (pHelp) + pItem->maHelpText = pHelp->GetHelpText(OStringToOUString(pItem->maHelpId, RTL_TEXTENCODING_UTF8), this); + } + + return pItem->maHelpText; + } + return OUString(); +} + +bool TabBar::StartDrag(const CommandEvent& rCEvt, vcl::Region& rRegion) +{ + if (!(mnWinStyle & WB_DRAG) || (rCEvt.GetCommand() != CommandEventId::StartDrag)) + return false; + + // Check if the clicked page was selected. If this is not the case + // set it as actual entry. We check for this only at a mouse action + // if Drag and Drop can be triggered from the keyboard. + // We only do this, if Select() was not triggered, as the Select() + // could have scrolled the area + if (rCEvt.IsMouseEvent() && !mbInSelect) + { + sal_uInt16 nSelId = GetPageId(rCEvt.GetMousePosPixel()); + + // do not start dragging if no entry was clicked + if (!nSelId) + return false; + + // check if page was selected. If not set it as actual + // page and call Select() + if (!IsPageSelected(nSelId)) + { + if (ImplDeactivatePage()) + { + SetCurPageId(nSelId); + PaintImmediately(); + ImplActivatePage(); + ImplSelect(); + } + else + return false; + } + } + mbInSelect = false; + + vcl::Region aRegion; + + // assign region + rRegion = aRegion; + + return true; +} + +sal_uInt16 TabBar::ShowDropPos(const Point& rPos) +{ + sal_uInt16 nDropId; + sal_uInt16 nNewDropPos; + sal_uInt16 nItemCount = mpImpl->getItemSize(); + sal_Int16 nScroll = 0; + + if (rPos.X() > mnLastOffX-TABBAR_DRAG_SCROLLOFF) + { + auto& pItem = mpImpl->mpItemList[mpImpl->mpItemList.size() - 1]; + if (!pItem->maRect.IsEmpty() && (rPos.X() > pItem->maRect.Right())) + nNewDropPos = mpImpl->getItemSize(); + else + { + nNewDropPos = mnFirstPos + 1; + nScroll = 1; + } + } + else if ((rPos.X() <= mnOffX) || + (!mnOffX && (rPos.X() <= TABBAR_DRAG_SCROLLOFF))) + { + if (mnFirstPos) + { + nNewDropPos = mnFirstPos; + nScroll = -1; + } + else + nNewDropPos = 0; + } + else + { + nDropId = GetPageId(rPos); + if (nDropId) + { + nNewDropPos = GetPagePos(nDropId); + if (mnFirstPos && (nNewDropPos == mnFirstPos - 1)) + nScroll = -1; + } + else + nNewDropPos = nItemCount; + } + + if (mbDropPos && (nNewDropPos == mnDropPos) && !nScroll) + return mnDropPos; + + if (mbDropPos) + HideDropPos(); + mbDropPos = true; + mnDropPos = nNewDropPos; + + if (nScroll) + { + sal_uInt16 nOldFirstPos = mnFirstPos; + SetFirstPageId(GetPageId(mnFirstPos + nScroll)); + + // draw immediately, as Paint not possible during Drag and Drop + if (nOldFirstPos != mnFirstPos) + { + tools::Rectangle aRect(mnOffX, 0, mnLastOffX, maWinSize.Height()); + SetFillColor(GetBackground().GetColor()); + DrawRect(aRect); + Invalidate(aRect); + } + } + + // draw drop position arrows + Color aBlackColor(COL_BLACK); + long nX; + long nY = (maWinSize.Height() / 2) - 1; + sal_uInt16 nCurPos = GetPagePos(mnCurPageId); + + sal_Int32 nTriangleWidth = 3 * GetDPIScaleFactor(); + + if (mnDropPos < nItemCount) + { + SetLineColor(aBlackColor); + SetFillColor(aBlackColor); + + auto& pItem = mpImpl->mpItemList[mnDropPos]; + nX = pItem->maRect.Left(); + if ( mnDropPos == nCurPos ) + nX--; + else + nX++; + + if (!pItem->IsDefaultTabBgColor() && !pItem->mbSelect) + { + SetLineColor(pItem->maTabTextColor); + SetFillColor(pItem->maTabTextColor); + } + + tools::Polygon aPoly(3); + aPoly.SetPoint(Point(nX, nY), 0); + aPoly.SetPoint(Point(nX + nTriangleWidth, nY - nTriangleWidth), 1); + aPoly.SetPoint(Point(nX + nTriangleWidth, nY + nTriangleWidth), 2); + DrawPolygon(aPoly); + } + if (mnDropPos > 0 && mnDropPos < nItemCount + 1) + { + SetLineColor(aBlackColor); + SetFillColor(aBlackColor); + + auto& pItem = mpImpl->mpItemList[mnDropPos - 1]; + nX = pItem->maRect.Right(); + if (mnDropPos == nCurPos) + nX++; + if (!pItem->IsDefaultTabBgColor() && !pItem->mbSelect) + { + SetLineColor(pItem->maTabTextColor); + SetFillColor(pItem->maTabTextColor); + } + tools::Polygon aPoly(3); + aPoly.SetPoint(Point(nX, nY), 0); + aPoly.SetPoint(Point(nX - nTriangleWidth, nY - nTriangleWidth), 1); + aPoly.SetPoint(Point(nX - nTriangleWidth, nY + nTriangleWidth), 2); + DrawPolygon(aPoly); + } + + return mnDropPos; +} + +void TabBar::HideDropPos() +{ + if (!mbDropPos) + return; + + long nX; + long nY1 = (maWinSize.Height() / 2) - 3; + long nY2 = nY1 + 5; + sal_uInt16 nItemCount = mpImpl->getItemSize(); + + if (mnDropPos < nItemCount) + { + auto& pItem = mpImpl->mpItemList[mnDropPos]; + nX = pItem->maRect.Left(); + // immediately call Paint, as it is not possible during drag and drop + tools::Rectangle aRect( nX-1, nY1, nX+3, nY2 ); + vcl::Region aRegion( aRect ); + SetClipRegion( aRegion ); + Invalidate(aRect); + SetClipRegion(); + } + if (mnDropPos > 0 && mnDropPos < nItemCount + 1) + { + auto& pItem = mpImpl->mpItemList[mnDropPos - 1]; + nX = pItem->maRect.Right(); + // immediately call Paint, as it is not possible during drag and drop + tools::Rectangle aRect(nX - 2, nY1, nX + 1, nY2); + vcl::Region aRegion(aRect); + SetClipRegion(aRegion); + Invalidate(aRect); + SetClipRegion(); + } + + mbDropPos = false; + mnDropPos = 0; +} + +void TabBar::SwitchPage(const Point& rPos) +{ + sal_uInt16 nSwitchId = GetPageId(rPos); + if (!nSwitchId) + EndSwitchPage(); + else + { + if (nSwitchId != mnSwitchId) + { + mnSwitchId = nSwitchId; + mnSwitchTime = tools::Time::GetSystemTicks(); + } + else + { + // change only after 500 ms + if (mnSwitchId != GetCurPageId()) + { + if (tools::Time::GetSystemTicks() > mnSwitchTime + 500) + { + if (ImplDeactivatePage()) + { + SetCurPageId( mnSwitchId ); + PaintImmediately(); + ImplActivatePage(); + ImplSelect(); + } + } + } + } + } +} + +void TabBar::EndSwitchPage() +{ + mnSwitchTime = 0; + mnSwitchId = 0; +} + +void TabBar::SetStyle(WinBits nStyle) +{ + mnWinStyle = nStyle; + ImplInitControls(); + // order possible controls + if (IsReallyVisible() && IsUpdateMode()) + Resize(); +} + +Size TabBar::CalcWindowSizePixel() const +{ + long nWidth = 0; + + if (!mpImpl->mpItemList.empty()) + { + const_cast<TabBar*>(this)->ImplCalcWidth(); + for (const auto& pItem : mpImpl->mpItemList) + { + nWidth += pItem->mnWidth; + } + } + + return Size(nWidth, GetSettings().GetStyleSettings().GetScrollBarSize()); +} + +tools::Rectangle TabBar::GetPageArea() const +{ + return tools::Rectangle(Point(mnOffX, mnOffY), + Size(mnLastOffX - mnOffX + 1, GetSizePixel().Height() - mnOffY)); +} + +css::uno::Reference<css::accessibility::XAccessible> TabBar::CreateAccessible() +{ + return mpImpl->maAccessibleFactory.getFactory().createAccessibleTabBar(*this); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/control/toolbarmenu.cxx b/svtools/source/control/toolbarmenu.cxx new file mode 100644 index 000000000..c96dba998 --- /dev/null +++ b/svtools/source/control/toolbarmenu.cxx @@ -0,0 +1,267 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <memory> +#include <comphelper/processfactory.hxx> +#include <osl/diagnose.h> + +#include <vcl/taskpanelist.hxx> +#include <vcl/settings.hxx> +#include <vcl/commandevent.hxx> +#include <vcl/event.hxx> +#include <vcl/svapp.hxx> + +#include <svtools/framestatuslistener.hxx> +#include <svtools/valueset.hxx> +#include <svtools/toolbarmenu.hxx> + +using namespace ::com::sun::star::uno; +using namespace ::com::sun::star::lang; +using namespace ::com::sun::star::frame; +using namespace ::com::sun::star::accessibility; + +namespace svtools { + +static vcl::Window* GetTopMostParentSystemWindow( vcl::Window* pWindow ) +{ + OSL_ASSERT( pWindow ); + if ( pWindow ) + { + // ->manually search topmost system window + // required because their might be another system window between this and the top window + pWindow = pWindow->GetParent(); + SystemWindow* pTopMostSysWin = nullptr; + while ( pWindow ) + { + if ( pWindow->IsSystemWindow() ) + pTopMostSysWin = static_cast<SystemWindow*>(pWindow); + pWindow = pWindow->GetParent(); + } + pWindow = pTopMostSysWin; + OSL_ASSERT( pWindow ); + return pWindow; + } + + return nullptr; +} + +class ToolbarPopupStatusListener : public svt::FrameStatusListener +{ +public: + ToolbarPopupStatusListener( const css::uno::Reference< css::frame::XFrame >& xFrame, + ToolbarPopupBase& rToolbarPopup ); + + virtual void SAL_CALL dispose() override; + virtual void SAL_CALL statusChanged( const css::frame::FeatureStateEvent& Event ) override; + + ToolbarPopupBase* mpPopup; +}; + + +ToolbarPopupStatusListener::ToolbarPopupStatusListener( + const css::uno::Reference< css::frame::XFrame >& xFrame, + ToolbarPopupBase& rToolbarPopup ) +: svt::FrameStatusListener( ::comphelper::getProcessComponentContext(), xFrame ) +, mpPopup( &rToolbarPopup ) +{ +} + + +void SAL_CALL ToolbarPopupStatusListener::dispose() +{ + mpPopup = nullptr; + svt::FrameStatusListener::dispose(); +} + + +void SAL_CALL ToolbarPopupStatusListener::statusChanged( const css::frame::FeatureStateEvent& Event ) +{ + if( mpPopup ) + mpPopup->statusChanged( Event ); +} + +ToolbarPopupBase::ToolbarPopupBase(const css::uno::Reference<css::frame::XFrame>& rFrame) + : mxFrame(rFrame) +{ +} + +ToolbarPopupBase::~ToolbarPopupBase() +{ + if (mxStatusListener.is()) + { + mxStatusListener->dispose(); + mxStatusListener.clear(); + } +} + +ToolbarPopup::ToolbarPopup( const css::uno::Reference<css::frame::XFrame>& rFrame, vcl::Window* pParentWindow, + const OString& rID, const OUString& rUIXMLDescription ) + : DockingWindow(pParentWindow, rID, rUIXMLDescription, rFrame) + , ToolbarPopupBase(rFrame) +{ + init(); +} + +void ToolbarPopup::init() +{ + vcl::Window* pWindow = GetTopMostParentSystemWindow( this ); + if ( pWindow ) + static_cast<SystemWindow*>(pWindow)->GetTaskPaneList()->AddWindow( this ); +} + +ToolbarPopup::~ToolbarPopup() +{ + disposeOnce(); +} + +void ToolbarPopup::dispose() +{ + vcl::Window* pWindow = GetTopMostParentSystemWindow( this ); + if ( pWindow ) + static_cast<SystemWindow*>(pWindow)->GetTaskPaneList()->RemoveWindow( this ); + + if ( mxStatusListener.is() ) + { + mxStatusListener->dispose(); + mxStatusListener.clear(); + } + + mxFrame.clear(); + DockingWindow::dispose(); +} + +void ToolbarPopupBase::AddStatusListener( const OUString& rCommandURL ) +{ + if( !mxStatusListener.is() ) + mxStatusListener.set( new ToolbarPopupStatusListener( mxFrame, *this ) ); + + mxStatusListener->addStatusListener( rCommandURL ); +} + +void ToolbarPopupBase::statusChanged( const css::frame::FeatureStateEvent& /*Event*/ ) +{ +} + +void ToolbarPopup::EndPopupMode() +{ + GetDockingManager()->EndPopupMode(this); +} + + +} + +WeldToolbarPopup::WeldToolbarPopup(const css::uno::Reference<css::frame::XFrame>& rFrame, + weld::Widget* pParent, const OUString& rUIFile, + const OString& rId) + : ToolbarPopupBase(rFrame) + , m_xBuilder(Application::CreateBuilder(pParent, rUIFile)) + , m_xTopLevel(m_xBuilder->weld_container(rId)) + , m_xContainer(m_xBuilder->weld_container("container")) +{ + m_xTopLevel->connect_focus_in(LINK(this, WeldToolbarPopup, FocusHdl)); +} + +WeldToolbarPopup::~WeldToolbarPopup() +{ +} + +IMPL_LINK_NOARG(WeldToolbarPopup, FocusHdl, weld::Widget&, void) +{ + GrabFocus(); +} + +ToolbarPopupContainer::ToolbarPopupContainer(weld::Widget* pParent) + : m_xBuilder(Application::CreateBuilder(pParent, "svx/ui/toolbarpopover.ui")) + , m_xTopLevel(m_xBuilder->weld_container("ToolbarPopover")) + , m_xContainer(m_xBuilder->weld_container("container")) +{ + m_xTopLevel->connect_focus_in(LINK(this, ToolbarPopupContainer, FocusHdl)); +} + +void ToolbarPopupContainer::setPopover(std::unique_ptr<WeldToolbarPopup> xPopup) +{ + m_xPopup = std::move(xPopup); + // move the WeldToolbarPopup contents into this toolbar so on-demand contents can appear inside a preexisting gtk popover + // because the arrow for the popover is only enabled if there's a popover set + m_xPopup->getTopLevel()->move(m_xPopup->getContainer(), m_xContainer.get()); + m_xPopup->GrabFocus(); +} + +void ToolbarPopupContainer::unsetPopover() +{ + if (!m_xPopup) + return; + m_xContainer->move(m_xPopup->getContainer(), m_xPopup->getTopLevel()); + m_xPopup.reset(); +} + +ToolbarPopupContainer::~ToolbarPopupContainer() +{ + unsetPopover(); +} + +IMPL_LINK_NOARG(ToolbarPopupContainer, FocusHdl, weld::Widget&, void) +{ + if (m_xPopup) + m_xPopup->GrabFocus(); +} + +InterimToolbarPopup::InterimToolbarPopup(const css::uno::Reference<css::frame::XFrame>& rFrame, vcl::Window* pParent, + std::unique_ptr<WeldToolbarPopup> xPopup, bool bTearable) + : ToolbarPopup(rFrame, pParent, + !bTearable ? OString("InterimDockParent") : OString("InterimTearableParent"), + !bTearable ? OUString("svx/ui/interimdockparent.ui") : OUString("svx/ui/interimtearableparent.ui")) + , m_xBox(get("box")) + , m_xBuilder(Application::CreateInterimBuilder(m_xBox.get(), "svx/ui/interimparent.ui")) + , m_xContainer(m_xBuilder->weld_container("container")) + , m_xPopup(std::move(xPopup)) +{ + // move the WeldToolbarPopup contents into this interim toolbar so welded contents can appear as a dropdown in an unwelded toolbar + m_xPopup->getTopLevel()->move(m_xPopup->getContainer(), m_xContainer.get()); +} + +void InterimToolbarPopup::GetFocus() +{ + ToolbarPopup::GetFocus(); + m_xPopup->GrabFocus(); +} + +void InterimToolbarPopup::dispose() +{ + // if we have focus when disposed, pick the document window as destination + // for focus rather than let it go to an arbitrary windows + if (HasFocus()) + { + if (auto xWindow = mxFrame->getContainerWindow()) + xWindow->setFocus(); + } + // move the contents back where it belongs + m_xContainer->move(m_xPopup->getContainer(), m_xPopup->getTopLevel()); + m_xPopup.reset(); + m_xContainer.reset(); + m_xBox.clear(); + ToolbarPopup::dispose(); +} + +InterimToolbarPopup::~InterimToolbarPopup() +{ + disposeOnce(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/control/valueacc.cxx b/svtools/source/control/valueacc.cxx new file mode 100644 index 000000000..c43e8d070 --- /dev/null +++ b/svtools/source/control/valueacc.cxx @@ -0,0 +1,1020 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <unotools/accessiblestatesethelper.hxx> +#include <vcl/svapp.hxx> +#include <vcl/settings.hxx> +#include <sal/log.hxx> +#include <tools/debug.hxx> +#include <tools/diagnose_ex.h> +#include <svtools/valueset.hxx> +#include "valueimp.hxx" +#include <comphelper/servicehelper.hxx> +#include <com/sun/star/accessibility/AccessibleEventId.hpp> +#include <com/sun/star/accessibility/AccessibleRole.hpp> +#include <com/sun/star/accessibility/AccessibleStateType.hpp> +#include <com/sun/star/accessibility/AccessibleRelationType.hpp> +#include <com/sun/star/lang/IndexOutOfBoundsException.hpp> +#include <unotools/accessiblerelationsethelper.hxx> + +using namespace ::com::sun::star; + + +ValueSetItem::ValueSetItem( ValueSet& rParent ) + : mrParent(rParent) + , mnId(0) + , meType(VALUESETITEM_NONE) + , mbVisible(true) + , mpData(nullptr) + , mxAcc() +{ +} + + +ValueSetItem::~ValueSetItem() +{ + if( mxAcc.is() ) + { + mxAcc->ParentDestroyed(); + } +} + +uno::Reference< accessibility::XAccessible > ValueSetItem::GetAccessible( bool bIsTransientChildrenDisabled ) +{ + if( !mxAcc.is() ) + mxAcc = new ValueItemAcc( this, bIsTransientChildrenDisabled ); + + return mxAcc.get(); +} + +ValueItemAcc::ValueItemAcc( ValueSetItem* pParent, bool bIsTransientChildrenDisabled ) : + mpParent( pParent ), + mbIsTransientChildrenDisabled( bIsTransientChildrenDisabled ) +{ +} + +ValueItemAcc::~ValueItemAcc() +{ +} + +void ValueItemAcc::ParentDestroyed() +{ + const ::osl::MutexGuard aGuard( maMutex ); + mpParent = nullptr; +} + +namespace +{ + class theValueItemAccUnoTunnelId : public rtl::Static< UnoTunnelIdInit, theValueItemAccUnoTunnelId > {}; +} + +const uno::Sequence< sal_Int8 >& ValueItemAcc::getUnoTunnelId() +{ + return theValueItemAccUnoTunnelId::get().getSeq(); +} + + +ValueItemAcc* ValueItemAcc::getImplementation( const uno::Reference< uno::XInterface >& rxData ) + throw() +{ + try + { + return comphelper::getUnoTunnelImplementation<ValueItemAcc>(rxData); + } + catch(const css::uno::Exception&) + { + return nullptr; + } +} + + +uno::Reference< accessibility::XAccessibleContext > SAL_CALL ValueItemAcc::getAccessibleContext() +{ + return this; +} + + +sal_Int32 SAL_CALL ValueItemAcc::getAccessibleChildCount() +{ + return 0; +} + + +uno::Reference< accessibility::XAccessible > SAL_CALL ValueItemAcc::getAccessibleChild( sal_Int32 ) +{ + throw lang::IndexOutOfBoundsException(); +} + + +uno::Reference< accessibility::XAccessible > SAL_CALL ValueItemAcc::getAccessibleParent() +{ + const SolarMutexGuard aSolarGuard; + uno::Reference< accessibility::XAccessible > xRet; + + if( mpParent ) + xRet = mpParent->mrParent.mxAccessible; + + return xRet; +} + + +sal_Int32 SAL_CALL ValueItemAcc::getAccessibleIndexInParent() +{ + const SolarMutexGuard aSolarGuard; + // The index defaults to -1 to indicate the child does not belong to its + // parent. + sal_Int32 nIndexInParent = -1; + + if( mpParent ) + { + bool bDone = false; + + sal_uInt16 nCount = mpParent->mrParent.ImplGetVisibleItemCount(); + ValueSetItem* pItem; + for (sal_uInt16 i=0; i<nCount && !bDone; i++) + { + // Guard the retrieval of the i-th child with a try/catch block + // just in case the number of children changes in the meantime. + try + { + pItem = mpParent->mrParent.ImplGetItem(i); + } + catch (const lang::IndexOutOfBoundsException&) + { + pItem = nullptr; + } + + // Do not create an accessible object for the test. + if (pItem != nullptr && pItem->mxAcc.is()) + if (pItem->GetAccessible( mbIsTransientChildrenDisabled ).get() == this ) + { + nIndexInParent = i; + bDone = true; + } + } + } + + //if this valueset contain a none field(common value is default), then we should increase the real index and set the noitem index value equal 0. + if ( mpParent && ( (mpParent->mrParent.GetStyle() & WB_NONEFIELD) != 0 ) ) + { + ValueSetItem* pFirstItem = mpParent->mrParent.ImplGetItem (VALUESET_ITEM_NONEITEM); + if( pFirstItem && pFirstItem ->GetAccessible(mbIsTransientChildrenDisabled).get() == this ) + nIndexInParent = 0; + else + nIndexInParent++; + } + return nIndexInParent; +} + + +sal_Int16 SAL_CALL ValueItemAcc::getAccessibleRole() +{ + return accessibility::AccessibleRole::LIST_ITEM; +} + + +OUString SAL_CALL ValueItemAcc::getAccessibleDescription() +{ + return OUString(); +} + + +OUString SAL_CALL ValueItemAcc::getAccessibleName() +{ + const SolarMutexGuard aSolarGuard; + + if( mpParent ) + { + if (mpParent->maText.isEmpty()) + return "Item " + OUString::number(static_cast<sal_Int32>(mpParent->mnId)); + else + return mpParent->maText; + } + + return OUString(); +} + + +uno::Reference< accessibility::XAccessibleRelationSet > SAL_CALL ValueItemAcc::getAccessibleRelationSet() +{ + return uno::Reference< accessibility::XAccessibleRelationSet >(); +} + + +uno::Reference< accessibility::XAccessibleStateSet > SAL_CALL ValueItemAcc::getAccessibleStateSet() +{ + const SolarMutexGuard aSolarGuard; + ::utl::AccessibleStateSetHelper* pStateSet = new ::utl::AccessibleStateSetHelper; + + if( mpParent ) + { + pStateSet->AddState (accessibility::AccessibleStateType::ENABLED); + pStateSet->AddState (accessibility::AccessibleStateType::SENSITIVE); + pStateSet->AddState (accessibility::AccessibleStateType::SHOWING); + pStateSet->AddState (accessibility::AccessibleStateType::VISIBLE); + if ( !mbIsTransientChildrenDisabled ) + pStateSet->AddState (accessibility::AccessibleStateType::TRANSIENT); + + // SELECTABLE + pStateSet->AddState( accessibility::AccessibleStateType::SELECTABLE ); + // pStateSet->AddState( accessibility::AccessibleStateType::FOCUSABLE ); + + // SELECTED + if( mpParent->mrParent.GetSelectedItemId() == mpParent->mnId ) + { + pStateSet->AddState( accessibility::AccessibleStateType::SELECTED ); + // pStateSet->AddState( accessibility::AccessibleStateType::FOCUSED ); + } + } + + return pStateSet; +} + + +lang::Locale SAL_CALL ValueItemAcc::getLocale() +{ + const SolarMutexGuard aSolarGuard; + uno::Reference< accessibility::XAccessible > xParent( getAccessibleParent() ); + lang::Locale aRet( "", "", "" ); + + if( xParent.is() ) + { + uno::Reference< accessibility::XAccessibleContext > xParentContext( xParent->getAccessibleContext() ); + + if( xParentContext.is() ) + aRet = xParentContext->getLocale(); + } + + return aRet; +} + + +void SAL_CALL ValueItemAcc::addAccessibleEventListener( const uno::Reference< accessibility::XAccessibleEventListener >& rxListener ) +{ + const ::osl::MutexGuard aGuard( maMutex ); + + if( !rxListener.is() ) + return; + + bool bFound = false; + + for (auto const& eventListener : mxEventListeners) + { + if(eventListener == rxListener) + { + bFound = true; + break; + } + } + + if (!bFound) + mxEventListeners.push_back( rxListener ); +} + + +void SAL_CALL ValueItemAcc::removeAccessibleEventListener( const uno::Reference< accessibility::XAccessibleEventListener >& rxListener ) +{ + const ::osl::MutexGuard aGuard( maMutex ); + + if( rxListener.is() ) + { + ::std::vector< uno::Reference< accessibility::XAccessibleEventListener > >::iterator aIter = + std::find(mxEventListeners.begin(), mxEventListeners.end(), rxListener); + + if (aIter != mxEventListeners.end()) + mxEventListeners.erase(aIter); + } +} + + +sal_Bool SAL_CALL ValueItemAcc::containsPoint( const awt::Point& aPoint ) +{ + const awt::Rectangle aRect( getBounds() ); + const Point aSize( aRect.Width, aRect.Height ); + const Point aNullPoint, aTestPoint( aPoint.X, aPoint.Y ); + + return tools::Rectangle( aNullPoint, aSize ).IsInside( aTestPoint ); +} + +uno::Reference< accessibility::XAccessible > SAL_CALL ValueItemAcc::getAccessibleAtPoint( const awt::Point& ) +{ + uno::Reference< accessibility::XAccessible > xRet; + return xRet; +} + +awt::Rectangle SAL_CALL ValueItemAcc::getBounds() +{ + const SolarMutexGuard aSolarGuard; + awt::Rectangle aRet; + + if( mpParent ) + { + tools::Rectangle aRect( mpParent->mrParent.GetItemRect(mpParent->mnId) ); + tools::Rectangle aParentRect( Point(), mpParent->mrParent.GetOutputSizePixel() ); + + aRect.Intersection( aParentRect ); + + aRet.X = aRect.Left(); + aRet.Y = aRect.Top(); + aRet.Width = aRect.GetWidth(); + aRet.Height = aRect.GetHeight(); + } + + return aRet; +} + +awt::Point SAL_CALL ValueItemAcc::getLocation() +{ + const awt::Rectangle aRect( getBounds() ); + awt::Point aRet; + + aRet.X = aRect.X; + aRet.Y = aRect.Y; + + return aRet; +} + +awt::Point SAL_CALL ValueItemAcc::getLocationOnScreen() +{ + const SolarMutexGuard aSolarGuard; + awt::Point aRet; + + if( mpParent ) + { + const Point aPos = mpParent->mrParent.GetItemRect(mpParent->mnId).TopLeft(); + const Point aScreenPos( mpParent->mrParent.GetDrawingArea()->get_accessible_location() ); + + aRet.X = aPos.X() + aScreenPos.X(); + aRet.Y = aPos.Y() + aScreenPos.Y(); + } + + return aRet; +} + +awt::Size SAL_CALL ValueItemAcc::getSize() +{ + const awt::Rectangle aRect( getBounds() ); + awt::Size aRet; + + aRet.Width = aRect.Width; + aRet.Height = aRect.Height; + + return aRet; +} + +void SAL_CALL ValueItemAcc::grabFocus() +{ + // nothing to do +} + +sal_Int32 SAL_CALL ValueItemAcc::getForeground( ) +{ + Color nColor = Application::GetSettings().GetStyleSettings().GetWindowTextColor(); + return static_cast<sal_Int32>(nColor); +} + +sal_Int32 SAL_CALL ValueItemAcc::getBackground( ) +{ + Color nColor; + if (mpParent && mpParent->meType == VALUESETITEM_COLOR) + nColor = mpParent->maColor; + else + nColor = Application::GetSettings().GetStyleSettings().GetWindowColor(); + return static_cast<sal_Int32>(nColor); +} + +sal_Int64 SAL_CALL ValueItemAcc::getSomething( const uno::Sequence< sal_Int8 >& rId ) +{ + sal_Int64 nRet; + + if( isUnoTunnelId<ValueItemAcc>(rId) ) + nRet = reinterpret_cast< sal_Int64 >( this ); + else + nRet = 0; + + return nRet; +} + +void ValueItemAcc::FireAccessibleEvent( short nEventId, const uno::Any& rOldValue, const uno::Any& rNewValue ) +{ + if( !nEventId ) + return; + + ::std::vector< uno::Reference< accessibility::XAccessibleEventListener > > aTmpListeners( mxEventListeners ); + accessibility::AccessibleEventObject aEvtObject; + + aEvtObject.EventId = nEventId; + aEvtObject.Source = static_cast<uno::XWeak*>(this); + aEvtObject.NewValue = rNewValue; + aEvtObject.OldValue = rOldValue; + + for (auto const& tmpListener : aTmpListeners) + { + tmpListener->notifyEvent( aEvtObject ); + } +} + +ValueSetAcc::ValueSetAcc( ValueSet* pParent ) : + ValueSetAccComponentBase (m_aMutex), + mpParent( pParent ), + mbIsFocused(false) +{ +} + + +ValueSetAcc::~ValueSetAcc() +{ +} + + +void ValueSetAcc::FireAccessibleEvent( short nEventId, const uno::Any& rOldValue, const uno::Any& rNewValue ) +{ + if( !nEventId ) + return; + + ::std::vector< uno::Reference< accessibility::XAccessibleEventListener > > aTmpListeners( mxEventListeners ); + accessibility::AccessibleEventObject aEvtObject; + + aEvtObject.EventId = nEventId; + aEvtObject.Source = static_cast<uno::XWeak*>(this); + aEvtObject.NewValue = rNewValue; + aEvtObject.OldValue = rOldValue; + + for (auto const& tmpListener : aTmpListeners) + { + try + { + tmpListener->notifyEvent( aEvtObject ); + } + catch(const uno::Exception&) + { + } + } +} + +namespace +{ + class theValueSetAccUnoTunnelId : public rtl::Static< UnoTunnelIdInit, theValueSetAccUnoTunnelId > {}; +} + +const uno::Sequence< sal_Int8 >& ValueSetAcc::getUnoTunnelId() +{ + return theValueSetAccUnoTunnelId::get().getSeq(); +} + + +ValueSetAcc* ValueSetAcc::getImplementation( const uno::Reference< uno::XInterface >& rxData ) + throw() +{ + try + { + return comphelper::getUnoTunnelImplementation<ValueSetAcc>(rxData); + } + catch(const css::uno::Exception&) + { + return nullptr; + } +} + + +void ValueSetAcc::GetFocus() +{ + mbIsFocused = true; + + // Broadcast the state change. + css::uno::Any aOldState, aNewState; + aNewState <<= css::accessibility::AccessibleStateType::FOCUSED; + FireAccessibleEvent( + css::accessibility::AccessibleEventId::STATE_CHANGED, + aOldState, aNewState); +} + + +void ValueSetAcc::LoseFocus() +{ + mbIsFocused = false; + + // Broadcast the state change. + css::uno::Any aOldState, aNewState; + aOldState <<= css::accessibility::AccessibleStateType::FOCUSED; + FireAccessibleEvent( + css::accessibility::AccessibleEventId::STATE_CHANGED, + aOldState, aNewState); +} + + +uno::Reference< accessibility::XAccessibleContext > SAL_CALL ValueSetAcc::getAccessibleContext() +{ + ThrowIfDisposed(); + return this; +} + + +sal_Int32 SAL_CALL ValueSetAcc::getAccessibleChildCount() +{ + const SolarMutexGuard aSolarGuard; + ThrowIfDisposed(); + + sal_Int32 nCount = mpParent->ImplGetVisibleItemCount(); + if (HasNoneField()) + nCount += 1; + return nCount; +} + + +uno::Reference< accessibility::XAccessible > SAL_CALL ValueSetAcc::getAccessibleChild( sal_Int32 i ) +{ + ThrowIfDisposed(); + const SolarMutexGuard aSolarGuard; + ValueSetItem* pItem = getItem (sal::static_int_cast< sal_uInt16 >(i)); + + if( !pItem ) + throw lang::IndexOutOfBoundsException(); + + uno::Reference< accessibility::XAccessible > xRet = pItem->GetAccessible( false/*bIsTransientChildrenDisabled*/ ); + return xRet; +} + +uno::Reference< accessibility::XAccessible > SAL_CALL ValueSetAcc::getAccessibleParent() +{ + ThrowIfDisposed(); + const SolarMutexGuard aSolarGuard; + return mpParent->GetDrawingArea()->get_accessible_parent(); +} + +sal_Int32 SAL_CALL ValueSetAcc::getAccessibleIndexInParent() +{ + ThrowIfDisposed(); + const SolarMutexGuard aSolarGuard; + + // -1 for child not found/no parent (according to specification) + sal_Int32 nRet = -1; + + uno::Reference<accessibility::XAccessible> xParent(getAccessibleParent()); + if (!xParent) + return nRet; + + try + { + uno::Reference<accessibility::XAccessibleContext> xParentContext(xParent->getAccessibleContext()); + + // iterate over parent's children and search for this object + if ( xParentContext.is() ) + { + sal_Int32 nChildCount = xParentContext->getAccessibleChildCount(); + for ( sal_Int32 nChild = 0; ( nChild < nChildCount ) && ( -1 == nRet ); ++nChild ) + { + uno::Reference<XAccessible> xChild(xParentContext->getAccessibleChild(nChild)); + if ( xChild.get() == this ) + nRet = nChild; + } + } + } + catch (const uno::Exception&) + { + TOOLS_WARN_EXCEPTION( "svtools", "OAccessibleContextHelper::getAccessibleIndexInParent" ); + } + + return nRet; +} + +sal_Int16 SAL_CALL ValueSetAcc::getAccessibleRole() +{ + ThrowIfDisposed(); + return accessibility::AccessibleRole::LIST; +} + + +OUString SAL_CALL ValueSetAcc::getAccessibleDescription() +{ + ThrowIfDisposed(); + const SolarMutexGuard aSolarGuard; + OUString aRet; + + if (mpParent) + { + aRet = mpParent->GetAccessibleDescription(); + } + + return aRet; +} + + +OUString SAL_CALL ValueSetAcc::getAccessibleName() +{ + ThrowIfDisposed(); + const SolarMutexGuard aSolarGuard; + OUString aRet; + + if (mpParent) + { + aRet = mpParent->GetAccessibleName(); + } + + return aRet; +} + +uno::Reference< accessibility::XAccessibleRelationSet > SAL_CALL ValueSetAcc::getAccessibleRelationSet() +{ + ThrowIfDisposed(); + SolarMutexGuard g; + return mpParent->GetDrawingArea()->get_accessible_relation_set(); +} + +uno::Reference< accessibility::XAccessibleStateSet > SAL_CALL ValueSetAcc::getAccessibleStateSet() +{ + ThrowIfDisposed(); + ::utl::AccessibleStateSetHelper* pStateSet = new ::utl::AccessibleStateSetHelper(); + + // Set some states. + pStateSet->AddState (accessibility::AccessibleStateType::ENABLED); + pStateSet->AddState (accessibility::AccessibleStateType::SENSITIVE); + pStateSet->AddState (accessibility::AccessibleStateType::SHOWING); + pStateSet->AddState (accessibility::AccessibleStateType::VISIBLE); + pStateSet->AddState (accessibility::AccessibleStateType::MANAGES_DESCENDANTS); + pStateSet->AddState (accessibility::AccessibleStateType::FOCUSABLE); + if (mbIsFocused) + pStateSet->AddState (accessibility::AccessibleStateType::FOCUSED); + + return pStateSet; +} + + +lang::Locale SAL_CALL ValueSetAcc::getLocale() +{ + ThrowIfDisposed(); + const SolarMutexGuard aSolarGuard; + uno::Reference< accessibility::XAccessible > xParent( getAccessibleParent() ); + lang::Locale aRet( "", "", "" ); + + if( xParent.is() ) + { + uno::Reference< accessibility::XAccessibleContext > xParentContext( xParent->getAccessibleContext() ); + + if( xParentContext.is() ) + aRet = xParentContext->getLocale (); + } + + return aRet; +} + + +void SAL_CALL ValueSetAcc::addAccessibleEventListener( const uno::Reference< accessibility::XAccessibleEventListener >& rxListener ) +{ + ThrowIfDisposed(); + ::osl::MutexGuard aGuard (m_aMutex); + + if( !rxListener.is() ) + return; + + bool bFound = false; + + for (auto const& eventListener : mxEventListeners) + { + if(eventListener == rxListener) + { + bFound = true; + break; + } + } + + if (!bFound) + mxEventListeners.push_back( rxListener ); +} + + +void SAL_CALL ValueSetAcc::removeAccessibleEventListener( const uno::Reference< accessibility::XAccessibleEventListener >& rxListener ) +{ + ThrowIfDisposed(); + ::osl::MutexGuard aGuard (m_aMutex); + + if( rxListener.is() ) + { + ::std::vector< uno::Reference< accessibility::XAccessibleEventListener > >::iterator aIter = + std::find(mxEventListeners.begin(), mxEventListeners.end(), rxListener); + + if (aIter != mxEventListeners.end()) + mxEventListeners.erase(aIter); + } +} + + +sal_Bool SAL_CALL ValueSetAcc::containsPoint( const awt::Point& aPoint ) +{ + ThrowIfDisposed(); + const awt::Rectangle aRect( getBounds() ); + const Point aSize( aRect.Width, aRect.Height ); + const Point aNullPoint, aTestPoint( aPoint.X, aPoint.Y ); + + return tools::Rectangle( aNullPoint, aSize ).IsInside( aTestPoint ); +} + + +uno::Reference< accessibility::XAccessible > SAL_CALL ValueSetAcc::getAccessibleAtPoint( const awt::Point& aPoint ) +{ + ThrowIfDisposed(); + const SolarMutexGuard aSolarGuard; + const sal_uInt16 nItemId = mpParent->GetItemId( Point( aPoint.X, aPoint.Y ) ); + uno::Reference< accessibility::XAccessible > xRet; + + if ( nItemId ) + { + const size_t nItemPos = mpParent->GetItemPos( nItemId ); + + if( VALUESET_ITEM_NONEITEM != nItemPos ) + { + ValueSetItem *const pItem = mpParent->mItemList[nItemPos].get(); + xRet = pItem->GetAccessible( false/*bIsTransientChildrenDisabled*/ ); + } + } + + return xRet; +} + + +awt::Rectangle SAL_CALL ValueSetAcc::getBounds() +{ + ThrowIfDisposed(); + const SolarMutexGuard aSolarGuard; + const Point aOutPos; + const Size aOutSize( mpParent->GetOutputSizePixel() ); + awt::Rectangle aRet; + + aRet.X = aOutPos.X(); + aRet.Y = aOutPos.Y(); + aRet.Width = aOutSize.Width(); + aRet.Height = aOutSize.Height(); + + return aRet; +} + +awt::Point SAL_CALL ValueSetAcc::getLocation() +{ + ThrowIfDisposed(); + const awt::Rectangle aRect( getBounds() ); + awt::Point aRet; + + aRet.X = aRect.X; + aRet.Y = aRect.Y; + + return aRet; +} + +awt::Point SAL_CALL ValueSetAcc::getLocationOnScreen() +{ + ThrowIfDisposed(); + const SolarMutexGuard aSolarGuard; + awt::Point aScreenLoc(0, 0); + + uno::Reference<accessibility::XAccessible> xParent(getAccessibleParent()); + if (xParent) + { + uno::Reference<accessibility::XAccessibleContext> xParentContext(xParent->getAccessibleContext()); + uno::Reference<accessibility::XAccessibleComponent> xParentComponent(xParentContext, css::uno::UNO_QUERY); + OSL_ENSURE( xParentComponent.is(), "ValueSetAcc::getLocationOnScreen: no parent component!" ); + if ( xParentComponent.is() ) + { + awt::Point aParentScreenLoc( xParentComponent->getLocationOnScreen() ); + awt::Point aOwnRelativeLoc( getLocation() ); + aScreenLoc.X = aParentScreenLoc.X + aOwnRelativeLoc.X; + aScreenLoc.Y = aParentScreenLoc.Y + aOwnRelativeLoc.Y; + } + } + + return aScreenLoc; +} + +awt::Size SAL_CALL ValueSetAcc::getSize() +{ + ThrowIfDisposed(); + const awt::Rectangle aRect( getBounds() ); + awt::Size aRet; + + aRet.Width = aRect.Width; + aRet.Height = aRect.Height; + + return aRet; +} + +void SAL_CALL ValueSetAcc::grabFocus() +{ + ThrowIfDisposed(); + const SolarMutexGuard aSolarGuard; + mpParent->GrabFocus(); +} + +sal_Int32 SAL_CALL ValueSetAcc::getForeground( ) +{ + ThrowIfDisposed(); + Color nColor = Application::GetSettings().GetStyleSettings().GetWindowTextColor(); + return static_cast<sal_Int32>(nColor); +} + +sal_Int32 SAL_CALL ValueSetAcc::getBackground( ) +{ + ThrowIfDisposed(); + Color nColor = Application::GetSettings().GetStyleSettings().GetWindowColor(); + return static_cast<sal_Int32>(nColor); +} + +void SAL_CALL ValueSetAcc::selectAccessibleChild( sal_Int32 nChildIndex ) +{ + ThrowIfDisposed(); + const SolarMutexGuard aSolarGuard; + ValueSetItem* pItem = getItem (sal::static_int_cast< sal_uInt16 >(nChildIndex)); + + if(pItem == nullptr) + throw lang::IndexOutOfBoundsException(); + + mpParent->SelectItem( pItem->mnId ); +} + + +sal_Bool SAL_CALL ValueSetAcc::isAccessibleChildSelected( sal_Int32 nChildIndex ) +{ + ThrowIfDisposed(); + const SolarMutexGuard aSolarGuard; + ValueSetItem* pItem = getItem (sal::static_int_cast< sal_uInt16 >(nChildIndex)); + + if (pItem == nullptr) + throw lang::IndexOutOfBoundsException(); + + bool bRet = mpParent->IsItemSelected( pItem->mnId ); + return bRet; +} + + +void SAL_CALL ValueSetAcc::clearAccessibleSelection() +{ + ThrowIfDisposed(); + const SolarMutexGuard aSolarGuard; + mpParent->SetNoSelection(); +} + + +void SAL_CALL ValueSetAcc::selectAllAccessibleChildren() +{ + ThrowIfDisposed(); + // unsupported due to single selection only +} + + +sal_Int32 SAL_CALL ValueSetAcc::getSelectedAccessibleChildCount() +{ + ThrowIfDisposed(); + const SolarMutexGuard aSolarGuard; + sal_Int32 nRet = 0; + + for( sal_uInt16 i = 0, nCount = getItemCount(); i < nCount; i++ ) + { + ValueSetItem* pItem = getItem (i); + + if( pItem && mpParent->IsItemSelected( pItem->mnId ) ) + ++nRet; + } + + return nRet; +} + + +uno::Reference< accessibility::XAccessible > SAL_CALL ValueSetAcc::getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex ) +{ + ThrowIfDisposed(); + const SolarMutexGuard aSolarGuard; + uno::Reference< accessibility::XAccessible > xRet; + + for( sal_uInt16 i = 0, nCount = getItemCount(), nSel = 0; ( i < nCount ) && !xRet.is(); i++ ) + { + ValueSetItem* pItem = getItem(i); + + if( pItem && mpParent->IsItemSelected( pItem->mnId ) && ( nSelectedChildIndex == static_cast< sal_Int32 >( nSel++ ) ) ) + xRet = pItem->GetAccessible( false/*bIsTransientChildrenDisabled*/ ); + } + + return xRet; +} + + +void SAL_CALL ValueSetAcc::deselectAccessibleChild( sal_Int32 nChildIndex ) +{ + ThrowIfDisposed(); + const SolarMutexGuard aSolarGuard; + // Because of the single selection we can reset the whole selection when + // the specified child is currently selected. + if (isAccessibleChildSelected(nChildIndex)) + mpParent->SetNoSelection(); +} + + +sal_Int64 SAL_CALL ValueSetAcc::getSomething( const uno::Sequence< sal_Int8 >& rId ) +{ + sal_Int64 nRet; + + if( isUnoTunnelId<ValueSetAcc>(rId) ) + nRet = reinterpret_cast< sal_Int64 >( this ); + else + nRet = 0; + + return nRet; +} + + +void SAL_CALL ValueSetAcc::disposing() +{ + ::std::vector<uno::Reference<accessibility::XAccessibleEventListener> > aListenerListCopy; + + { + // Make a copy of the list and clear the original. + const SolarMutexGuard aSolarGuard; + ::osl::MutexGuard aGuard (m_aMutex); + aListenerListCopy.swap(mxEventListeners); + + // Reset the pointer to the parent. It has to be the one who has + // disposed us because he is dying. + mpParent = nullptr; + } + + // Inform all listeners that this objects is disposing. + lang::EventObject aEvent (static_cast<accessibility::XAccessible*>(this)); + for (auto const& listenerCopy : aListenerListCopy) + { + try + { + listenerCopy->disposing (aEvent); + } + catch(const uno::Exception&) + { + // Ignore exceptions. + } + } +} + + +sal_uInt16 ValueSetAcc::getItemCount() const +{ + sal_uInt16 nCount = mpParent->ImplGetVisibleItemCount(); + // When the None-Item is visible then increase the number of items by + // one. + if (HasNoneField()) + nCount += 1; + return nCount; +} + +ValueSetItem* ValueSetAcc::getItem (sal_uInt16 nIndex) const +{ + ValueSetItem* pItem = nullptr; + + if (HasNoneField()) + { + if (nIndex == 0) + // When present the first item is the then always visible none field. + pItem = mpParent->ImplGetItem (VALUESET_ITEM_NONEITEM); + else + // Shift down the index to compensate for the none field. + nIndex -= 1; + } + if (pItem == nullptr) + pItem = mpParent->ImplGetItem (nIndex); + + return pItem; +} + + +void ValueSetAcc::ThrowIfDisposed() +{ + if (rBHelper.bDisposed || rBHelper.bInDispose) + { + SAL_WARN("svx", "Calling disposed object. Throwing exception:"); + throw lang::DisposedException ( + "object has been already disposed", + static_cast<uno::XWeak*>(this)); + } + else + { + DBG_ASSERT (mpParent!=nullptr, "ValueSetAcc not disposed but mpParent == NULL"); + } +} + +bool ValueSetAcc::HasNoneField() const +{ + assert(mpParent && "ValueSetAcc::HasNoneField called with mpParent==NULL"); + return ((mpParent->GetStyle() & WB_NONEFIELD) != 0); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/control/valueimp.hxx b/svtools/source/control/valueimp.hxx new file mode 100644 index 000000000..5f874acb9 --- /dev/null +++ b/svtools/source/control/valueimp.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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <osl/mutex.hxx> +#include <tools/color.hxx> +#include <vcl/image.hxx> +#include <cppuhelper/implbase.hxx> +#include <cppuhelper/compbase.hxx> +#include <cppuhelper/basemutex.hxx> +#include <com/sun/star/lang/XUnoTunnel.hpp> +#include <com/sun/star/accessibility/XAccessible.hpp> +#include <com/sun/star/accessibility/XAccessibleContext.hpp> +#include <com/sun/star/accessibility/XAccessibleComponent.hpp> +#include <com/sun/star/accessibility/XAccessibleSelection.hpp> +#include <com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp> + +#include <vector> + +#define VALUESET_ITEM_NONEITEM 0xFFFE + +enum ValueSetItemType +{ + VALUESETITEM_NONE, + VALUESETITEM_IMAGE, + VALUESETITEM_IMAGE_AND_TEXT, + VALUESETITEM_COLOR, + VALUESETITEM_USERDRAW +}; + +class ValueItemAcc; +class ValueSet; + +struct ValueSetItem +{ + ValueSet& mrParent; + sal_uInt16 mnId; + sal_uInt8 meType; + bool mbVisible; + Image maImage; + Color maColor; + OUString maText; + void* mpData; + rtl::Reference< ValueItemAcc > mxAcc; + + explicit ValueSetItem( ValueSet& rParent ); + ~ValueSetItem(); + + css::uno::Reference< css::accessibility::XAccessible > + GetAccessible( bool bIsTransientChildrenDisabled ); +}; + +typedef ::cppu::WeakComponentImplHelper< + css::accessibility::XAccessible, + css::accessibility::XAccessibleEventBroadcaster, + css::accessibility::XAccessibleContext, + css::accessibility::XAccessibleComponent, + css::accessibility::XAccessibleSelection, + css::lang::XUnoTunnel > + ValueSetAccComponentBase; + +class ValueSetAcc : + public ::cppu::BaseMutex, + public ValueSetAccComponentBase +{ +public: + + explicit ValueSetAcc(ValueSet* pParent); + virtual ~ValueSetAcc() override; + + void FireAccessibleEvent( short nEventId, const css::uno::Any& rOldValue, const css::uno::Any& rNewValue ); + bool HasAccessibleListeners() const { return( mxEventListeners.size() > 0 ); } + + static ValueSetAcc* getImplementation( const css::uno::Reference< css::uno::XInterface >& rxData ) throw(); + +public: + + /** Called by the corresponding ValueSet when it gets the focus. + Stores the new focus state and broadcasts a state change event. + */ + void GetFocus(); + + /** Called by the corresponding ValueSet when it loses the focus. + Stores the new focus state and broadcasts a state change event. + */ + void LoseFocus(); + + // XAccessible + virtual css::uno::Reference< css::accessibility::XAccessibleContext > SAL_CALL getAccessibleContext( ) 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; + + // 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; + + // 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; + + // XAccessibleSelection + 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; + + // XUnoTunnel + static const css::uno::Sequence< sal_Int8 >& getUnoTunnelId(); + virtual sal_Int64 SAL_CALL getSomething( const css::uno::Sequence< sal_Int8 >& rId ) override; + +private: + ::std::vector< css::uno::Reference< + css::accessibility::XAccessibleEventListener > > mxEventListeners; + ValueSet* mpParent; + /// The current FOCUSED state. + bool mbIsFocused; + + /** Tell all listeners that the object is dying. This callback is + usually called from the WeakComponentImplHelper class. + */ + virtual void SAL_CALL disposing() override; + + /** Return the number of items. This takes the None-Item into account. + */ + sal_uInt16 getItemCount() const; + + /** Return the item associated with the given index. The None-Item is + taken into account which, when present, is taken to be the first + (with index 0) item. + @param nIndex + Index of the item to return. The index 0 denotes the None-Item + when present. + @return + Returns NULL when the given index is out of range. + */ + ValueSetItem* getItem (sal_uInt16 nIndex) const; + + /** 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(); + + /** Check whether the value set has a 'none' field, i.e. a field (button) + that deselects any items (selects none of them). + @return + Returns <true/> if there is a 'none' field and <false/> if it is + missing. + */ + bool HasNoneField() const; +}; + +class ValueItemAcc : public ::cppu::WeakImplHelper< css::accessibility::XAccessible, + css::accessibility::XAccessibleEventBroadcaster, + css::accessibility::XAccessibleContext, + css::accessibility::XAccessibleComponent, + css::lang::XUnoTunnel > +{ +private: + + ::std::vector< css::uno::Reference< + css::accessibility::XAccessibleEventListener > > mxEventListeners; + ::osl::Mutex maMutex; + ValueSetItem* mpParent; + bool mbIsTransientChildrenDisabled; + +public: + + ValueItemAcc(ValueSetItem* pParent, bool bIsTransientChildrenDisabled); + virtual ~ValueItemAcc() override; + + void ParentDestroyed(); + + void FireAccessibleEvent( short nEventId, const css::uno::Any& rOldValue, const css::uno::Any& rNewValue ); + + static ValueItemAcc* getImplementation( const css::uno::Reference< css::uno::XInterface >& rxData ) throw(); + +public: + + // XAccessible + virtual css::uno::Reference< css::accessibility::XAccessibleContext > SAL_CALL getAccessibleContext( ) 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; + + // 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; + + // 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; + + // XUnoTunnel + static const css::uno::Sequence< sal_Int8 >& getUnoTunnelId(); + virtual sal_Int64 SAL_CALL getSomething( const css::uno::Sequence< sal_Int8 >& rId ) override; +}; + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/control/valueset.cxx b/svtools/source/control/valueset.cxx new file mode 100644 index 000000000..8e679562a --- /dev/null +++ b/svtools/source/control/valueset.cxx @@ -0,0 +1,1942 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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/config.h> + +#include <o3tl/safeint.hxx> +#include <tools/debug.hxx> +#include <tools/stream.hxx> +#include <comphelper/base64.hxx> +#include <vcl/decoview.hxx> +#include <vcl/event.hxx> +#include <vcl/graph.hxx> +#include <vcl/svapp.hxx> +#include <vcl/scrbar.hxx> +#include <vcl/cvtgrf.hxx> +#include <vcl/help.hxx> +#include <vcl/settings.hxx> +#include <vcl/commandevent.hxx> +#include <vcl/virdev.hxx> + +#include <com/sun/star/accessibility/AccessibleEventId.hpp> +#include <com/sun/star/lang/XComponent.hpp> +#include <rtl/ustring.hxx> +#include <sal/log.hxx> +#include "valueimp.hxx" + +#include <svtools/valueset.hxx> +#include <boost/property_tree/ptree.hpp> + +using namespace css::uno; +using namespace css::lang; +using namespace css::accessibility; + +namespace +{ + +enum +{ + ITEM_OFFSET = 4, + ITEM_OFFSET_DOUBLE = 6, + NAME_LINE_OFF_X = 2, + NAME_LINE_OFF_Y = 2, + NAME_LINE_HEIGHT = 2, + NAME_OFFSET = 2, + SCRBAR_OFFSET = 1 +}; + +} + +ValueSet::ValueSet(std::unique_ptr<weld::ScrolledWindow> pScrolledWindow) + : maVirDev( VclPtr<VirtualDevice>::Create()) + , mxScrolledWindow(std::move(pScrolledWindow)) + , mnHighItemId(0) + , maColor(COL_TRANSPARENT) + , mnStyle(0) + , mbFormat(true) + , mbHighlight(false) +{ + maVirDev->SetBackground(Application::GetSettings().GetStyleSettings().GetFaceColor()); + + mnItemWidth = 0; + mnItemHeight = 0; + mnTextOffset = 0; + mnVisLines = 0; + mnLines = 0; + mnUserItemWidth = 0; + mnUserItemHeight = 0; + mnFirstLine = 0; + mnSelItemId = 0; + mnSavedItemId = -1; + mnCols = 0; + mnCurCol = 0; + mnUserCols = 0; + mnUserVisLines = 0; + mnSpacing = 0; + mnFrameStyle = DrawFrameStyle::NONE; + mbNoSelection = true; + mbDrawSelection = true; + mbBlackSel = false; + mbDoubleSel = false; + mbScroll = false; + mbFullMode = true; + mbEdgeBlending = false; + mbHasVisibleItems = false; + + if (mxScrolledWindow) + { + mxScrolledWindow->set_user_managed_scrolling(); + mxScrolledWindow->connect_vadjustment_changed(LINK(this, ValueSet, ImplScrollHdl)); + } +} + +void ValueSet::SetDrawingArea(weld::DrawingArea* pDrawingArea) +{ + CustomWidgetController::SetDrawingArea(pDrawingArea); + // #106446#, #106601# force mirroring of virtual device + maVirDev->EnableRTL(pDrawingArea->get_direction()); +} + +Reference<XAccessible> ValueSet::CreateAccessible() +{ + if (!mxAccessible) + mxAccessible.set(new ValueSetAcc(this)); + return mxAccessible; +} + +ValueSet::~ValueSet() +{ + Reference<XComponent> xComponent(mxAccessible, UNO_QUERY); + if (xComponent.is()) + xComponent->dispose(); + + ImplDeleteItems(); +} + +void ValueSet::ImplDeleteItems() +{ + const size_t n = mItemList.size(); + + for ( size_t i = 0; i < n; ++i ) + { + ValueSetItem* pItem = mItemList[i].get(); + if ( pItem->mbVisible && ImplHasAccessibleListeners() ) + { + Any aOldAny; + Any aNewAny; + + aOldAny <<= pItem->GetAccessible( false/*bIsTransientChildrenDisabled*/ ); + ImplFireAccessibleEvent(AccessibleEventId::CHILD, aOldAny, aNewAny); + } + + mItemList[i].reset(); + } + + mItemList.clear(); +} + +void ValueSet::Select() +{ + maSelectHdl.Call( this ); +} + +void ValueSet::UserDraw( const UserDrawEvent& ) +{ +} + +size_t ValueSet::ImplGetItem( const Point& rPos ) const +{ + if (!mbHasVisibleItems) + { + return VALUESET_ITEM_NOTFOUND; + } + + if (mpNoneItem && maNoneItemRect.IsInside(rPos)) + { + return VALUESET_ITEM_NONEITEM; + } + + if (maItemListRect.IsInside(rPos)) + { + const int xc = rPos.X() - maItemListRect.Left(); + const int yc = rPos.Y() - maItemListRect.Top(); + // The point is inside the area of item list, + // let's find the containing item. + const int col = xc / (mnItemWidth + mnSpacing); + const int x = xc % (mnItemWidth + mnSpacing); + const int row = yc / (mnItemHeight + mnSpacing); + const int y = yc % (mnItemHeight + mnSpacing); + + if (x < mnItemWidth && y < mnItemHeight) + { + // the point is inside item rect and not inside spacing + const size_t item = (mnFirstLine + row) * static_cast<size_t>(mnCols) + col; + if (item < mItemList.size()) + { + return item; + } + } + } + + return VALUESET_ITEM_NOTFOUND; +} + +ValueSetItem* ValueSet::ImplGetItem( size_t nPos ) +{ + if (nPos == VALUESET_ITEM_NONEITEM) + return mpNoneItem.get(); + else + return (nPos < mItemList.size()) ? mItemList[nPos].get() : nullptr; +} + +ValueSetItem* ValueSet::ImplGetFirstItem() +{ + return !mItemList.empty() ? mItemList[0].get() : nullptr; +} + +sal_uInt16 ValueSet::ImplGetVisibleItemCount() const +{ + sal_uInt16 nRet = 0; + const size_t nItemCount = mItemList.size(); + + for ( size_t n = 0; n < nItemCount; ++n ) + { + if ( mItemList[n]->mbVisible ) + ++nRet; + } + + return nRet; +} + +void ValueSet::ImplFireAccessibleEvent( short nEventId, const Any& rOldValue, const Any& rNewValue ) +{ + ValueSetAcc* pAcc = ValueSetAcc::getImplementation(mxAccessible); + + if( pAcc ) + pAcc->FireAccessibleEvent( nEventId, rOldValue, rNewValue ); +} + +bool ValueSet::ImplHasAccessibleListeners() +{ + ValueSetAcc* pAcc = ValueSetAcc::getImplementation(mxAccessible); + return( pAcc && pAcc->HasAccessibleListeners() ); +} + +IMPL_LINK(ValueSet, ImplScrollHdl, weld::ScrolledWindow&, rScrollWin, void) +{ + auto nNewFirstLine = rScrollWin.vadjustment_get_value(); + if ( nNewFirstLine != mnFirstLine ) + { + mnFirstLine = nNewFirstLine; + mbFormat = true; + Invalidate(); + } +} + +void ValueSet::Paint(vcl::RenderContext& rRenderContext, const tools::Rectangle&) +{ + if (GetStyle() & WB_FLATVALUESET) + { + const StyleSettings& rStyleSettings = rRenderContext.GetSettings().GetStyleSettings(); + rRenderContext.SetLineColor(); + rRenderContext.SetFillColor(rStyleSettings.GetFaceColor()); + long nOffY = maVirDev->GetOutputSizePixel().Height(); + Size aWinSize(GetOutputSizePixel()); + rRenderContext.DrawRect(tools::Rectangle(Point(0, nOffY ), Point( aWinSize.Width(), aWinSize.Height()))); + } + + ImplDraw(rRenderContext); +} + +void ValueSet::GetFocus() +{ + SAL_INFO("svtools", "value set getting focus"); + Invalidate(); + CustomWidgetController::GetFocus(); + + // Tell the accessible object that we got the focus. + ValueSetAcc* pAcc = ValueSetAcc::getImplementation(mxAccessible); + if (pAcc) + pAcc->GetFocus(); +} + +void ValueSet::LoseFocus() +{ + SAL_INFO("svtools", "value set losing focus"); + Invalidate(); + CustomWidgetController::LoseFocus(); + + // Tell the accessible object that we lost the focus. + ValueSetAcc* pAcc = ValueSetAcc::getImplementation(mxAccessible); + if( pAcc ) + pAcc->LoseFocus(); +} + +void ValueSet::Resize() +{ + mbFormat = true; + if ( IsReallyVisible() && IsUpdateMode() ) + Invalidate(); + CustomWidgetController::Resize(); +} + +bool ValueSet::KeyInput( const KeyEvent& rKeyEvent ) +{ + size_t nLastItem = mItemList.size(); + + if ( !nLastItem || !ImplGetFirstItem() ) + return CustomWidgetController::KeyInput(rKeyEvent); + + if (mbFormat) + Invalidate(); + + --nLastItem; + + const size_t nCurPos + = mnSelItemId ? GetItemPos(mnSelItemId) : (mpNoneItem ? VALUESET_ITEM_NONEITEM : 0); + size_t nItemPos = VALUESET_ITEM_NOTFOUND; + size_t nVStep = mnCols; + + switch (rKeyEvent.GetKeyCode().GetCode()) + { + case KEY_HOME: + nItemPos = mpNoneItem ? VALUESET_ITEM_NONEITEM : 0; + break; + + case KEY_END: + nItemPos = nLastItem; + break; + + case KEY_LEFT: + if (nCurPos != VALUESET_ITEM_NONEITEM) + { + if (nCurPos) + { + nItemPos = nCurPos-1; + } + else if (mpNoneItem) + { + nItemPos = VALUESET_ITEM_NONEITEM; + } + } + break; + + case KEY_RIGHT: + if (nCurPos < nLastItem) + { + if (nCurPos == VALUESET_ITEM_NONEITEM) + { + nItemPos = 0; + } + else + { + nItemPos = nCurPos+1; + } + } + break; + + case KEY_PAGEUP: + if (rKeyEvent.GetKeyCode().IsShift() || rKeyEvent.GetKeyCode().IsMod1() || rKeyEvent.GetKeyCode().IsMod2()) + { + return CustomWidgetController::KeyInput(rKeyEvent); + } + nVStep *= mnVisLines; + [[fallthrough]]; + case KEY_UP: + if (nCurPos != VALUESET_ITEM_NONEITEM) + { + if (nCurPos == nLastItem) + { + const size_t nCol = mnCols ? nLastItem % mnCols : 0; + if (nCol < mnCurCol) + { + // Move to previous row/page, keeping the old column + nVStep -= mnCurCol - nCol; + } + } + if (nCurPos >= nVStep) + { + // Go up of a whole page + nItemPos = nCurPos-nVStep; + } + else if (mpNoneItem) + { + nItemPos = VALUESET_ITEM_NONEITEM; + } + else if (nCurPos > mnCols) + { + // Go to same column in first row + nItemPos = nCurPos % mnCols; + } + } + break; + + case KEY_PAGEDOWN: + if (rKeyEvent.GetKeyCode().IsShift() || rKeyEvent.GetKeyCode().IsMod1() || rKeyEvent.GetKeyCode().IsMod2()) + { + return CustomWidgetController::KeyInput(rKeyEvent); + } + nVStep *= mnVisLines; + [[fallthrough]]; + case KEY_DOWN: + if (nCurPos != nLastItem) + { + if (nCurPos == VALUESET_ITEM_NONEITEM) + { + nItemPos = nVStep-mnCols+mnCurCol; + } + else + { + nItemPos = nCurPos+nVStep; + } + if (nItemPos > nLastItem) + { + nItemPos = nLastItem; + } + } + break; + + case KEY_RETURN: + if (GetStyle() & WB_NO_DIRECTSELECT) + { + Select(); + break; + } + [[fallthrough]]; + default: + return CustomWidgetController::KeyInput(rKeyEvent); + } + + if ( nItemPos == VALUESET_ITEM_NOTFOUND ) + return true; + + if ( nItemPos!=VALUESET_ITEM_NONEITEM && nItemPos<nLastItem ) + { + // update current column only in case of a new position + // which is also not a "specially" handled one. + mnCurCol = mnCols ? nItemPos % mnCols : 0; + } + const sal_uInt16 nItemId = (nItemPos != VALUESET_ITEM_NONEITEM) ? GetItemId( nItemPos ) : 0; + if ( nItemId != mnSelItemId ) + { + SelectItem( nItemId ); + if (!(GetStyle() & WB_NO_DIRECTSELECT)) + { + // select only if WB_NO_DIRECTSELECT is not set + Select(); + } + } + + return true; +} + +void ValueSet::ImplTracking(const Point& rPos) +{ + ValueSetItem* pItem = ImplGetItem( ImplGetItem( rPos ) ); + if ( pItem ) + { + if( GetStyle() & WB_MENUSTYLEVALUESET || GetStyle() & WB_FLATVALUESET ) + mbHighlight = true; + + ImplHighlightItem( pItem->mnId ); + } + else + { + if( GetStyle() & WB_MENUSTYLEVALUESET || GetStyle() & WB_FLATVALUESET ) + mbHighlight = true; + + ImplHighlightItem( mnSelItemId, false ); + } +} + +bool ValueSet::MouseButtonDown( const MouseEvent& rMouseEvent ) +{ + if ( rMouseEvent.IsLeft() ) + { + ValueSetItem* pItem = ImplGetItem( ImplGetItem( rMouseEvent.GetPosPixel() ) ); + if (pItem && !rMouseEvent.IsMod2()) + { + if (rMouseEvent.GetClicks() == 1) + { + SelectItem( pItem->mnId ); + if (!(GetStyle() & WB_NOPOINTERFOCUS)) + GrabFocus(); + } + else if ( rMouseEvent.GetClicks() == 2 ) + maDoubleClickHdl.Call( this ); + + return true; + } + } + + return CustomWidgetController::MouseButtonDown( rMouseEvent ); +} + +bool ValueSet::MouseButtonUp( const MouseEvent& rMouseEvent ) +{ + if (rMouseEvent.IsLeft() && !rMouseEvent.IsMod2()) + { + Select(); + return true; + } + + return CustomWidgetController::MouseButtonUp( rMouseEvent ); +} + +bool ValueSet::MouseMove(const MouseEvent& rMouseEvent) +{ + // because of SelectionMode + if ((GetStyle() & WB_MENUSTYLEVALUESET) || (GetStyle() & WB_FLATVALUESET)) + ImplTracking(rMouseEvent.GetPosPixel()); + return CustomWidgetController::MouseMove(rMouseEvent); +} + +void ValueSet::QueueReformat() +{ + queue_resize(); + RecalcScrollBar(); + mbFormat = true; + if ( IsReallyVisible() && IsUpdateMode() ) + Invalidate(); +} + +void ValueSet::RemoveItem( sal_uInt16 nItemId ) +{ + size_t nPos = GetItemPos( nItemId ); + + if ( nPos == VALUESET_ITEM_NOTFOUND ) + return; + + if ( nPos < mItemList.size() ) { + mItemList.erase( mItemList.begin() + nPos ); + } + + // reset variables + if (mnHighItemId == nItemId || mnSelItemId == nItemId) + { + mnCurCol = 0; + mnHighItemId = 0; + mnSelItemId = 0; + mbNoSelection = true; + } + + QueueReformat(); +} + +bool ValueSet::TurnOffScrollBar() +{ + if (mxScrolledWindow->get_vpolicy() == VclPolicyType::NEVER) + return false; + mxScrolledWindow->set_vpolicy(VclPolicyType::NEVER); + weld::DrawingArea* pDrawingArea = GetDrawingArea(); + Size aPrefSize(pDrawingArea->get_preferred_size()); + pDrawingArea->set_size_request(aPrefSize.Width() + GetScrollWidth(), aPrefSize.Height()); + return true; +} + +void ValueSet::TurnOnScrollBar() +{ + if (mxScrolledWindow->get_vpolicy() == VclPolicyType::ALWAYS) + return; + mxScrolledWindow->set_vpolicy(VclPolicyType::ALWAYS); + weld::DrawingArea* pDrawingArea = GetDrawingArea(); + Size aPrefSize(pDrawingArea->get_preferred_size()); + pDrawingArea->set_size_request(aPrefSize.Width() - GetScrollWidth(), aPrefSize.Height()); +} + +void ValueSet::RecalcScrollBar() +{ + if (!mxScrolledWindow) + return; + const bool bScrollAllowed = GetStyle() & WB_VSCROLL; + if (!bScrollAllowed) + return; + // reset scrolled window state to initial value so it will get configured + // to the right adjustment on the next format which we toggle on to happen + // if the scrolledwindow wasn't in its initial state already + if (TurnOffScrollBar()) + mbFormat = true; +} + +void ValueSet::Clear() +{ + ImplDeleteItems(); + + // reset variables + mnFirstLine = 0; + mnCurCol = 0; + mnHighItemId = 0; + mnSelItemId = 0; + mbNoSelection = true; + + RecalcScrollBar(); + + mbFormat = true; + if ( IsReallyVisible() && IsUpdateMode() ) + Invalidate(); +} + +size_t ValueSet::GetItemCount() const +{ + return mItemList.size(); +} + +size_t ValueSet::GetItemPos( sal_uInt16 nItemId ) const +{ + for ( size_t i = 0, n = mItemList.size(); i < n; ++i ) { + if ( mItemList[i]->mnId == nItemId ) { + return i; + } + } + return VALUESET_ITEM_NOTFOUND; +} + +sal_uInt16 ValueSet::GetItemId( size_t nPos ) const +{ + return ( nPos < mItemList.size() ) ? mItemList[nPos]->mnId : 0 ; +} + +sal_uInt16 ValueSet::GetItemId( const Point& rPos ) const +{ + size_t nItemPos = ImplGetItem( rPos ); + if ( nItemPos != VALUESET_ITEM_NOTFOUND ) + return GetItemId( nItemPos ); + + return 0; +} + +tools::Rectangle ValueSet::GetItemRect( sal_uInt16 nItemId ) const +{ + const size_t nPos = GetItemPos( nItemId ); + + if ( nPos!=VALUESET_ITEM_NOTFOUND && mItemList[nPos]->mbVisible ) + return ImplGetItemRect( nPos ); + + return tools::Rectangle(); +} + +tools::Rectangle ValueSet::ImplGetItemRect( size_t nPos ) const +{ + const size_t nVisibleBegin = static_cast<size_t>(mnFirstLine)*mnCols; + const size_t nVisibleEnd = nVisibleBegin + static_cast<size_t>(mnVisLines)*mnCols; + + // Check if the item is inside the range of the displayed ones, + // taking into account that last row could be incomplete + if ( nPos<nVisibleBegin || nPos>=nVisibleEnd || nPos>=mItemList.size() ) + return tools::Rectangle(); + + nPos -= nVisibleBegin; + + const size_t row = mnCols ? nPos/mnCols : 0; + const size_t col = mnCols ? nPos%mnCols : 0; + const long x = maItemListRect.Left()+col*(mnItemWidth+mnSpacing); + const long y = maItemListRect.Top()+row*(mnItemHeight+mnSpacing); + + return tools::Rectangle( Point(x, y), Size(mnItemWidth, mnItemHeight) ); +} + +void ValueSet::ImplHighlightItem( sal_uInt16 nItemId, bool bIsSelection ) +{ + if ( mnHighItemId == nItemId ) + return; + + // remember the old item to delete the previous selection + mnHighItemId = nItemId; + + // don't draw the selection if nothing is selected + if ( !bIsSelection && mbNoSelection ) + mbDrawSelection = false; + + // remove the old selection and draw the new one + Invalidate(); + mbDrawSelection = true; +} + +void ValueSet::ImplDraw(vcl::RenderContext& rRenderContext) +{ + if (mbFormat) + Format(rRenderContext); + + Point aDefPos; + Size aSize = maVirDev->GetOutputSizePixel(); + + rRenderContext.DrawOutDev(aDefPos, aSize, aDefPos, aSize, *maVirDev); + + // draw parting line to the Namefield + if (GetStyle() & WB_NAMEFIELD) + { + if (!(GetStyle() & WB_FLATVALUESET)) + { + const StyleSettings& rStyleSettings = rRenderContext.GetSettings().GetStyleSettings(); + Size aWinSize(GetOutputSizePixel()); + Point aPos1(NAME_LINE_OFF_X, mnTextOffset + NAME_LINE_OFF_Y); + Point aPos2(aWinSize.Width() - (NAME_LINE_OFF_X * 2), mnTextOffset + NAME_LINE_OFF_Y); + if (!(rStyleSettings.GetOptions() & StyleSettingsOptions::Mono)) + { + rRenderContext.SetLineColor(rStyleSettings.GetShadowColor()); + rRenderContext.DrawLine(aPos1, aPos2); + aPos1.AdjustY( 1 ); + aPos2.AdjustY( 1 ); + rRenderContext.SetLineColor(rStyleSettings.GetLightColor()); + } + else + rRenderContext.SetLineColor(rStyleSettings.GetWindowTextColor()); + rRenderContext.DrawLine(aPos1, aPos2); + } + } + + ImplDrawSelect(rRenderContext); +} + +/** + * An inelegant method; sets the item width & height such that + * all of the included items and their labels fit; if we can + * calculate that. + */ +void ValueSet::RecalculateItemSizes() +{ + Size aLargestItem = GetLargestItemSize(); + + if ( mnUserItemWidth != aLargestItem.Width() || + mnUserItemHeight != aLargestItem.Height() ) + { + mnUserItemWidth = aLargestItem.Width(); + mnUserItemHeight = aLargestItem.Height(); + QueueReformat(); + } +} + +void ValueSet::SetFirstLine(sal_uInt16 nNewFirstLine) +{ + if (nNewFirstLine != mnFirstLine) + { + mnFirstLine = nNewFirstLine; + if (mxScrolledWindow) + mxScrolledWindow->vadjustment_set_value(mnFirstLine); + } +} + +void ValueSet::SelectItem( sal_uInt16 nItemId ) +{ + size_t nItemPos = 0; + + if ( nItemId ) + { + nItemPos = GetItemPos( nItemId ); + if ( nItemPos == VALUESET_ITEM_NOTFOUND ) + return; + } + + if ( !((mnSelItemId != nItemId) || mbNoSelection) ) + return; + + const sal_uInt16 nOldItem = mnSelItemId; + mnSelItemId = nItemId; + mbNoSelection = false; + + bool bNewOut = !mbFormat && IsReallyVisible() && IsUpdateMode(); + bool bNewLine = false; + + if (weld::DrawingArea* pNeedsFormatToScroll = !mnCols ? GetDrawingArea() : nullptr) + { + Format(pNeedsFormatToScroll->get_ref_device()); + // reset scrollbar so its set to the later calculated mnFirstLine on + // the next Format + RecalcScrollBar(); // reset scrollbar so its set to the later calculated + } + + // if necessary scroll to the visible area + if (mbScroll && nItemId && mnCols) + { + sal_uInt16 nNewLine = static_cast<sal_uInt16>(nItemPos / mnCols); + if ( nNewLine < mnFirstLine ) + { + SetFirstLine(nNewLine); + bNewLine = true; + } + else if ( nNewLine > o3tl::make_unsigned(mnFirstLine+mnVisLines-1) ) + { + SetFirstLine(static_cast<sal_uInt16>(nNewLine-mnVisLines+1)); + bNewLine = true; + } + } + + if ( bNewOut ) + { + if ( bNewLine ) + { + // redraw everything if the visible area has changed + mbFormat = true; + } + Invalidate(); + } + + if( ImplHasAccessibleListeners() ) + { + // focus event (deselect) + if( nOldItem ) + { + const size_t nPos = GetItemPos( nItemId ); + + if( nPos != VALUESET_ITEM_NOTFOUND ) + { + ValueItemAcc* pItemAcc = ValueItemAcc::getImplementation( + mItemList[nPos]->GetAccessible( false/*bIsTransientChildrenDisabled*/ ) ); + + if( pItemAcc ) + { + Any aOldAny; + Any aNewAny; + aOldAny <<= Reference<XInterface>(static_cast<cppu::OWeakObject*>(pItemAcc)); + ImplFireAccessibleEvent(AccessibleEventId::ACTIVE_DESCENDANT_CHANGED, aOldAny, aNewAny ); + } + } + } + + // focus event (select) + const size_t nPos = GetItemPos( mnSelItemId ); + + ValueSetItem* pItem; + if( nPos != VALUESET_ITEM_NOTFOUND ) + pItem = mItemList[nPos].get(); + else + pItem = mpNoneItem.get(); + + ValueItemAcc* pItemAcc = nullptr; + if (pItem != nullptr) + pItemAcc = ValueItemAcc::getImplementation( pItem->GetAccessible( false/*bIsTransientChildrenDisabled*/ ) ); + + if( pItemAcc ) + { + Any aOldAny; + Any aNewAny; + aNewAny <<= Reference<XInterface>(static_cast<cppu::OWeakObject*>(pItemAcc)); + ImplFireAccessibleEvent(AccessibleEventId::ACTIVE_DESCENDANT_CHANGED, aOldAny, aNewAny); + } + + // selection event + Any aOldAny; + Any aNewAny; + ImplFireAccessibleEvent(AccessibleEventId::SELECTION_CHANGED, aOldAny, aNewAny); + } +} + +void ValueSet::SetNoSelection() +{ + mbNoSelection = true; + mbHighlight = false; + + if (IsReallyVisible() && IsUpdateMode()) + Invalidate(); +} + +void ValueSet::SetStyle(WinBits nStyle) +{ + if (nStyle != mnStyle) + { + mnStyle = nStyle; + mbFormat = true; + Invalidate(); + } +} + +void ValueSet::Format(vcl::RenderContext const & rRenderContext) +{ + Size aWinSize(GetOutputSizePixel()); + size_t nItemCount = mItemList.size(); + WinBits nStyle = GetStyle(); + long nTxtHeight = rRenderContext.GetTextHeight(); + long nOff; + long nNoneHeight; + long nNoneSpace; + + if (mxScrolledWindow && !(nStyle & WB_VSCROLL) && mxScrolledWindow->get_vpolicy() != VclPolicyType::NEVER) + TurnOffScrollBar(); + + // calculate item offset + if (nStyle & WB_ITEMBORDER) + { + if (nStyle & WB_DOUBLEBORDER) + nOff = ITEM_OFFSET_DOUBLE; + else + nOff = ITEM_OFFSET; + } + else + nOff = 0; + + // consider size, if NameField does exist + if (nStyle & WB_NAMEFIELD) + { + mnTextOffset = aWinSize.Height() - nTxtHeight - NAME_OFFSET; + aWinSize.AdjustHeight( -(nTxtHeight + NAME_OFFSET) ); + + if (!(nStyle & WB_FLATVALUESET)) + { + mnTextOffset -= NAME_LINE_HEIGHT + NAME_LINE_OFF_Y; + aWinSize.AdjustHeight( -(NAME_LINE_HEIGHT + NAME_LINE_OFF_Y) ); + } + } + else + mnTextOffset = 0; + + // consider offset and size, if NoneField does exist + if (nStyle & WB_NONEFIELD) + { + nNoneHeight = nTxtHeight + nOff; + nNoneSpace = mnSpacing; + } + else + { + nNoneHeight = 0; + nNoneSpace = 0; + mpNoneItem.reset(); + } + + // calculate number of columns + if (!mnUserCols) + { + if (mnUserItemWidth) + { + mnCols = static_cast<sal_uInt16>((aWinSize.Width() - mnSpacing) / (mnUserItemWidth + mnSpacing)); + if (mnCols <= 0) + mnCols = 1; + } + else + { + mnCols = 1; + } + } + else + { + mnCols = mnUserCols; + } + + // calculate number of rows + mbScroll = false; + + auto nOldLines = mnLines; + // Floor( (M+N-1)/N )==Ceiling( M/N ) + mnLines = (static_cast<long>(nItemCount) + mnCols - 1) / mnCols; + if (mnLines <= 0) + mnLines = 1; + + bool bAdjustmentOutOfDate = nOldLines != mnLines; + + auto nOldVisLines = mnVisLines; + + long nCalcHeight = aWinSize.Height() - nNoneHeight; + if (mnUserVisLines) + { + mnVisLines = mnUserVisLines; + } + else if (mnUserItemHeight) + { + mnVisLines = (nCalcHeight - nNoneSpace + mnSpacing) / (mnUserItemHeight + mnSpacing); + if (!mnVisLines) + mnVisLines = 1; + } + else + { + mnVisLines = mnLines; + } + + bAdjustmentOutOfDate |= nOldVisLines != mnVisLines; + + if (mnLines > mnVisLines) + mbScroll = true; + + if (mnLines <= mnVisLines) + { + SetFirstLine(0); + } + else + { + if (mnFirstLine > o3tl::make_unsigned(mnLines - mnVisLines)) + SetFirstLine(static_cast<sal_uInt16>(mnLines - mnVisLines)); + } + + // calculate item size + const long nColSpace = (mnCols - 1) * static_cast<long>(mnSpacing); + const long nLineSpace = ((mnVisLines - 1) * mnSpacing) + nNoneSpace; + if (mnUserItemWidth && !mnUserCols) + { + mnItemWidth = mnUserItemWidth; + if (mnItemWidth > aWinSize.Width() - nColSpace) + mnItemWidth = aWinSize.Width() - nColSpace; + } + else + mnItemWidth = (aWinSize.Width() - nColSpace) / mnCols; + if (mnUserItemHeight && !mnUserVisLines) + { + mnItemHeight = mnUserItemHeight; + if (mnItemHeight > nCalcHeight - nNoneSpace) + mnItemHeight = nCalcHeight - nNoneSpace; + } + else + { + nCalcHeight -= nLineSpace; + mnItemHeight = nCalcHeight / mnVisLines; + } + + // Init VirDev + maVirDev->SetSettings(rRenderContext.GetSettings()); + maVirDev->SetOutputSizePixel(aWinSize); + + // nothing is changed in case of too small items + if ((mnItemWidth <= 0) || + (mnItemHeight <= ((nStyle & WB_ITEMBORDER) ? 4 : 2)) || + !nItemCount) + { + mbHasVisibleItems = false; + + if ((nStyle & WB_NONEFIELD) && mpNoneItem) + { + mpNoneItem->mbVisible = false; + mpNoneItem->maText = GetText(); + } + + for (size_t i = 0; i < nItemCount; i++) + { + mItemList[i]->mbVisible = false; + } + + if (mxScrolledWindow && mxScrolledWindow->get_vpolicy() != VclPolicyType::NEVER) + TurnOffScrollBar(); + } + else + { + mbHasVisibleItems = true; + + // determine Frame-Style + if (nStyle & WB_DOUBLEBORDER) + mnFrameStyle = DrawFrameStyle::DoubleIn; + else + mnFrameStyle = DrawFrameStyle::In; + + // determine selected color and width + // if necessary change the colors, to make the selection + // better detectable + const StyleSettings& rStyleSettings = rRenderContext.GetSettings().GetStyleSettings(); + Color aHighColor(rStyleSettings.GetHighlightColor()); + if (((aHighColor.GetRed() > 0x80) || (aHighColor.GetGreen() > 0x80) || + (aHighColor.GetBlue() > 0x80)) || + ((aHighColor.GetRed() == 0x80) && (aHighColor.GetGreen() == 0x80) && + (aHighColor.GetBlue() == 0x80))) + { + mbBlackSel = true; + } + else + { + mbBlackSel = false; + } + // draw the selection with double width if the items are bigger + if ((nStyle & WB_DOUBLEBORDER) && + ((mnItemWidth >= 25) && (mnItemHeight >= 20))) + { + mbDoubleSel = true; + } + else + { + mbDoubleSel = false; + } + + // calculate offsets + long nStartX; + long nStartY; + if (mbFullMode) + { + long nAllItemWidth = (mnItemWidth * mnCols) + nColSpace; + long nAllItemHeight = (mnItemHeight * mnVisLines) + nNoneHeight + nLineSpace; + nStartX = (aWinSize.Width() - nAllItemWidth) / 2; + nStartY = (aWinSize.Height() - nAllItemHeight) / 2; + } + else + { + nStartX = 0; + nStartY = 0; + } + + // calculate and draw items + maVirDev->SetLineColor(); + long x = nStartX; + long y = nStartY; + + // create NoSelection field and show it + if (nStyle & WB_NONEFIELD) + { + if (!mpNoneItem) + mpNoneItem.reset(new ValueSetItem(*this)); + + mpNoneItem->mnId = 0; + mpNoneItem->meType = VALUESETITEM_NONE; + mpNoneItem->mbVisible = true; + maNoneItemRect.SetLeft( x ); + maNoneItemRect.SetTop( y ); + maNoneItemRect.SetRight( maNoneItemRect.Left() + aWinSize.Width() - x - 1 ); + maNoneItemRect.SetBottom( y + nNoneHeight - 1 ); + + ImplFormatItem(rRenderContext, mpNoneItem.get(), maNoneItemRect); + + y += nNoneHeight + nNoneSpace; + } + + // draw items + sal_uLong nFirstItem = static_cast<sal_uLong>(mnFirstLine) * mnCols; + sal_uLong nLastItem = nFirstItem + (mnVisLines * mnCols); + + maItemListRect.SetLeft( x ); + maItemListRect.SetTop( y ); + maItemListRect.SetRight( x + mnCols * (mnItemWidth + mnSpacing) - mnSpacing - 1 ); + maItemListRect.SetBottom( y + mnVisLines * (mnItemHeight + mnSpacing) - mnSpacing - 1 ); + + if (!mbFullMode) + { + // If want also draw parts of items in the last line, + // then we add one more line if parts of these line are + // visible + if (y + (mnVisLines * (mnItemHeight + mnSpacing)) < aWinSize.Height()) + nLastItem += mnCols; + maItemListRect.SetBottom( aWinSize.Height() - y ); + } + for (size_t i = 0; i < nItemCount; i++) + { + ValueSetItem* pItem = mItemList[i].get(); + + if (i >= nFirstItem && i < nLastItem) + { + if (!pItem->mbVisible && ImplHasAccessibleListeners()) + { + Any aOldAny; + Any aNewAny; + + aNewAny <<= pItem->GetAccessible(false/*bIsTransientChildrenDisabled*/); + ImplFireAccessibleEvent(AccessibleEventId::CHILD, aOldAny, aNewAny); + } + + pItem->mbVisible = true; + ImplFormatItem(rRenderContext, pItem, tools::Rectangle(Point(x, y), Size(mnItemWidth, mnItemHeight))); + + if (!((i + 1) % mnCols)) + { + x = nStartX; + y += mnItemHeight + mnSpacing; + } + else + x += mnItemWidth + mnSpacing; + } + else + { + if (pItem->mbVisible && ImplHasAccessibleListeners()) + { + Any aOldAny; + Any aNewAny; + + aOldAny <<= pItem->GetAccessible(false/*bIsTransientChildrenDisabled*/); + ImplFireAccessibleEvent(AccessibleEventId::CHILD, aOldAny, aNewAny); + } + + pItem->mbVisible = false; + } + } + + // arrange ScrollBar, set values and show it + if (mxScrolledWindow && (nStyle & WB_VSCROLL)) + { + bool bTurnScrollbarOn = mxScrolledWindow->get_vpolicy() != VclPolicyType::ALWAYS; + if (bAdjustmentOutOfDate || bTurnScrollbarOn) + { + long nPageSize = mnVisLines; + if (nPageSize < 1) + nPageSize = 1; + mxScrolledWindow->vadjustment_configure(mnFirstLine, 0, mnLines, 1, + mnVisLines, nPageSize); + } + + if (bTurnScrollbarOn) + TurnOnScrollBar(); + } + } + + // waiting for the next since the formatting is finished + mbFormat = false; +} + +void ValueSet::ImplDrawSelect(vcl::RenderContext& rRenderContext) +{ + if (!IsReallyVisible()) + return; + + const bool bFocus = HasFocus(); + const bool bDrawSel = !((mbNoSelection && !mbHighlight) || (!mbDrawSelection && mbHighlight)); + + if (!bFocus && !bDrawSel) + { + ImplDrawItemText(rRenderContext, OUString()); + return; + } + + ImplDrawSelect(rRenderContext, mnSelItemId, bFocus, bDrawSel); + if (mbHighlight) + { + ImplDrawSelect(rRenderContext, mnHighItemId, bFocus, bDrawSel); + } +} + +void ValueSet::ImplDrawSelect(vcl::RenderContext& rRenderContext, sal_uInt16 nItemId, const bool bFocus, const bool bDrawSel ) +{ + ValueSetItem* pItem; + tools::Rectangle aRect; + if (nItemId) + { + const size_t nPos = GetItemPos( nItemId ); + pItem = mItemList[ nPos ].get(); + aRect = ImplGetItemRect( nPos ); + } + else if (mpNoneItem) + { + pItem = mpNoneItem.get(); + aRect = maNoneItemRect; + } + else if (bFocus && (pItem = ImplGetFirstItem())) + { + aRect = ImplGetItemRect(0); + } + else + { + return; + } + + if (!pItem->mbVisible) + return; + + // draw selection + const StyleSettings& rStyleSettings = rRenderContext.GetSettings().GetStyleSettings(); + rRenderContext.SetFillColor(); + + Color aDoubleColor(rStyleSettings.GetHighlightColor()); + Color aSingleColor(rStyleSettings.GetHighlightTextColor()); + if (!mbDoubleSel) + { + /* + * #99777# contrast enhancement for thin mode + */ + const Wallpaper& rWall = maVirDev->GetBackground(); + if (!rWall.IsBitmap() && ! rWall.IsGradient()) + { + const Color& rBack = rWall.GetColor(); + if (rBack.IsDark() && ! aDoubleColor.IsBright()) + { + aDoubleColor = COL_WHITE; + aSingleColor = COL_BLACK; + } + else if (rBack.IsBright() && !aDoubleColor.IsDark()) + { + aDoubleColor = COL_BLACK; + aSingleColor = COL_WHITE; + } + } + } + + // specify selection output + WinBits nStyle = GetStyle(); + if (nStyle & WB_MENUSTYLEVALUESET) + { + if (bFocus) + DrawFocusRect(rRenderContext, aRect); + if (bDrawSel) + { + rRenderContext.SetLineColor(mbBlackSel ? COL_BLACK : aDoubleColor); + rRenderContext.DrawRect(aRect); + } + } + else + { + if (bDrawSel) + { + rRenderContext.SetLineColor(mbBlackSel ? COL_BLACK : aDoubleColor); + rRenderContext.DrawRect(aRect); + } + if (mbDoubleSel) + { + aRect.AdjustLeft( 1 ); + aRect.AdjustTop( 1 ); + aRect.AdjustRight( -1 ); + aRect.AdjustBottom( -1 ); + if (bDrawSel) + rRenderContext.DrawRect(aRect); + } + aRect.AdjustLeft( 1 ); + aRect.AdjustTop( 1 ); + aRect.AdjustRight( -1 ); + aRect.AdjustBottom( -1 ); + tools::Rectangle aRect2 = aRect; + aRect.AdjustLeft( 1 ); + aRect.AdjustTop( 1 ); + aRect.AdjustRight( -1 ); + aRect.AdjustBottom( -1 ); + if (bDrawSel) + rRenderContext.DrawRect(aRect); + if (mbDoubleSel) + { + aRect.AdjustLeft( 1 ); + aRect.AdjustTop( 1 ); + aRect.AdjustRight( -1 ); + aRect.AdjustBottom( -1 ); + if (bDrawSel) + rRenderContext.DrawRect(aRect); + } + + if (bDrawSel) + { + rRenderContext.SetLineColor(mbBlackSel ? COL_WHITE : aSingleColor); + } + else + { + rRenderContext.SetLineColor(COL_LIGHTGRAY); + } + rRenderContext.DrawRect(aRect2); + if (bFocus) + DrawFocusRect(rRenderContext, aRect2); + } + + ImplDrawItemText(rRenderContext, pItem->maText); +} + +void ValueSet::ImplFormatItem(vcl::RenderContext const & rRenderContext, ValueSetItem* pItem, tools::Rectangle aRect) +{ + WinBits nStyle = GetStyle(); + if (nStyle & WB_ITEMBORDER) + { + aRect.AdjustLeft(1 ); + aRect.AdjustTop(1 ); + aRect.AdjustRight( -1 ); + aRect.AdjustBottom( -1 ); + + if (nStyle & WB_FLATVALUESET) + { + sal_Int32 nBorder = (nStyle & WB_DOUBLEBORDER) ? 2 : 1; + + aRect.AdjustLeft(nBorder ); + aRect.AdjustTop(nBorder ); + aRect.AdjustRight( -nBorder ); + aRect.AdjustBottom( -nBorder ); + } + else + { + DecorationView aView(maVirDev.get()); + aRect = aView.DrawFrame(aRect, mnFrameStyle); + } + } + + if (pItem == mpNoneItem.get()) + pItem->maText = GetText(); + + if (!((aRect.GetHeight() > 0) && (aRect.GetWidth() > 0))) + return; + + const StyleSettings& rStyleSettings = rRenderContext.GetSettings().GetStyleSettings(); + + if (pItem == mpNoneItem.get()) + { + maVirDev->SetFont(rRenderContext.GetFont()); + maVirDev->SetTextColor((nStyle & WB_MENUSTYLEVALUESET) ? rStyleSettings.GetMenuTextColor() : rStyleSettings.GetWindowTextColor()); + maVirDev->SetTextFillColor(); + maVirDev->SetFillColor((nStyle & WB_MENUSTYLEVALUESET) ? rStyleSettings.GetMenuColor() : rStyleSettings.GetWindowColor()); + maVirDev->DrawRect(aRect); + Point aTxtPos(aRect.Left() + 2, aRect.Top()); + long nTxtWidth = rRenderContext.GetTextWidth(pItem->maText); + if ((aTxtPos.X() + nTxtWidth) > aRect.Right()) + { + maVirDev->SetClipRegion(vcl::Region(aRect)); + maVirDev->DrawText(aTxtPos, pItem->maText); + maVirDev->SetClipRegion(); + } + else + maVirDev->DrawText(aTxtPos, pItem->maText); + } + else if (pItem->meType == VALUESETITEM_COLOR) + { + maVirDev->SetFillColor(pItem->maColor); + maVirDev->DrawRect(aRect); + } + else + { + if (IsColor()) + maVirDev->SetFillColor(maColor); + else if (nStyle & WB_MENUSTYLEVALUESET) + maVirDev->SetFillColor(rStyleSettings.GetMenuColor()); + else if (IsEnabled()) + maVirDev->SetFillColor(rStyleSettings.GetWindowColor()); + else + maVirDev->SetFillColor(rStyleSettings.GetFaceColor()); + maVirDev->DrawRect(aRect); + + if (pItem->meType == VALUESETITEM_USERDRAW) + { + UserDrawEvent aUDEvt(nullptr, maVirDev.get(), aRect, pItem->mnId); + UserDraw(aUDEvt); + } + else + { + Size aImageSize = pItem->maImage.GetSizePixel(); + Size aRectSize = aRect.GetSize(); + Point aPos(aRect.Left(), aRect.Top()); + aPos.AdjustX((aRectSize.Width() - aImageSize.Width()) / 2 ); + + if (pItem->meType != VALUESETITEM_IMAGE_AND_TEXT) + aPos.AdjustY((aRectSize.Height() - aImageSize.Height()) / 2 ); + + DrawImageFlags nImageStyle = DrawImageFlags::NONE; + if (!IsEnabled()) + nImageStyle |= DrawImageFlags::Disable; + + if (aImageSize.Width() > aRectSize.Width() || + aImageSize.Height() > aRectSize.Height()) + { + maVirDev->SetClipRegion(vcl::Region(aRect)); + maVirDev->DrawImage(aPos, pItem->maImage, nImageStyle); + maVirDev->SetClipRegion(); + } + else + maVirDev->DrawImage(aPos, pItem->maImage, nImageStyle); + + if (pItem->meType == VALUESETITEM_IMAGE_AND_TEXT) + { + maVirDev->SetFont(rRenderContext.GetFont()); + maVirDev->SetTextColor((nStyle & WB_MENUSTYLEVALUESET) ? rStyleSettings.GetMenuTextColor() : rStyleSettings.GetWindowTextColor()); + maVirDev->SetTextFillColor(); + + long nTxtWidth = maVirDev->GetTextWidth(pItem->maText); + + if (nTxtWidth > aRect.GetWidth()) + maVirDev->SetClipRegion(vcl::Region(aRect)); + + maVirDev->DrawText(Point(aRect.Left() + + (aRect.GetWidth() - nTxtWidth) / 2, + aRect.Bottom() - maVirDev->GetTextHeight()), + pItem->maText); + + if (nTxtWidth > aRect.GetWidth()) + maVirDev->SetClipRegion(); + } + } + } + + const sal_uInt16 nEdgeBlendingPercent(GetEdgeBlending() ? rStyleSettings.GetEdgeBlending() : 0); + + if (nEdgeBlendingPercent) + { + const Color& rTopLeft(rStyleSettings.GetEdgeBlendingTopLeftColor()); + const Color& rBottomRight(rStyleSettings.GetEdgeBlendingBottomRightColor()); + const sal_uInt8 nAlpha((nEdgeBlendingPercent * 255) / 100); + const BitmapEx aBlendFrame(createBlendFrame(aRect.GetSize(), nAlpha, rTopLeft, rBottomRight)); + + if (!aBlendFrame.IsEmpty()) + { + maVirDev->DrawBitmapEx(aRect.TopLeft(), aBlendFrame); + } + } +} + +void ValueSet::ImplDrawItemText(vcl::RenderContext& rRenderContext, const OUString& rText) +{ + if (!(GetStyle() & WB_NAMEFIELD)) + return; + + Size aWinSize(GetOutputSizePixel()); + long nTxtWidth = rRenderContext.GetTextWidth(rText); + long nTxtOffset = mnTextOffset; + + // delete rectangle and show text + if (GetStyle() & WB_FLATVALUESET) + { + const StyleSettings& rStyleSettings = rRenderContext.GetSettings().GetStyleSettings(); + rRenderContext.SetLineColor(); + rRenderContext.SetFillColor(rStyleSettings.GetFaceColor()); + rRenderContext.DrawRect(tools::Rectangle(Point(0, nTxtOffset), Point(aWinSize.Width(), aWinSize.Height()))); + rRenderContext.SetTextColor(rStyleSettings.GetButtonTextColor()); + } + else + { + nTxtOffset += NAME_LINE_HEIGHT+NAME_LINE_OFF_Y; + rRenderContext.SetBackground(Application::GetSettings().GetStyleSettings().GetFaceColor()); + rRenderContext.Erase(tools::Rectangle(Point(0, nTxtOffset), Point(aWinSize.Width(), aWinSize.Height()))); + } + rRenderContext.DrawText(Point((aWinSize.Width() - nTxtWidth) / 2, nTxtOffset + (NAME_OFFSET / 2)), rText); +} + +void ValueSet::StyleUpdated() +{ + mbFormat = true; + CustomWidgetController::StyleUpdated(); +} + +void ValueSet::EnableFullItemMode( bool bFullMode ) +{ + mbFullMode = bFullMode; +} + +void ValueSet::SetColCount( sal_uInt16 nNewCols ) +{ + if ( mnUserCols != nNewCols ) + { + mnUserCols = nNewCols; + QueueReformat(); + } +} + +void ValueSet::SetItemImage( sal_uInt16 nItemId, const Image& rImage ) +{ + size_t nPos = GetItemPos( nItemId ); + + if ( nPos == VALUESET_ITEM_NOTFOUND ) + return; + + ValueSetItem* pItem = mItemList[nPos].get(); + pItem->meType = VALUESETITEM_IMAGE; + pItem->maImage = rImage; + + if ( !mbFormat && IsReallyVisible() && IsUpdateMode() ) + { + const tools::Rectangle aRect = ImplGetItemRect(nPos); + Invalidate(aRect); + } + else + mbFormat = true; +} + +void ValueSet::SetItemColor( sal_uInt16 nItemId, const Color& rColor ) +{ + size_t nPos = GetItemPos( nItemId ); + + if ( nPos == VALUESET_ITEM_NOTFOUND ) + return; + + ValueSetItem* pItem = mItemList[nPos].get(); + pItem->meType = VALUESETITEM_COLOR; + pItem->maColor = rColor; + + if ( !mbFormat && IsReallyVisible() && IsUpdateMode() ) + { + const tools::Rectangle aRect = ImplGetItemRect(nPos); + Invalidate( aRect ); + } + else + mbFormat = true; +} + +Color ValueSet::GetItemColor( sal_uInt16 nItemId ) const +{ + size_t nPos = GetItemPos( nItemId ); + + if ( nPos != VALUESET_ITEM_NOTFOUND ) + return mItemList[nPos]->maColor; + else + return Color(); +} + +Size ValueSet::CalcWindowSizePixel( const Size& rItemSize, sal_uInt16 nDesireCols, + sal_uInt16 nDesireLines ) const +{ + size_t nCalcCols = nDesireCols; + size_t nCalcLines = nDesireLines; + + if ( !nCalcCols ) + { + if ( mnUserCols ) + nCalcCols = mnUserCols; + else + nCalcCols = 1; + } + + if ( !nCalcLines ) + { + nCalcLines = mnVisLines; + + if ( mbFormat ) + { + if ( mnUserVisLines ) + nCalcLines = mnUserVisLines; + else + { + // Floor( (M+N-1)/N )==Ceiling( M/N ) + nCalcLines = (mItemList.size()+nCalcCols-1) / nCalcCols; + if ( !nCalcLines ) + nCalcLines = 1; + } + } + } + + Size aSize( rItemSize.Width() * nCalcCols, rItemSize.Height() * nCalcLines ); + WinBits nStyle = GetStyle(); + long nTxtHeight = GetTextHeight(); + long n; + + if ( nStyle & WB_ITEMBORDER ) + { + if ( nStyle & WB_DOUBLEBORDER ) + n = ITEM_OFFSET_DOUBLE; + else + n = ITEM_OFFSET; + + aSize.AdjustWidth(n * nCalcCols ); + aSize.AdjustHeight(n * nCalcLines ); + } + else + n = 0; + + if ( mnSpacing ) + { + aSize.AdjustWidth(mnSpacing * (nCalcCols - 1) ); + aSize.AdjustHeight(mnSpacing * (nCalcLines - 1) ); + } + + if ( nStyle & WB_NAMEFIELD ) + { + aSize.AdjustHeight(nTxtHeight + NAME_OFFSET ); + if ( !(nStyle & WB_FLATVALUESET) ) + aSize.AdjustHeight(NAME_LINE_HEIGHT + NAME_LINE_OFF_Y ); + } + + if ( nStyle & WB_NONEFIELD ) + { + aSize.AdjustHeight(nTxtHeight + n + mnSpacing ); + } + + return aSize; +} + +void ValueSet::InsertItem( sal_uInt16 nItemId, const Image& rImage ) +{ + std::unique_ptr<ValueSetItem> pItem(new ValueSetItem( *this )); + pItem->mnId = nItemId; + pItem->meType = VALUESETITEM_IMAGE; + pItem->maImage = rImage; + ImplInsertItem( std::move(pItem), VALUESET_APPEND ); +} + +void ValueSet::InsertItem( sal_uInt16 nItemId, const Image& rImage, + const OUString& rText, size_t nPos, + bool bShowLegend ) +{ + std::unique_ptr<ValueSetItem> pItem(new ValueSetItem( *this )); + pItem->mnId = nItemId; + pItem->meType = bShowLegend ? VALUESETITEM_IMAGE_AND_TEXT : VALUESETITEM_IMAGE; + pItem->maImage = rImage; + pItem->maText = rText; + ImplInsertItem( std::move(pItem), nPos ); +} + +void ValueSet::InsertItem( sal_uInt16 nItemId, size_t nPos ) +{ + std::unique_ptr<ValueSetItem> pItem(new ValueSetItem( *this )); + pItem->mnId = nItemId; + pItem->meType = VALUESETITEM_USERDRAW; + ImplInsertItem( std::move(pItem), nPos ); +} + +void ValueSet::InsertItem( sal_uInt16 nItemId, const Color& rColor, + const OUString& rText ) +{ + std::unique_ptr<ValueSetItem> pItem(new ValueSetItem( *this )); + pItem->mnId = nItemId; + pItem->meType = VALUESETITEM_COLOR; + pItem->maColor = rColor; + pItem->maText = rText; + ImplInsertItem( std::move(pItem), VALUESET_APPEND ); +} + +void ValueSet::ImplInsertItem( std::unique_ptr<ValueSetItem> pItem, const size_t nPos ) +{ + DBG_ASSERT( pItem->mnId, "ValueSet::InsertItem(): ItemId == 0" ); + DBG_ASSERT( GetItemPos( pItem->mnId ) == VALUESET_ITEM_NOTFOUND, + "ValueSet::InsertItem(): ItemId already exists" ); + + if ( nPos < mItemList.size() ) { + mItemList.insert( mItemList.begin() + nPos, std::move(pItem) ); + } else { + mItemList.push_back( std::move(pItem) ); + } + + QueueReformat(); +} + +int ValueSet::GetScrollWidth() const +{ + if (mxScrolledWindow) + return mxScrolledWindow->get_vscroll_width(); + return 0; +} + +void ValueSet::SetEdgeBlending(bool bNew) +{ + if(mbEdgeBlending != bNew) + { + mbEdgeBlending = bNew; + mbFormat = true; + + if (GetDrawingArea() && IsReallyVisible() && IsUpdateMode()) + { + Invalidate(); + } + } +} + +Size ValueSet::CalcItemSizePixel( const Size& rItemSize) const +{ + Size aSize = rItemSize; + + WinBits nStyle = GetStyle(); + if ( nStyle & WB_ITEMBORDER ) + { + long n; + + if ( nStyle & WB_DOUBLEBORDER ) + n = ITEM_OFFSET_DOUBLE; + else + n = ITEM_OFFSET; + + aSize.AdjustWidth(n ); + aSize.AdjustHeight(n ); + } + + return aSize; +} + +void ValueSet::SetLineCount( sal_uInt16 nNewLines ) +{ + if ( mnUserVisLines != nNewLines ) + { + mnUserVisLines = nNewLines; + QueueReformat(); + } +} + +void ValueSet::SetItemWidth( long nNewItemWidth ) +{ + if ( mnUserItemWidth != nNewItemWidth ) + { + mnUserItemWidth = nNewItemWidth; + QueueReformat(); + } +} + +//method to set accessible when the style is user draw. +void ValueSet::InsertItem( sal_uInt16 nItemId, const OUString& rText, size_t nPos ) +{ + DBG_ASSERT( nItemId, "ValueSet::InsertItem(): ItemId == 0" ); + DBG_ASSERT( GetItemPos( nItemId ) == VALUESET_ITEM_NOTFOUND, + "ValueSet::InsertItem(): ItemId already exists" ); + std::unique_ptr<ValueSetItem> pItem(new ValueSetItem( *this )); + pItem->mnId = nItemId; + pItem->meType = VALUESETITEM_USERDRAW; + pItem->maText = rText; + ImplInsertItem( std::move(pItem), nPos ); +} + +void ValueSet::SetItemHeight( long nNewItemHeight ) +{ + if ( mnUserItemHeight != nNewItemHeight ) + { + mnUserItemHeight = nNewItemHeight; + QueueReformat(); + } +} + +OUString ValueSet::RequestHelp(tools::Rectangle& rHelpRect) +{ + Point aPos = rHelpRect.TopLeft(); + const size_t nItemPos = ImplGetItem( aPos ); + OUString sRet; + if (nItemPos != VALUESET_ITEM_NOTFOUND) + { + rHelpRect = ImplGetItemRect(nItemPos); + sRet = GetItemText(ImplGetItem(nItemPos)->mnId); + } + return sRet; +} + +OUString ValueSet::GetItemText(sal_uInt16 nItemId) const +{ + const size_t nPos = GetItemPos(nItemId); + + if ( nPos != VALUESET_ITEM_NOTFOUND ) + return mItemList[nPos]->maText; + + return OUString(); +} + +void ValueSet::SetExtraSpacing( sal_uInt16 nNewSpacing ) +{ + if ( GetStyle() & WB_ITEMBORDER ) + { + mnSpacing = nNewSpacing; + QueueReformat(); + } +} + +void ValueSet::SetFormat() +{ + mbFormat = true; +} + +void ValueSet::SetItemData( sal_uInt16 nItemId, void* pData ) +{ + size_t nPos = GetItemPos( nItemId ); + + if ( nPos == VALUESET_ITEM_NOTFOUND ) + return; + + ValueSetItem* pItem = mItemList[nPos].get(); + pItem->mpData = pData; + + if ( pItem->meType == VALUESETITEM_USERDRAW ) + { + if ( !mbFormat && IsReallyVisible() && IsUpdateMode() ) + { + const tools::Rectangle aRect = ImplGetItemRect(nPos); + Invalidate(aRect); + } + else + mbFormat = true; + } +} + +void* ValueSet::GetItemData( sal_uInt16 nItemId ) const +{ + size_t nPos = GetItemPos( nItemId ); + + if ( nPos != VALUESET_ITEM_NOTFOUND ) + return mItemList[nPos]->mpData; + else + return nullptr; +} + +void ValueSet::SetItemText(sal_uInt16 nItemId, const OUString& rText) +{ + size_t nPos = GetItemPos( nItemId ); + + if ( nPos == VALUESET_ITEM_NOTFOUND ) + return; + + ValueSetItem* pItem = mItemList[nPos].get(); + + // Remember old and new name for accessibility event. + Any aOldName; + Any aNewName; + OUString sString (pItem->maText); + aOldName <<= sString; + sString = rText; + aNewName <<= sString; + + pItem->maText = rText; + + if (!mbFormat && IsReallyVisible() && IsUpdateMode()) + { + sal_uInt16 nTempId = mnSelItemId; + + if (mbHighlight) + nTempId = mnHighItemId; + + if (nTempId == nItemId) + Invalidate(); + } + + if (ImplHasAccessibleListeners()) + { + Reference<XAccessible> xAccessible(pItem->GetAccessible( false/*bIsTransientChildrenDisabled*/)); + ValueItemAcc* pValueItemAcc = static_cast<ValueItemAcc*>(xAccessible.get()); + pValueItemAcc->FireAccessibleEvent(AccessibleEventId::NAME_CHANGED, aOldName, aNewName); + } +} + +Size ValueSet::GetLargestItemSize() +{ + Size aLargestItem; + + for (const std::unique_ptr<ValueSetItem>& pItem : mItemList) + { + if (!pItem->mbVisible) + continue; + + if (pItem->meType != VALUESETITEM_IMAGE && + pItem->meType != VALUESETITEM_IMAGE_AND_TEXT) + { + // handle determining an optimal size for this case + continue; + } + + Size aSize = pItem->maImage.GetSizePixel(); + if (pItem->meType == VALUESETITEM_IMAGE_AND_TEXT) + { + aSize.AdjustHeight(3 * NAME_LINE_HEIGHT + + maVirDev->GetTextHeight() ); + aSize.setWidth( std::max(aSize.Width(), + maVirDev->GetTextWidth(pItem->maText) + NAME_OFFSET) ); + } + + aLargestItem.setWidth( std::max(aLargestItem.Width(), aSize.Width()) ); + aLargestItem.setHeight( std::max(aLargestItem.Height(), aSize.Height()) ); + } + + return aLargestItem; +} + +void ValueSet::SetOptimalSize() +{ + Size aLargestSize(GetLargestItemSize()); + aLargestSize.setWidth(std::max(aLargestSize.Width(), mnUserItemWidth)); + aLargestSize.setHeight(std::max(aLargestSize.Height(), mnUserItemHeight)); + Size aPrefSize(CalcWindowSizePixel(aLargestSize)); + GetDrawingArea()->set_size_request(aPrefSize.Width(), aPrefSize.Height()); +} + +Image ValueSet::GetItemImage(sal_uInt16 nItemId) const +{ + size_t nPos = GetItemPos( nItemId ); + + if ( nPos != VALUESET_ITEM_NOTFOUND ) + return mItemList[nPos]->maImage; + else + return Image(); +} + +void ValueSet::SetColor(const Color& rColor) +{ + maColor = rColor; + mbFormat = true; + if (IsReallyVisible() && IsUpdateMode()) + Invalidate(); +} + +void ValueSet::Show() +{ + if (mxScrolledWindow) + mxScrolledWindow->show(); + CustomWidgetController::Show(); +} + +void ValueSet::Hide() +{ + CustomWidgetController::Hide(); + if (mxScrolledWindow) + mxScrolledWindow->hide(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/dialogs/PlaceEditDialog.cxx b/svtools/source/dialogs/PlaceEditDialog.cxx new file mode 100644 index 000000000..b41f16072 --- /dev/null +++ b/svtools/source/dialogs/PlaceEditDialog.cxx @@ -0,0 +1,376 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.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 <config_oauth2.h> + +#include <svtools/PlaceEditDialog.hxx> + +#include <com/sun/star/uno/Sequence.hxx> +#include <officecfg/Office/Common.hxx> +#include <svtools/svtresid.hxx> +#include <svtools/strings.hrc> +#include <svtools/place.hxx> + +#include "ServerDetailsControls.hxx" + +using namespace com::sun::star::uno; + +PlaceEditDialog::PlaceEditDialog(weld::Window* pParent) + : GenericDialogController(pParent, "svt/ui/placeedit.ui", "PlaceEditDialog") + , m_xCurrentDetails() + , m_nCurrentType( 0 ) + , m_bLabelChanged( false ) + , m_bShowPassword( true ) + , m_xEDServerName(m_xBuilder->weld_entry("name")) + , m_xLBServerType(m_xBuilder->weld_combo_box("type")) + , m_xEDUsername(m_xBuilder->weld_entry("login")) + , m_xFTUsernameLabel(m_xBuilder->weld_label("loginLabel")) + , m_xBTOk(m_xBuilder->weld_button("ok")) + , m_xBTCancel(m_xBuilder->weld_button("cancel")) + , m_xBTDelete(m_xBuilder->weld_button("delete")) + , m_xBTRepoRefresh(m_xBuilder->weld_button("repositoriesRefresh")) + , m_xCBPassword(m_xBuilder->weld_check_button("rememberPassword")) + , m_xEDPassword(m_xBuilder->weld_entry("password")) + , m_xFTPasswordLabel(m_xBuilder->weld_label("passwordLabel")) + , m_xTypeGrid(m_xBuilder->weld_widget("TypeGrid")) + + , m_xRepositoryBox(m_xBuilder->weld_widget("RepositoryDetails")) + , m_xFTRepository(m_xBuilder->weld_label("repositoryLabel")) + , m_xLBRepository(m_xBuilder->weld_combo_box("repositories")) + + , m_xEDShare(m_xBuilder->weld_entry("share")) + , m_xFTShare(m_xBuilder->weld_label("shareLabel")) + + , m_xDetailsGrid(m_xBuilder->weld_widget("Details")) + , m_xHostBox(m_xBuilder->weld_widget("HostDetails")) + , m_xEDHost(m_xBuilder->weld_entry("host")) + , m_xFTHost(m_xBuilder->weld_label("hostLabel")) + , m_xEDPort(m_xBuilder->weld_spin_button("port")) + , m_xFTPort(m_xBuilder->weld_label("portLabel")) + , m_xEDRoot(m_xBuilder->weld_entry("path")) + , m_xFTRoot(m_xBuilder->weld_label("pathLabel")) + + , m_xCBDavs(m_xBuilder->weld_check_button("webdavs")) +{ + m_xBTOk->connect_clicked( LINK( this, PlaceEditDialog, OKHdl) ); + m_xBTOk->set_sensitive( false ); + + m_xEDServerName->connect_changed( LINK( this, PlaceEditDialog, EditLabelHdl) ); + + // This constructor is called when user request a place creation, so + // delete button is hidden. + m_xBTDelete->hide(); + + m_xLBServerType->connect_changed( LINK( this, PlaceEditDialog, SelectTypeHdl ) ); + m_xEDUsername->connect_changed( LINK( this, PlaceEditDialog, EditUsernameHdl ) ); + m_xEDPassword->connect_changed( LINK( this, PlaceEditDialog, EditUsernameHdl ) ); + + InitDetails( ); +} + +PlaceEditDialog::PlaceEditDialog(weld::Window* pParent, const std::shared_ptr<Place>& rPlace) + : GenericDialogController(pParent, "svt/ui/placeedit.ui", "PlaceEditDialog") + , m_xCurrentDetails( ) + , m_bLabelChanged( true ) + , m_bShowPassword( false ) + , m_xEDServerName(m_xBuilder->weld_entry("name")) + , m_xLBServerType(m_xBuilder->weld_combo_box("type")) + , m_xEDUsername(m_xBuilder->weld_entry("login")) + , m_xFTUsernameLabel(m_xBuilder->weld_label("loginLabel")) + , m_xBTOk(m_xBuilder->weld_button("ok")) + , m_xBTCancel(m_xBuilder->weld_button("cancel")) + , m_xBTDelete(m_xBuilder->weld_button("delete")) + , m_xBTRepoRefresh(m_xBuilder->weld_button("repositoriesRefresh")) + , m_xCBPassword(m_xBuilder->weld_check_button("rememberPassword")) + , m_xEDPassword(m_xBuilder->weld_entry("password")) + , m_xFTPasswordLabel(m_xBuilder->weld_label("passwordLabel")) + , m_xTypeGrid(m_xBuilder->weld_widget("TypeGrid")) + + , m_xRepositoryBox(m_xBuilder->weld_widget("RepositoryDetails")) + , m_xFTRepository(m_xBuilder->weld_label("repositoryLabel")) + , m_xLBRepository(m_xBuilder->weld_combo_box("repositories")) + + , m_xEDShare(m_xBuilder->weld_entry("share")) + , m_xFTShare(m_xBuilder->weld_label("shareLabel")) + + , m_xDetailsGrid(m_xBuilder->weld_widget("Details")) + , m_xHostBox(m_xBuilder->weld_widget("HostDetails")) + , m_xEDHost(m_xBuilder->weld_entry("host")) + , m_xFTHost(m_xBuilder->weld_label("hostLabel")) + , m_xEDPort(m_xBuilder->weld_spin_button("port")) + , m_xFTPort(m_xBuilder->weld_label("portLabel")) + , m_xEDRoot(m_xBuilder->weld_entry("path")) + , m_xFTRoot(m_xBuilder->weld_label("pathLabel")) + + , m_xCBDavs(m_xBuilder->weld_check_button("webdavs")) +{ + m_xEDPassword->hide(); + m_xFTPasswordLabel->hide(); + m_xCBPassword->hide(); + + m_xBTOk->connect_clicked( LINK( this, PlaceEditDialog, OKHdl) ); + m_xBTDelete->connect_clicked( LINK( this, PlaceEditDialog, DelHdl) ); + + m_xEDServerName->connect_changed( LINK( this, PlaceEditDialog, ModifyHdl) ); + m_xLBServerType->connect_changed( LINK( this, PlaceEditDialog, SelectTypeHdl ) ); + + InitDetails( ); + + m_xEDServerName->set_text(rPlace->GetName()); + + // Fill the boxes with the URL parts + bool bSuccess = false; + for (size_t i = 0 ; i < m_aDetailsContainers.size( ) && !bSuccess; ++i) + { + INetURLObject& rUrl = rPlace->GetUrlObject(); + bSuccess = m_aDetailsContainers[i]->setUrl( rUrl ); + if ( bSuccess ) + { + // Fill the Username field + if ( rUrl.HasUserData( ) ) + { + m_xEDUsername->set_text( rUrl.GetUser(INetURLObject::DecodeMechanism::WithCharset) ); + m_aDetailsContainers[i]->setUsername( rUrl.GetUser(INetURLObject::DecodeMechanism::WithCharset) ); + } + + m_xLBServerType->set_active(i); + SelectType(true); + } + } + + // In edit mode user can't change connection type + m_xTypeGrid->hide(); +} + +PlaceEditDialog::~PlaceEditDialog() +{ +} + +OUString PlaceEditDialog::GetServerUrl() +{ + OUString sUrl; + if (m_xCurrentDetails) + { + INetURLObject aUrl = m_xCurrentDetails->getUrl(); + OUString sUsername = m_xEDUsername->get_text().trim(); + if ( !sUsername.isEmpty( ) ) + aUrl.SetUser( sUsername ); + if ( !aUrl.HasError( ) ) + sUrl = aUrl.GetMainURL( INetURLObject::DecodeMechanism::NONE ); + } + + return sUrl; +} + +std::shared_ptr<Place> PlaceEditDialog::GetPlace() +{ + return std::make_shared<Place>(m_xEDServerName->get_text(), GetServerUrl(), true); +} + +void PlaceEditDialog::InitDetails( ) +{ + // Create CMIS controls for each server type + + Reference< XComponentContext > xContext = ::comphelper::getProcessComponentContext(); + + // Load the ServerType entries + bool bSkipGDrive = OUString( GDRIVE_CLIENT_ID ).isEmpty() || + OUString( GDRIVE_CLIENT_SECRET ).isEmpty(); + bool bSkipAlfresco = OUString( ALFRESCO_CLOUD_CLIENT_ID ).isEmpty() || + OUString( ALFRESCO_CLOUD_CLIENT_SECRET ).isEmpty(); + bool bSkipOneDrive= OUString( ONEDRIVE_CLIENT_ID ).isEmpty() || + OUString( ONEDRIVE_CLIENT_SECRET ).isEmpty(); + + Sequence< OUString > aTypesUrlsList( officecfg::Office::Common::Misc::CmisServersUrls::get( xContext ) ); + Sequence< OUString > aTypesNamesList( officecfg::Office::Common::Misc::CmisServersNames::get( xContext ) ); + + int nPos = 0; + auto nSize = std::min(aTypesUrlsList.getLength(), aTypesNamesList.getLength()); + for ( sal_Int32 i = 0; i < nSize; ++i ) + { + OUString sUrl = aTypesUrlsList[i].replaceFirst("<host", "<" + SvtResId(STR_SVT_HOST)).replaceFirst("port>", SvtResId(STR_SVT_PORT) + ">"); + + if ((sUrl == GDRIVE_BASE_URL && bSkipGDrive) || + (sUrl.startsWith( ALFRESCO_CLOUD_BASE_URL) && bSkipAlfresco) || + (sUrl == ONEDRIVE_BASE_URL && bSkipOneDrive)) + { + // this service is not supported + continue; + } + + m_xLBServerType->insert_text(nPos, aTypesNamesList[i].replaceFirst("Other CMIS", SvtResId(STR_SVT_OTHER_CMIS))); + + std::shared_ptr<DetailsContainer> xCmisDetails(std::make_shared<CmisDetailsContainer>(this, sUrl)); + xCmisDetails->setChangeHdl( LINK( this, PlaceEditDialog, EditHdl ) ); + m_aDetailsContainers.push_back(xCmisDetails); + + ++nPos; + } + + // Create WebDAV / FTP / SSH details control + std::shared_ptr<DetailsContainer> xDavDetails(std::make_shared<DavDetailsContainer>(this)); + xDavDetails->setChangeHdl( LINK( this, PlaceEditDialog, EditHdl ) ); + m_aDetailsContainers.push_back(xDavDetails); + + std::shared_ptr<DetailsContainer> xFtpDetails(std::make_shared<HostDetailsContainer>(this, 21, "ftp")); + xFtpDetails->setChangeHdl( LINK( this, PlaceEditDialog, EditHdl ) ); + m_aDetailsContainers.push_back(xFtpDetails); + + std::shared_ptr<DetailsContainer> xSshDetails(std::make_shared<HostDetailsContainer>(this, 22, "ssh")); + xSshDetails->setChangeHdl( LINK( this, PlaceEditDialog, EditHdl ) ); + m_aDetailsContainers.push_back(xSshDetails); + + // Remove Windows Share entry from dialog on Windows OS, where it's non-functional +#if defined(_WIN32) + // nPos is the position of first item that is pre-defined in svtools/uiconfig/ui/placeedit.ui, + // after other CMIS types were inserted + m_xLBServerType->remove(nPos + 3); +#else + // Create Windows Share control + std::shared_ptr<DetailsContainer> xSmbDetails(std::make_shared<SmbDetailsContainer>(this)); + xSmbDetails->setChangeHdl( LINK( this, PlaceEditDialog, EditHdl ) ); + m_aDetailsContainers.push_back(xSmbDetails); +#endif + + // Set default to first value + m_xLBServerType->set_active(0); + + if (m_xLBServerType->get_active_text() == "--------------------" ) + m_xLBServerType->set_active(1); + + SelectType(true); +} + +IMPL_LINK( PlaceEditDialog, OKHdl, weld::Button&, /*rBtn*/, void) +{ + if ( !m_xCurrentDetails ) + return; + + OUString sUrl = m_xCurrentDetails->getUrl().GetHost( INetURLObject::DecodeMechanism::WithCharset ); + + if ( sUrl.startsWith( GDRIVE_BASE_URL ) + || sUrl.startsWith( ALFRESCO_CLOUD_BASE_URL ) + || sUrl.startsWith( ONEDRIVE_BASE_URL ) ) + { + m_xBTRepoRefresh->clicked(); + + sUrl = m_xCurrentDetails->getUrl().GetHost( INetURLObject::DecodeMechanism::WithCharset ); + INetURLObject aHostUrl( sUrl ); + OUString sRepoId = aHostUrl.GetMark(); + + if ( !sRepoId.isEmpty() ) + { + m_xDialog->response(RET_OK); + } + else + { + // TODO: repository id missing. Auth error? + } + } + else + { + m_xDialog->response(RET_OK); + } +} + +IMPL_LINK( PlaceEditDialog, DelHdl, weld::Button&, /*rButton*/, void) +{ + // ReUsing existing symbols... + m_xDialog->response(RET_NO); +} + +IMPL_LINK_NOARG( PlaceEditDialog, EditHdl, DetailsContainer*, void ) +{ + if( !m_bLabelChanged ) + { + if( !m_xEDUsername->get_text().isEmpty( ) ) + { + OUString sLabel = SvtResId( STR_SVT_DEFAULT_SERVICE_LABEL ); + OUString sUser = m_xEDUsername->get_text(); + + int nLength = sUser.indexOf( '@' ); + if( nLength < 0 ) + nLength = sUser.getLength(); + + sLabel = sLabel.replaceFirst( "$user$", sUser.copy( 0, nLength ) ); + sLabel = sLabel.replaceFirst( "$service$", m_xLBServerType->get_active_text() ); + + m_xEDServerName->set_text( sLabel ); + m_bLabelChanged = false; + } + else + { + m_xEDServerName->set_text( m_xLBServerType->get_active_text( ) ); + } + } + + OUString sUrl = GetServerUrl( ); + OUString sName = m_xEDServerName->get_text().trim(); + m_xBTOk->set_sensitive( !sName.isEmpty( ) && !sUrl.isEmpty( ) ); +} + +IMPL_LINK_NOARG( PlaceEditDialog, ModifyHdl, weld::Entry&, void ) +{ + EditHdl(nullptr); +} + +IMPL_LINK_NOARG( PlaceEditDialog, EditLabelHdl, weld::Entry&, void ) +{ + m_bLabelChanged = true; + EditHdl(nullptr); +} + +IMPL_LINK_NOARG( PlaceEditDialog, EditUsernameHdl, weld::Entry&, void ) +{ + for ( auto& rxDetailsContainer : m_aDetailsContainers ) + { + rxDetailsContainer->setUsername( m_xEDUsername->get_text() ); + rxDetailsContainer->setPassword( m_xEDPassword->get_text() ); + } + + EditHdl(nullptr); +} + +IMPL_LINK_NOARG( PlaceEditDialog, SelectTypeHdl, weld::ComboBox&, void ) +{ + SelectType(false); +} + +void PlaceEditDialog::SelectType(bool bSkipSeparator) +{ + if ( m_xLBServerType->get_active_text() == "--------------------" ) + { + if (bSkipSeparator) + m_xLBServerType->set_active(m_nCurrentType); + else + m_xLBServerType->set_active(-1); + return; + } + + if (m_xCurrentDetails) + m_xCurrentDetails->set_visible(false); + + const int nPos = m_xLBServerType->get_active( ); + m_xCurrentDetails = m_aDetailsContainers[nPos]; + m_nCurrentType = nPos; + + m_xCurrentDetails->set_visible(true); + + m_xCBPassword->set_visible( m_bShowPassword && m_xCurrentDetails->enableUserCredentials() ); + m_xEDPassword->set_visible( m_bShowPassword && m_xCurrentDetails->enableUserCredentials() ); + m_xFTPasswordLabel->set_visible( m_bShowPassword && m_xCurrentDetails->enableUserCredentials() ); + m_xEDUsername->set_visible( m_xCurrentDetails->enableUserCredentials() ); + m_xFTUsernameLabel->set_visible( m_xCurrentDetails->enableUserCredentials() ); + + m_xDialog->resize_to_request(); + + EditHdl(nullptr); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/dialogs/ServerDetailsControls.cxx b/svtools/source/dialogs/ServerDetailsControls.cxx new file mode 100644 index 000000000..339704dc6 --- /dev/null +++ b/svtools/source/dialogs/ServerDetailsControls.cxx @@ -0,0 +1,494 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.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 <com/sun/star/lang/XMultiServiceFactory.hpp> +#include <com/sun/star/task/InteractionHandler.hpp> +#include <com/sun/star/task/PasswordContainer.hpp> +#include <com/sun/star/task/XPasswordContainer2.hpp> +#include <com/sun/star/ucb/XCommandEnvironment.hpp> +#include <com/sun/star/ucb/XContentAccess.hpp> +#include <com/sun/star/sdbc/XResultSet.hpp> +#include <com/sun/star/sdbc/XRow.hpp> + +#include <comphelper/processfactory.hxx> +#include <o3tl/safeint.hxx> +#include <rtl/uri.hxx> +#include <ucbhelper/content.hxx> +#include <ucbhelper/commandenvironment.hxx> +#include <tools/diagnose_ex.h> + +#include <svtools/PlaceEditDialog.hxx> +#include <config_oauth2.h> + +#include "ServerDetailsControls.hxx" + +using namespace std; +using namespace com::sun::star::lang; +using namespace com::sun::star::sdbc; +using namespace com::sun::star::task; +using namespace com::sun::star::ucb; +using namespace com::sun::star::uno; + +DetailsContainer::DetailsContainer(PlaceEditDialog* pDialog) + : m_pDialog(pDialog) +{ + m_pDialog->m_xEDPort->connect_output(LINK(this, DetailsContainer, FormatPortHdl)); +} + +//format without thousand separator +IMPL_STATIC_LINK(DetailsContainer, FormatPortHdl, weld::SpinButton&, rSpinButton, void) +{ + rSpinButton.set_text(OUString::number(rSpinButton.get_value())); +} + +DetailsContainer::~DetailsContainer( ) +{ +} + +void DetailsContainer::set_visible( bool ) +{ + m_pDialog->m_xDetailsGrid->set_sensitive(true); + + m_pDialog->m_xEDHost->connect_changed( LINK( this, DetailsContainer, ValueChangeHdl ) ); + m_pDialog->m_xEDPort->connect_changed( LINK( this, DetailsContainer, ValueChangeHdl ) ); + m_pDialog->m_xEDRoot->connect_changed( LINK( this, DetailsContainer, ValueChangeHdl ) ); +} + +INetURLObject DetailsContainer::getUrl( ) +{ + // Don't use that class directly: make it smarter by subclassing it. + return INetURLObject( ); +} + +bool DetailsContainer::setUrl( const INetURLObject& ) +{ + // That class doesn't contain any logic... it defers the dirty work + // to the sub classes. + return false; +} + +void DetailsContainer::notifyChange( ) +{ + m_aChangeHdl.Call( this ); +} + +IMPL_LINK_NOARG( DetailsContainer, ValueChangeHdl, weld::Entry&, void ) +{ + notifyChange( ); +} + +HostDetailsContainer::HostDetailsContainer(PlaceEditDialog* pDialog, sal_uInt16 nPort, const OUString& sScheme) : + DetailsContainer( pDialog ), + m_nDefaultPort( nPort ), + m_sScheme( sScheme ) +{ + set_visible( false ); +} + +void HostDetailsContainer::set_visible( bool bShow ) +{ + m_pDialog->m_xFTHost->set_visible( bShow ); + m_pDialog->m_xHostBox->set_visible( bShow ); + m_pDialog->m_xEDRoot->set_visible( bShow ); + m_pDialog->m_xFTRoot->set_visible( bShow ); + + DetailsContainer::set_visible( bShow ); + + if ( bShow ) + { + if (m_pDialog->m_xEDPort->get_value() == 0) + m_pDialog->m_xEDPort->set_value( m_nDefaultPort ); + m_pDialog->m_xEDHost->set_text( m_sHost ); + } + else + m_pDialog->m_xEDPort->set_value( 0 ); +} + +INetURLObject HostDetailsContainer::getUrl( ) +{ + OUString sHost = m_pDialog->m_xEDHost->get_text().trim(); + sal_Int64 nPort = m_pDialog->m_xEDPort->get_value(); + OUString sPath = m_pDialog->m_xEDRoot->get_text().trim(); + + OUString sUrl; + if ( !sHost.isEmpty( ) ) + { + sUrl = m_sScheme + "://" + sHost; + if ( nPort != m_nDefaultPort ) + sUrl += ":" + OUString::number( nPort ); + if ( !sPath.isEmpty( ) ) + if ( sPath.indexOf( '/' ) != 0 ) + sUrl += "/"; + sUrl += sPath; + } + + return INetURLObject( sUrl ); +} + +bool HostDetailsContainer::setUrl( const INetURLObject& rUrl ) +{ + bool bSuccess = verifyScheme( INetURLObject::GetScheme( rUrl.GetProtocol( ) ) ); + + if ( bSuccess ) + { + m_sHost = rUrl.GetHost( ); + m_pDialog->m_xEDHost->set_text( rUrl.GetHost( ) ); + m_pDialog->m_xEDPort->set_value( rUrl.GetPort( ) ); + m_pDialog->m_xEDRoot->set_text( rUrl.GetURLPath() ); + } + + return bSuccess; +} + +bool HostDetailsContainer::verifyScheme( const OUString& sScheme ) +{ + return sScheme == ( m_sScheme + "://" ); +} + +DavDetailsContainer::DavDetailsContainer(PlaceEditDialog* pBuilder) + : HostDetailsContainer(pBuilder, 80, "http") +{ + m_pDialog->m_xCBDavs->connect_toggled(LINK(this, DavDetailsContainer, ToggledDavsHdl)); + + set_visible( false ); +} + +void DavDetailsContainer::set_visible( bool bShow ) +{ + HostDetailsContainer::set_visible( bShow ); + + if ( !bShow ) + m_pDialog->m_xCBDavs->set_active(false); + + m_pDialog->m_xCBDavs->set_visible(bShow); +} + +bool DavDetailsContainer::verifyScheme( const OUString& rScheme ) +{ + bool bValid = false; + if ( rScheme == "http://" ) + { + bValid = true; + m_pDialog->m_xCBDavs->set_active(false); + } + else if ( rScheme == "https://" ) + { + bValid = true; + m_pDialog->m_xCBDavs->set_active(true); + } + return bValid; +} + +IMPL_LINK( DavDetailsContainer, ToggledDavsHdl, weld::ToggleButton&, rCheckBox, void ) +{ + // Change default port if needed + bool bCheckedDavs = rCheckBox.get_active(); + if ( m_pDialog->m_xEDPort->get_value() == 80 && bCheckedDavs ) + m_pDialog->m_xEDPort->set_value( 443 ); + else if ( m_pDialog->m_xEDPort->get_value() == 443 && !bCheckedDavs ) + m_pDialog->m_xEDPort->set_value( 80 ); + + OUString sScheme( "http" ); + if ( bCheckedDavs ) + sScheme = "https"; + setScheme( sScheme ); + + notifyChange( ); +} + +SmbDetailsContainer::SmbDetailsContainer(PlaceEditDialog* pDialog) + : DetailsContainer(pDialog) +{ + m_pDialog->m_xEDShare->connect_changed( LINK( this, DetailsContainer, ValueChangeHdl ) ); + + set_visible( false ); +} + +INetURLObject SmbDetailsContainer::getUrl( ) +{ + OUString sHost = m_pDialog->m_xEDHost->get_text().trim( ); + OUString sShare = m_pDialog->m_xEDShare->get_text().trim( ); + OUString sPath = m_pDialog->m_xEDRoot->get_text().trim( ); + + OUString sUrl; + if ( !sHost.isEmpty( ) ) + { + sUrl = "smb://" + sHost + "/"; + if ( !sShare.isEmpty( ) ) + sUrl += sShare; + if ( !sPath.isEmpty( ) ) + if ( sPath.indexOf( '/' ) != 0 ) + sUrl += "/"; + sUrl += sPath; + } + + return INetURLObject( sUrl ); +} + +bool SmbDetailsContainer::setUrl( const INetURLObject& rUrl ) +{ + bool bSuccess = rUrl.GetProtocol() == INetProtocol::Smb; + + if ( bSuccess ) + { + OUString sShare = rUrl.getName( 0 ); + OUString sFullPath = rUrl.GetURLPath( ); + OUString sPath; + if ( sFullPath.getLength( ) > sShare.getLength( ) ) + { + sal_Int32 nPos = sShare.getLength( ); + if ( nPos != 0 ) + ++nPos; + sPath = sFullPath.copy( nPos ); + } + + m_sHost = rUrl.GetHost( ); + m_pDialog->m_xEDHost->set_text( m_sHost ); + m_pDialog->m_xEDShare->set_text( sShare ); + m_pDialog->m_xEDRoot->set_text( sPath ); + } + + return bSuccess; +} + +void SmbDetailsContainer::set_visible( bool bShow ) +{ + m_pDialog->m_xEDShare->set_visible( bShow ); + m_pDialog->m_xFTShare->set_visible( bShow ); + m_pDialog->m_xEDRoot->set_visible( bShow ); + m_pDialog->m_xFTRoot->set_visible( bShow ); + + m_pDialog->m_xFTHost->set_visible( bShow ); + m_pDialog->m_xHostBox->set_visible( bShow ); + m_pDialog->m_xEDPort->set_sensitive( !bShow ); + m_pDialog->m_xFTPort->set_sensitive( !bShow ); + + if ( bShow ) + m_pDialog->m_xEDHost->set_text( m_sHost ); +} + +CmisDetailsContainer::CmisDetailsContainer(PlaceEditDialog* pParentDialog, OUString const & sBinding) : + DetailsContainer( pParentDialog ), + m_sUsername( ), + m_xCmdEnv( ), + m_aRepoIds( ), + m_sRepoId( ), + m_sBinding( sBinding ), + m_xParentDialog(pParentDialog->getDialog()->GetXWindow()) +{ + Reference< XComponentContext > xContext = ::comphelper::getProcessComponentContext(); + Reference< XInteractionHandler > xGlobalInteractionHandler = + InteractionHandler::createWithParent(xContext, m_xParentDialog); + m_xCmdEnv = new ucbhelper::CommandEnvironment( xGlobalInteractionHandler, Reference< XProgressHandler >() ); + + set_visible( false ); +} + +void CmisDetailsContainer::set_visible( bool bShow ) +{ + m_pDialog->m_xLBRepository->connect_changed( LINK( this, CmisDetailsContainer, SelectRepoHdl ) ); + m_pDialog->m_xBTRepoRefresh->connect_clicked( LINK( this, CmisDetailsContainer, RefreshReposHdl ) ); + + m_pDialog->m_xEDHost->set_text( m_sBinding ); + + if( ( m_sBinding == GDRIVE_BASE_URL ) + || m_sBinding.startsWith( ALFRESCO_CLOUD_BASE_URL ) + || ( m_sBinding == ONEDRIVE_BASE_URL ) ) + { + m_pDialog->m_xFTHost->hide(); + m_pDialog->m_xHostBox->hide(); + m_pDialog->m_xFTRepository->hide(); + m_pDialog->m_xRepositoryBox->hide(); + m_pDialog->m_xEDRoot->hide(); + m_pDialog->m_xFTRoot->hide(); + } + else + { + m_pDialog->m_xFTHost->set_visible( bShow ); + m_pDialog->m_xHostBox->set_visible( bShow ); + m_pDialog->m_xFTRepository->set_visible( bShow ); + m_pDialog->m_xRepositoryBox->set_visible( bShow ); + m_pDialog->m_xEDRoot->set_visible( bShow ); + m_pDialog->m_xFTRoot->set_visible( bShow ); + } + + DetailsContainer::set_visible( bShow ); + m_pDialog->m_xEDPort->set_sensitive( !bShow ); + m_pDialog->m_xFTPort->set_sensitive( !bShow ); +} + +INetURLObject CmisDetailsContainer::getUrl( ) +{ + OUString sBindingUrl = m_pDialog->m_xEDHost->get_text().trim(); + OUString sPath = m_pDialog->m_xEDRoot->get_text().trim(); + + bool bSkip = true; + if( ( m_sBinding == GDRIVE_BASE_URL ) + || m_sBinding.startsWith( ALFRESCO_CLOUD_BASE_URL ) + || ( m_sBinding == ONEDRIVE_BASE_URL ) ) + { + bSkip = m_sUsername.isEmpty(); + } + else + { + bSkip = m_sRepoId.isEmpty(); + } + + OUString sUrl; + if ( !sBindingUrl.isEmpty( ) && !bSkip ) + { + OUString sEncodedBinding = rtl::Uri::encode( + sBindingUrl + "#" + m_sRepoId, + rtl_UriCharClassRelSegment, + rtl_UriEncodeKeepEscapes, + RTL_TEXTENCODING_UTF8 ); + sUrl = "vnd.libreoffice.cmis://" + sEncodedBinding; + } + sUrl += sPath; + + return INetURLObject( sUrl ); +} + +bool CmisDetailsContainer::setUrl( const INetURLObject& rUrl ) +{ + bool bSuccess = rUrl.GetProtocol() == INetProtocol::Cmis; + + if ( bSuccess ) + { + OUString sDecodedHost = rUrl.GetHost( INetURLObject::DecodeMechanism::WithCharset ); + INetURLObject aHostUrl( sDecodedHost ); + m_sBinding = aHostUrl.GetURLNoMark( ); + m_sRepoId = aHostUrl.GetMark( ); + + m_pDialog->m_xEDHost->set_text( m_sBinding ); + m_pDialog->m_xEDRoot->set_text( rUrl.GetURLPath() ); + } + return bSuccess; +} + +void CmisDetailsContainer::setUsername( const OUString& rUsername ) +{ + m_sUsername = rUsername; +} + +void CmisDetailsContainer::setPassword( const OUString& rPass ) +{ + m_sPassword = rPass; +} + +void CmisDetailsContainer::selectRepository( ) +{ + // Get the repo ID and call the Change listener + const int nPos = m_pDialog->m_xLBRepository->get_active(); + if( o3tl::make_unsigned(nPos) < m_aRepoIds.size() ) + { + m_sRepoId = m_aRepoIds[nPos]; + notifyChange( ); + } +} + +IMPL_LINK_NOARG( CmisDetailsContainer, RefreshReposHdl, weld::Button&, void ) +{ + Reference< XComponentContext > xContext = ::comphelper::getProcessComponentContext(); + Reference< XPasswordContainer2 > xMasterPasswd = PasswordContainer::create( xContext ); + + + OUString sBindingUrl = m_pDialog->m_xEDHost->get_text().trim( ); + + OUString sEncodedUsername = ""; + + if ( !m_sUsername.isEmpty( ) ) + { + sEncodedUsername = rtl::Uri::encode(m_sUsername, + rtl_UriCharClassUserinfo, + rtl_UriEncodeKeepEscapes, + RTL_TEXTENCODING_UTF8 ) + + "@"; + } + + // Clean the listbox + m_pDialog->m_xLBRepository->clear(); + m_aRepoIds.clear(); + + // Compute the URL + OUString sUrl; + if ( !sBindingUrl.isEmpty( ) ) + { + OUString sEncodedBinding = rtl::Uri::encode( + sBindingUrl, + rtl_UriCharClassRelSegment, + rtl_UriEncodeKeepEscapes, + RTL_TEXTENCODING_UTF8 ); + sUrl = "vnd.libreoffice.cmis://" + sEncodedUsername + sEncodedBinding; + } + + // temporary remember the password + try + { + if( !sUrl.isEmpty() && !m_sUsername.isEmpty() && !m_sPassword.isEmpty() ) + { + Reference< XInteractionHandler > xInteractionHandler = + InteractionHandler::createWithParent(xContext, m_xParentDialog); + + Sequence<OUString> aPasswd { m_sPassword }; + + xMasterPasswd->add( + sUrl, m_sUsername, aPasswd, xInteractionHandler ); + } + } + catch( const Exception& ) + {} + + try + { + // Get the Content + ::ucbhelper::Content aCnt( sUrl, m_xCmdEnv, comphelper::getProcessComponentContext() ); + Sequence<OUString> aProps { "Title" }; + Reference< XResultSet > xResultSet( aCnt.createCursor( aProps ), UNO_SET_THROW ); + Reference< XContentAccess > xAccess( xResultSet, UNO_QUERY_THROW ); + while ( xResultSet->next() ) + { + OUString sURL = xAccess->queryContentIdentifierString( ); + INetURLObject aURL( sURL ); + OUString sId = aURL.GetURLPath( INetURLObject::DecodeMechanism::WithCharset ); + sId = sId.copy( 1 ); + m_aRepoIds.push_back( sId ); + + Reference< XRow > xRow( xResultSet, UNO_QUERY ); + OUString sName = xRow->getString( 1 ); + m_pDialog->m_xLBRepository->append_text(sName); + } + } + catch ( const Exception&) + { + TOOLS_WARN_EXCEPTION( "svtools.dialogs", "RefreshReposHdl" ); + } + + // Auto-select the first one + if (m_pDialog->m_xLBRepository->get_count() > 0) + { + m_pDialog->m_xLBRepository->set_active(0); + selectRepository( ); + } + + // remove temporary password + try + { + xMasterPasswd->remove( sUrl, m_sUsername ); + } + catch( const Exception& ) + {} +} + +IMPL_LINK_NOARG( CmisDetailsContainer, SelectRepoHdl, weld::ComboBox&, void ) +{ + selectRepository( ); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/dialogs/ServerDetailsControls.hxx b/svtools/source/dialogs/ServerDetailsControls.hxx new file mode 100644 index 000000000..d5041ddef --- /dev/null +++ b/svtools/source/dialogs/ServerDetailsControls.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/. + */ +#ifndef INCLUDED_SVTOOLS_SERVERDETAILSCONTROLS_HXX +#define INCLUDED_SVTOOLS_SERVERDETAILSCONTROLS_HXX + +#include <vector> + +#include <com/sun/star/uno/Reference.hxx> + +#include <tools/link.hxx> +#include <tools/urlobj.hxx> + +namespace com :: sun :: star :: ucb { class XCommandEnvironment; } +namespace com :: sun :: star :: awt { class XWindow; } + +namespace weld { + class Button; + class ComboBox; + class Entry; + class SpinButton; + class ToggleButton; +} + +class PlaceEditDialog; + +class DetailsContainer +{ + protected: + PlaceEditDialog* m_pDialog; + Link<DetailsContainer*,void> m_aChangeHdl; + + public: + DetailsContainer(PlaceEditDialog* pDialog); + virtual ~DetailsContainer( ); + + void setChangeHdl( const Link<DetailsContainer*,void>& rLink ) { m_aChangeHdl = rLink; } + + virtual void set_visible( bool bShow ); + virtual INetURLObject getUrl( ); + + /** Try to split the URL in the controls of that container. + + \param sUrl the URL to split + \return true if the split worked, false otherwise. + */ + virtual bool setUrl( const INetURLObject& rUrl ); + + virtual void setUsername( const OUString& /*rUsername*/ ) { }; + virtual void setPassword( const OUString& ) { }; + + virtual bool enableUserCredentials( ) { return true; }; + + protected: + void notifyChange( ); + DECL_LINK(ValueChangeHdl, weld::Entry&, void); + DECL_STATIC_LINK(DetailsContainer, FormatPortHdl, weld::SpinButton&, void); +}; + +class HostDetailsContainer : public DetailsContainer +{ + private: + sal_uInt16 m_nDefaultPort; + OUString m_sScheme; + OUString m_sHost; + + public: + HostDetailsContainer(PlaceEditDialog* pDialog, sal_uInt16 nPort, const OUString& sScheme); + + virtual void set_visible( bool bShow ) override; + virtual INetURLObject getUrl( ) override; + virtual bool setUrl( const INetURLObject& rUrl ) override; + + protected: + void setScheme( const OUString& sScheme ) { m_sScheme = sScheme; } + + /** Verifies that the scheme split from the URL can be handled by + the container and set the proper controls accordingly if needed. + */ + virtual bool verifyScheme( const OUString& rScheme ); +}; + +class DavDetailsContainer final : public HostDetailsContainer +{ + public: + DavDetailsContainer(PlaceEditDialog* pDialog); + + virtual void set_visible( bool bShow ) override; + virtual bool enableUserCredentials( ) override { return false; }; + + private: + virtual bool verifyScheme( const OUString& rScheme ) override; + + DECL_LINK(ToggledDavsHdl, weld::ToggleButton&, void); +}; + +class SmbDetailsContainer final : public DetailsContainer +{ + private: + OUString m_sHost; + + public: + SmbDetailsContainer(PlaceEditDialog* pDialog); + + virtual INetURLObject getUrl( ) override; + virtual bool setUrl( const INetURLObject& rUrl ) override; + virtual void set_visible( bool bShow ) override; +}; + +class CmisDetailsContainer final : public DetailsContainer +{ + private: + OUString m_sUsername; + OUString m_sPassword; + css::uno::Reference< css::ucb::XCommandEnvironment > m_xCmdEnv; + std::vector< OUString > m_aRepoIds; + OUString m_sRepoId; + OUString m_sBinding; + css::uno::Reference< css::awt::XWindow > m_xParentDialog; + + public: + CmisDetailsContainer(PlaceEditDialog* pDialog, OUString const & sBinding); + + virtual void set_visible( bool bShow ) override; + virtual INetURLObject getUrl( ) override; + virtual bool setUrl( const INetURLObject& rUrl ) override; + virtual void setUsername( const OUString& rUsername ) override; + virtual void setPassword( const OUString& rPass ) override; + + private: + void selectRepository( ); + DECL_LINK ( RefreshReposHdl, weld::Button&, void ); + DECL_LINK ( SelectRepoHdl, weld::ComboBox&, void ); +}; + +#endif +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/dialogs/addresstemplate.cxx b/svtools/source/dialogs/addresstemplate.cxx new file mode 100644 index 000000000..bed1a0dae --- /dev/null +++ b/svtools/source/dialogs/addresstemplate.cxx @@ -0,0 +1,1125 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <memory> +#include <svtools/addresstemplate.hxx> +#include <svtools/strings.hrc> +#include <svtools/svtresid.hxx> +#include <tools/debug.hxx> +#include <comphelper/interaction.hxx> +#include <comphelper/string.hxx> +#include <unotools/configitem.hxx> +#include <vcl/stdtext.hxx> +#include <vcl/svapp.hxx> +#include <vcl/weld.hxx> +#include <sal/log.hxx> +#include <osl/diagnose.h> +#include <com/sun/star/util/AliasProgrammaticPair.hpp> +#include <com/sun/star/ui/dialogs/AddressBookSourcePilot.hpp> +#include <com/sun/star/beans/PropertyValue.hpp> +#include <com/sun/star/beans/XPropertySet.hpp> +#include <com/sun/star/sdb/DatabaseContext.hpp> +#include <com/sun/star/sdb/XCompletedConnection.hpp> +#include <com/sun/star/sdb/SQLContext.hpp> +#include <com/sun/star/sdbc/SQLWarning.hpp> +#include <com/sun/star/sdbc/XConnection.hpp> +#include <com/sun/star/sdbc/XDataSource.hpp> +#include <com/sun/star/task/InteractionHandler.hpp> +#include <com/sun/star/sdbcx/XTablesSupplier.hpp> +#include <com/sun/star/sdbcx/XColumnsSupplier.hpp> +#include <svl/filenotation.hxx> +#include <tools/urlobj.hxx> +#include <algorithm> +#include <map> +#include <set> +#include <array> +#include <strings.hxx> + + +namespace svt +{ + using namespace ::com::sun::star::uno; + using namespace ::com::sun::star::lang; + using namespace ::com::sun::star::container; + using namespace ::com::sun::star::ui::dialogs; + using namespace ::com::sun::star::util; + using namespace ::com::sun::star::beans; + using namespace ::com::sun::star::sdb; + using namespace ::com::sun::star::sdbc; + using namespace ::com::sun::star::sdbcx; + using namespace ::com::sun::star::task; + using namespace ::comphelper; + using namespace ::utl; + + typedef std::set<OUString> StringBag; + typedef std::map<OUString, OUString> MapString2String; + + namespace + { + OUString lcl_getSelectedDataSource( const weld::ComboBox& dataSourceCombo ) + { + OUString selectedDataSource = dataSourceCombo.get_active_text(); + if (dataSourceCombo.find_text(selectedDataSource) == -1) + { + // none of the pre-selected entries -> assume a path to a database document + OFileNotation aFileNotation( selectedDataSource, OFileNotation::N_SYSTEM ); + selectedDataSource = aFileNotation.get( OFileNotation::N_URL ); + } + return selectedDataSource; + } + + // = IAssigmentData + + class IAssigmentData + { + public: + virtual ~IAssigmentData(); + + /// the data source to use for the address book + virtual OUString getDatasourceName() const = 0; + + /// the command to use for the address book + virtual OUString getCommand() const = 0; + + /// checks whether or not there is an assignment for a given logical field + virtual bool hasFieldAssignment(const OUString& _rLogicalName) = 0; + /// retrieves the assignment for a given logical field + virtual OUString getFieldAssignment(const OUString& _rLogicalName) = 0; + + /// set the assignment for a given logical field + virtual void setFieldAssignment(const OUString& _rLogicalName, const OUString& _rAssignment) = 0; + + virtual void setDatasourceName(const OUString& _rName) = 0; + virtual void setCommand(const OUString& _rCommand) = 0; + }; + + } + + IAssigmentData::~IAssigmentData() + { + } + + + // = AssigmentTransientData + + namespace { + + class AssigmentTransientData : public IAssigmentData + { + protected: + OUString m_sDSName; + OUString m_sTableName; + MapString2String m_aAliases; + + public: + AssigmentTransientData( + const OUString& _rDataSourceName, + const OUString& _rTableName, + const Sequence< AliasProgrammaticPair >& _rFields + ); + + // IAssigmentData overridables + virtual OUString getDatasourceName() const override; + virtual OUString getCommand() const override; + + virtual bool hasFieldAssignment(const OUString& _rLogicalName) override; + virtual OUString getFieldAssignment(const OUString& _rLogicalName) override; + virtual void setFieldAssignment(const OUString& _rLogicalName, const OUString& _rAssignment) override; + + virtual void setDatasourceName(const OUString& _rName) override; + virtual void setCommand(const OUString& _rCommand) override; + }; + + } + + AssigmentTransientData::AssigmentTransientData( + const OUString& _rDataSourceName, const OUString& _rTableName, + const Sequence< AliasProgrammaticPair >& _rFields ) + :m_sDSName( _rDataSourceName ) + ,m_sTableName( _rTableName ) + { + // fill our aliases structure + // first collect all known programmatic names + StringBag aKnownNames; + + OUString const sLogicalFieldNames(STR_LOGICAL_FIELD_NAMES); + sal_Int32 nIndex = 0; + do + { + OUString aToken = sLogicalFieldNames.getToken(0, ';', nIndex); + aKnownNames.insert(aToken); + } + while ( nIndex >= 0); + + // loop through the given names + for (const AliasProgrammaticPair& rField : _rFields) + { + if ( aKnownNames.end() != aKnownNames.find( rField.ProgrammaticName ) ) + { + m_aAliases[ rField.ProgrammaticName ] = rField.Alias; + } + else + { + SAL_WARN( "svtools", "AssigmentTransientData::AssigmentTransientData: unknown programmatic name: " + << rField.ProgrammaticName ); + } + } + } + + + OUString AssigmentTransientData::getDatasourceName() const + { + return m_sDSName; + } + + + OUString AssigmentTransientData::getCommand() const + { + return m_sTableName; + } + + + bool AssigmentTransientData::hasFieldAssignment(const OUString& _rLogicalName) + { + MapString2String::const_iterator aPos = m_aAliases.find( _rLogicalName ); + return ( m_aAliases.end() != aPos ) + && ( !aPos->second.isEmpty() ); + } + + + OUString AssigmentTransientData::getFieldAssignment(const OUString& _rLogicalName) + { + OUString sReturn; + MapString2String::const_iterator aPos = m_aAliases.find( _rLogicalName ); + if ( m_aAliases.end() != aPos ) + sReturn = aPos->second; + + return sReturn; + } + + + void AssigmentTransientData::setFieldAssignment(const OUString& _rLogicalName, const OUString& _rAssignment) + { + m_aAliases[ _rLogicalName ] = _rAssignment; + } + + + void AssigmentTransientData::setDatasourceName(const OUString&) + { + OSL_FAIL( "AssigmentTransientData::setDatasourceName: cannot be implemented for transient data!" ); + } + + + void AssigmentTransientData::setCommand(const OUString&) + { + OSL_FAIL( "AssigmentTransientData::setCommand: cannot be implemented for transient data!" ); + } + + + // = AssignmentPersistentData + + namespace { + + class AssignmentPersistentData + :public ::utl::ConfigItem + ,public IAssigmentData + { + protected: + StringBag m_aStoredFields; + + protected: + css::uno::Any getProperty(const OUString& _rLocalName) const; + + OUString getStringProperty(const char* _pLocalName) const; + OUString getStringProperty(const OUString& _rLocalName) const; + + void setStringProperty(const char* _pLocalName, const OUString& _rValue); + + public: + AssignmentPersistentData(); + + // IAssigmentData overridables + virtual OUString getDatasourceName() const override; + virtual OUString getCommand() const override; + + virtual bool hasFieldAssignment(const OUString& _rLogicalName) override; + virtual OUString getFieldAssignment(const OUString& _rLogicalName) override; + virtual void setFieldAssignment(const OUString& _rLogicalName, const OUString& _rAssignment) override; + + virtual void setDatasourceName(const OUString& _rName) override; + virtual void setCommand(const OUString& _rCommand) override; + + virtual void Notify( const css::uno::Sequence<OUString>& aPropertyNames) override; + + private: + virtual void ImplCommit() override; + void clearFieldAssignment(const OUString& _rLogicalName); + }; + + } + +void AssignmentPersistentData::Notify( const css::uno::Sequence<OUString>& ) +{ +} + +void AssignmentPersistentData::ImplCommit() +{ +} + + + AssignmentPersistentData::AssignmentPersistentData() + :ConfigItem("Office.DataAccess/AddressBook") + { + Sequence< OUString > aStoredNames = GetNodeNames("Fields"); + std::copy(aStoredNames.begin(), aStoredNames.end(), + std::inserter(m_aStoredFields, m_aStoredFields.end())); + } + + bool AssignmentPersistentData::hasFieldAssignment(const OUString& _rLogicalName) + { + return (m_aStoredFields.end() != m_aStoredFields.find(_rLogicalName)); + } + + + OUString AssignmentPersistentData::getFieldAssignment(const OUString& _rLogicalName) + { + OUString sAssignment; + if (hasFieldAssignment(_rLogicalName)) + { + OUString sFieldPath = "Fields/" + _rLogicalName + "/AssignedFieldName"; + sAssignment = getStringProperty(sFieldPath); + } + return sAssignment; + } + + + Any AssignmentPersistentData::getProperty(const OUString& _rLocalName) const + { + Sequence< OUString > aProperties(&_rLocalName, 1); + Sequence< Any > aValues = const_cast<AssignmentPersistentData*>(this)->GetProperties(aProperties); + DBG_ASSERT(aValues.getLength() == 1, "AssignmentPersistentData::getProperty: invalid sequence length!"); + return aValues[0]; + } + + + OUString AssignmentPersistentData::getStringProperty(const OUString& _rLocalName) const + { + OUString sReturn; + getProperty( _rLocalName ) >>= sReturn; + return sReturn; + } + + + OUString AssignmentPersistentData::getStringProperty(const char* _pLocalName) const + { + OUString sReturn; + getProperty(OUString::createFromAscii(_pLocalName)) >>= sReturn; + return sReturn; + } + + + void AssignmentPersistentData::setStringProperty(const char* _pLocalName, const OUString& _rValue) + { + Sequence< OUString > aNames { OUString::createFromAscii(_pLocalName) }; + Sequence< Any > aValues(1); + aValues[0] <<= _rValue; + PutProperties(aNames, aValues); + } + + + void AssignmentPersistentData::setFieldAssignment(const OUString& _rLogicalName, const OUString& _rAssignment) + { + if (_rAssignment.isEmpty()) + { + if (hasFieldAssignment(_rLogicalName)) + { + // the assignment exists but it should be reset + clearFieldAssignment(_rLogicalName); + } + return; + } + + // Fields + OUString sDescriptionNodePath("Fields"); + + // Fields/<field> + OUString sFieldElementNodePath = sDescriptionNodePath + "/" + _rLogicalName; + + Sequence< PropertyValue > aNewFieldDescription(2); + // Fields/<field>/ProgrammaticFieldName + aNewFieldDescription[0].Name = sFieldElementNodePath + "/ProgrammaticFieldName"; + aNewFieldDescription[0].Value <<= _rLogicalName; + // Fields/<field>/AssignedFieldName + aNewFieldDescription[1].Name = sFieldElementNodePath + "/AssignedFieldName"; + aNewFieldDescription[1].Value <<= _rAssignment; + + // just set the new value + bool bSuccess = + SetSetProperties(sDescriptionNodePath, aNewFieldDescription); + DBG_ASSERT(bSuccess, "AssignmentPersistentData::setFieldAssignment: could not commit the changes a field!"); + } + + + void AssignmentPersistentData::clearFieldAssignment(const OUString& _rLogicalName) + { + if (!hasFieldAssignment(_rLogicalName)) + // nothing to do + return; + + Sequence< OUString > aNames(&_rLogicalName, 1); + ClearNodeElements("Fields", aNames); + } + + + OUString AssignmentPersistentData::getDatasourceName() const + { + return getStringProperty( "DataSourceName" ); + } + + + OUString AssignmentPersistentData::getCommand() const + { + return getStringProperty( "Command" ); + } + + + void AssignmentPersistentData::setDatasourceName(const OUString& _rName) + { + setStringProperty( "DataSourceName", _rName ); + } + + + void AssignmentPersistentData::setCommand(const OUString& _rCommand) + { + setStringProperty( "Command", _rCommand ); + } + + + // = AddressBookSourceDialogData + + struct AddressBookSourceDialogData + { + std::array<std::unique_ptr<weld::Label>, FIELD_PAIRS_VISIBLE*2> pFieldLabels; + std::array<std::unique_ptr<weld::ComboBox>, FIELD_PAIRS_VISIBLE*2> pFields; + + /// when working transient, we need the data source + Reference< XDataSource > + m_xTransientDataSource; + /// current scroll pos in the field list + sal_Int32 nFieldScrollPos; + /// indicates that we've an odd field number. This member is for efficiency only, it's redundant. + bool bOddFieldNumber : 1; + /// indicates that we're working with the real persistent configuration + bool bWorkingPersistent : 1; + + /// the strings to use as labels for the field selection listboxes + std::vector<OUString> aFieldLabels; + // the current field assignment + std::vector<OUString> aFieldAssignments; + /// the logical field names + std::vector<OUString> aLogicalFieldNames; + + std::unique_ptr<IAssigmentData> pConfigData; + + + AddressBookSourceDialogData( ) + :pFieldLabels{{nullptr}} + ,pFields{{nullptr}} + ,nFieldScrollPos(0) + ,bOddFieldNumber(false) + ,bWorkingPersistent( true ) + ,pConfigData( new AssignmentPersistentData ) + { + } + + AddressBookSourceDialogData( const Reference< XDataSource >& _rxTransientDS, const OUString& _rDataSourceName, + const OUString& _rTableName, const Sequence< AliasProgrammaticPair >& _rFields ) + :pFieldLabels{{nullptr}} + ,pFields{{nullptr}} + ,m_xTransientDataSource( _rxTransientDS ) + ,nFieldScrollPos(0) + ,bOddFieldNumber(false) + ,bWorkingPersistent( false ) + ,pConfigData( new AssigmentTransientData( _rDataSourceName, _rTableName, _rFields ) ) + { + } + + // Copy assignment is forbidden and not implemented. + AddressBookSourceDialogData (const AddressBookSourceDialogData &) = delete; + AddressBookSourceDialogData & operator= (const AddressBookSourceDialogData &) = delete; + }; + + // = AddressBookSourceDialog + AddressBookSourceDialog::AddressBookSourceDialog(weld::Window* pParent, + const Reference< XComponentContext >& _rxORB ) + : GenericDialogController(pParent, "svt/ui/addresstemplatedialog.ui", "AddressTemplateDialog") + , m_sNoFieldSelection(SvtResId(STR_NO_FIELD_SELECTION)) + , m_xORB(_rxORB) + , m_pImpl( new AddressBookSourceDialogData ) + { + implConstruct(); + } + + AddressBookSourceDialog::AddressBookSourceDialog(weld::Window* pParent, const Reference< XComponentContext >& _rxORB, + const Reference< XDataSource >& _rxTransientDS, const OUString& _rDataSourceName, + const OUString& _rTable, const Sequence< AliasProgrammaticPair >& _rMapping ) + : GenericDialogController(pParent, "svt/ui/addresstemplatedialog.ui", "AddressTemplateDialog") + , m_sNoFieldSelection(SvtResId(STR_NO_FIELD_SELECTION)) + , m_xORB(_rxORB) + , m_pImpl( new AddressBookSourceDialogData( _rxTransientDS, _rDataSourceName, _rTable, _rMapping ) ) + { + implConstruct(); + } + + void AddressBookSourceDialog::implConstruct() + { + m_xOKButton = m_xBuilder->weld_button("ok"); + m_xDatasource = m_xBuilder->weld_combo_box("datasource"); + m_xAdministrateDatasources = m_xBuilder->weld_button("admin"); + m_xTable = m_xBuilder->weld_combo_box("datatable"); + m_xFieldScroller = m_xBuilder->weld_scrolled_window("scrollwindow"); + m_xFieldScroller->set_user_managed_scrolling(); + m_xGrid = m_xBuilder->weld_widget("grid"); + + for (sal_Int32 row=0; row<FIELD_PAIRS_VISIBLE; ++row) + { + for (sal_Int32 column=0; column<2; ++column) + { + // the label + m_pImpl->pFieldLabels[row * 2 + column] = m_xBuilder->weld_label("label" + OString::number(row * 2 + column)); + // the listbox + m_pImpl->pFields[row * 2 + column] = m_xBuilder->weld_combo_box("box" + OString::number(row * 2 + column)); + m_pImpl->pFields[row * 2 + column]->connect_changed(LINK(this, AddressBookSourceDialog, OnFieldSelect)); + } + } + + initializeDatasources(); + + // for the moment, we have a hard coded list of all known fields. + // A better solution would be to store all known field translations in the configuration, which could be + // extensible by the user in an arbitrary way. + // But for the moment we need a quick solution ... + // (the main thing would be to store the translations to use here in the user interface, besides that, the code + // should be adjustable with a rather small effort.) + + // initialize the strings for the field labels + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_FIRSTNAME )); + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_LASTNAME )); + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_COMPANY)); + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_DEPARTMENT )); + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_STREET )); + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_ZIPCODE )); + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_CITY )); + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_STATE)); + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_COUNTRY )); + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_HOMETEL )); + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_WORKTEL )); + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_OFFICETEL)); + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_MOBILE)); + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_TELOTHER)); + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_PAGER)); + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_FAX )); + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_EMAIL )); + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_URL )); + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_TITLE )); + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_POSITION )); + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_INITIALS )); + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_ADDRFORM )); + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_SALUTATION )); + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_ID)); + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_CALENDAR)); + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_INVITE)); + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_NOTE)); + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_USER1)); + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_USER2)); + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_USER3)); + m_pImpl->aFieldLabels.push_back( SvtResId( STR_FIELD_USER4)); + + long nLabelWidth = 0; + long nListBoxWidth = m_pImpl->pFields[0]->get_approximate_digit_width() * 18; + for (auto const& fieldLabel : m_pImpl->aFieldLabels) + { + m_pImpl->pFieldLabels[0]->set_label(fieldLabel); + nLabelWidth = std::max(nLabelWidth, m_pImpl->pFieldLabels[0]->get_preferred_size().Width()); + } + for (sal_Int32 row=0; row<FIELD_PAIRS_VISIBLE; ++row) + { + for (sal_Int32 column=0; column<2; ++column) + { + m_pImpl->pFieldLabels[row * 2 + column]->set_size_request(nLabelWidth, -1); + m_pImpl->pFields[row * 2 + column]->set_size_request(nListBoxWidth, -1); + } + } + + // force an even number of known fields + m_pImpl->bOddFieldNumber = (m_pImpl->aFieldLabels.size() % 2) != 0; + if (m_pImpl->bOddFieldNumber) + m_pImpl->aFieldLabels.emplace_back(); + + // limit the scrollbar range accordingly + sal_Int32 nOverallFieldPairs = m_pImpl->aFieldLabels.size() / 2; + m_xFieldScroller->vadjustment_configure(0, 0, nOverallFieldPairs, + 1, FIELD_PAIRS_VISIBLE - 1, FIELD_PAIRS_VISIBLE); + + // reset the current field assignments + m_pImpl->aFieldAssignments.resize(m_pImpl->aFieldLabels.size()); + // (empty strings mean "no assignment") + + // some knittings + m_xFieldScroller->connect_vadjustment_changed(LINK(this, AddressBookSourceDialog, OnFieldScroll)); + m_xAdministrateDatasources->connect_clicked(LINK(this, AddressBookSourceDialog, OnAdministrateDatasources)); + m_xDatasource->set_entry_completion(true); + m_xTable->set_entry_completion(true); + m_xTable->connect_focus_in(LINK(this, AddressBookSourceDialog, OnComboGetFocus)); + m_xDatasource->connect_focus_in(LINK(this, AddressBookSourceDialog, OnComboGetFocus)); + m_xTable->connect_focus_out(LINK(this, AddressBookSourceDialog, OnComboLoseFocus)); + m_xDatasource->connect_focus_out(LINK(this, AddressBookSourceDialog, OnComboLoseFocus)); + m_xTable->connect_changed(LINK(this, AddressBookSourceDialog, OnComboSelect)); + m_xDatasource->connect_changed(LINK(this, AddressBookSourceDialog, OnComboSelect)); + m_xOKButton->connect_clicked(LINK(this, AddressBookSourceDialog, OnOkClicked)); + + // initialize the field controls + resetFields(); + // tdf#136494 wait until contents are filled before getting preferred height + m_xFieldScroller->set_size_request(-1, m_xGrid->get_preferred_size().Height()); + m_xFieldScroller->vadjustment_set_value(0); + m_pImpl->nFieldScrollPos = -1; + implScrollFields(0, false, false); + + // the logical names + OUString sLogicalFieldNames(STR_LOGICAL_FIELD_NAMES); + sal_Int32 nAdjustedTokenCount = comphelper::string::getTokenCount(sLogicalFieldNames, ';') + (m_pImpl->bOddFieldNumber ? 1 : 0); + DBG_ASSERT(nAdjustedTokenCount == static_cast<sal_Int32>(m_pImpl->aFieldLabels.size()), + "AddressBookSourceDialog::AddressBookSourceDialog: inconsistence between logical and UI field names!"); + m_pImpl->aLogicalFieldNames.reserve(nAdjustedTokenCount); + sal_Int32 nIdx{ 0 }; + for (sal_Int32 i = 0; i<nAdjustedTokenCount; ++i) + m_pImpl->aLogicalFieldNames.push_back(sLogicalFieldNames.getToken(0, ';', nIdx)); + + Application::PostUserEvent(LINK(this, AddressBookSourceDialog, OnDelayedInitialize), nullptr, false); + + // so the dialog will at least show up before we do the loading of the + // configuration data and the (maybe time consuming) analysis of the data source/table to select + + if (m_pImpl->bWorkingPersistent) + return; + + m_xAdministrateDatasources->hide(); + } + + void AddressBookSourceDialog::getFieldMapping(Sequence< AliasProgrammaticPair >& _rMapping) const + { + _rMapping.realloc( m_pImpl->aLogicalFieldNames.size() ); + AliasProgrammaticPair* pPair = _rMapping.getArray(); + + for (auto const& logicalFieldName : m_pImpl->aLogicalFieldNames) + { + if ( m_pImpl->pConfigData->hasFieldAssignment(logicalFieldName) ) + { + // the user gave us an assignment for this field + pPair->ProgrammaticName = logicalFieldName; + pPair->Alias = m_pImpl->pConfigData->getFieldAssignment(logicalFieldName); + ++pPair; + } + } + + _rMapping.realloc( pPair - _rMapping.getArray() ); + } + + void AddressBookSourceDialog::loadConfiguration() + { + OUString sName = m_pImpl->pConfigData->getDatasourceName(); + INetURLObject aURL( sName ); + if( aURL.GetProtocol() != INetProtocol::NotValid ) + { + OFileNotation aFileNotation( aURL.GetMainURL( INetURLObject::DecodeMechanism::NONE ) ); + sName = aFileNotation.get(OFileNotation::N_SYSTEM); + } + + m_xDatasource->set_entry_text(sName); + m_xTable->set_entry_text(m_pImpl->pConfigData->getCommand()); + // we ignore the CommandType: only tables are supported + + // the logical names for the fields + // AddressBookSourceDialog::loadConfiguration: inconsistence between field names and field assignments! + assert(m_pImpl->aLogicalFieldNames.size() == m_pImpl->aFieldAssignments.size()); + + auto aAssignment = m_pImpl->aFieldAssignments.begin(); + for (auto const& logicalFieldName : m_pImpl->aLogicalFieldNames) + { + *aAssignment = m_pImpl->pConfigData->getFieldAssignment(logicalFieldName); + ++aAssignment; + } + } + + AddressBookSourceDialog::~AddressBookSourceDialog() + { + } + + void AddressBookSourceDialog::initializeDatasources() + { + if (!m_xDatabaseContext.is()) + { + DBG_ASSERT(m_xORB.is(), "AddressBookSourceDialog::initializeDatasources: no service factory!"); + if (!m_xORB.is()) + return; + + try + { + m_xDatabaseContext = DatabaseContext::create(m_xORB); + } + catch(const Exception&) { } + if (!m_xDatabaseContext.is()) + { + const OUString sContextServiceName("com.sun.star.sdb.DatabaseContext"); + ShowServiceNotAvailableError(m_xDialog.get(), sContextServiceName, false); + return; + } + } + m_xDatasource->clear(); + + // fill the datasources listbox + try + { + const css::uno::Sequence<OUString> aElementNames = m_xDatabaseContext->getElementNames(); + for (const OUString& rDatasourceName : aElementNames) + m_xDatasource->append_text(rDatasourceName); + } + catch(Exception&) + { + OSL_FAIL("AddressBookSourceDialog::initializeDatasources: caught an exception while asking for the data source names!"); + } + } + + IMPL_LINK(AddressBookSourceDialog, OnFieldScroll, weld::ScrolledWindow&, rScrollBar, void) + { + implScrollFields(rScrollBar.vadjustment_get_value(), true, true); + } + + void AddressBookSourceDialog::resetTables() + { + if (!m_xDatabaseContext.is()) + return; + + weld::WaitObject aWaitCursor(m_xDialog.get()); + + // no matter what we do here, we handled the currently selected data source (no matter if successful or not) + m_xDatasource->save_value(); + + // create an interaction handler (may be needed for connecting) + Reference< XInteractionHandler > xHandler; + try + { + xHandler.set( + InteractionHandler::createWithParent(m_xORB, m_xDialog->GetXWindow()), + UNO_QUERY_THROW ); + } + catch(const Exception&) { } + if (!xHandler.is()) + { + const OUString sInteractionHandlerServiceName("com.sun.star.task.InteractionHandler"); + ShowServiceNotAvailableError(m_xDialog.get(), sInteractionHandlerServiceName, true); + return; + } + + // the currently selected table + OUString sOldTable = m_xTable->get_active_text(); + + m_xTable->clear(); + + m_xCurrentDatasourceTables= nullptr; + + // get the tables of the connection + Sequence< OUString > aTableNames; + Any aException; + try + { + Reference< XCompletedConnection > xDS; + if ( m_pImpl->bWorkingPersistent ) + { + OUString sSelectedDS = lcl_getSelectedDataSource(*m_xDatasource); + + // get the data source the user has chosen and let it build a connection + INetURLObject aURL( sSelectedDS ); + if ( aURL.GetProtocol() != INetProtocol::NotValid || m_xDatabaseContext->hasByName(sSelectedDS) ) + m_xDatabaseContext->getByName( sSelectedDS ) >>= xDS; + } + else + { + xDS.set(m_pImpl->m_xTransientDataSource, css::uno::UNO_QUERY); + } + + // build the connection + Reference< XConnection > xConn; + if (xDS.is()) + xConn = xDS->connectWithCompletion(xHandler); + + // get the table names + Reference< XTablesSupplier > xSupplTables(xConn, UNO_QUERY); + if (xSupplTables.is()) + { + m_xCurrentDatasourceTables = xSupplTables->getTables(); + if (m_xCurrentDatasourceTables.is()) + aTableNames = m_xCurrentDatasourceTables->getElementNames(); + } + } + catch(const SQLContext& e) { aException <<= e; } + catch(const SQLWarning& e) { aException <<= e; } + catch(const SQLException& e) { aException <<= e; } + catch(Exception&) + { + OSL_FAIL("AddressBookSourceDialog::resetTables: could not retrieve the table!"); + } + + if (aException.hasValue()) + { + Reference< XInteractionRequest > xRequest = new OInteractionRequest(aException); + try + { + xHandler->handle(xRequest); + } + catch(Exception&) { } + return; + } + + bool bKnowOldTable = false; + // fill the table list + for (const OUString& rTableName : std::as_const(aTableNames)) + { + m_xTable->append_text(rTableName); + if (rTableName == sOldTable) + bKnowOldTable = true; + } + + // set the old table, if the new data source knows a table with this name, too. Else reset the tables edit field. + if (!bKnowOldTable) + sOldTable.clear(); + m_xTable->set_entry_text(sOldTable); + + resetFields(); + } + + void AddressBookSourceDialog::resetFields() + { + weld::WaitObject aWaitCursor(m_xDialog.get()); + + // no matter what we do here, we handled the currently selected table (no matter if successful or not) + m_xDatasource->save_value(); + + OUString sSelectedTable = m_xTable->get_active_text(); + Sequence< OUString > aColumnNames; + try + { + if (m_xCurrentDatasourceTables.is()) + { + // get the table and the columns + Reference< XColumnsSupplier > xSuppTableCols; + if (m_xCurrentDatasourceTables->hasByName(sSelectedTable)) + xSuppTableCols.set( + m_xCurrentDatasourceTables->getByName(sSelectedTable), + css::uno::UNO_QUERY); + Reference< XNameAccess > xColumns; + if (xSuppTableCols.is()) + xColumns = xSuppTableCols->getColumns(); + if (xColumns.is()) + aColumnNames = xColumns->getElementNames(); + } + } + catch (const Exception&) + { + OSL_FAIL("AddressBookSourceDialog::resetFields: could not retrieve the table columns!"); + } + + + // for quicker access + ::std::set< OUString > aColumnNameSet; + std::copy(aColumnNames.begin(), aColumnNames.end(), std::inserter(aColumnNameSet, aColumnNameSet.end())); + + std::vector<OUString>::iterator aInitialSelection = m_pImpl->aFieldAssignments.begin() + m_pImpl->nFieldScrollPos; + + OUString sSaveSelection; + for (sal_Int32 i=0; i<FIELD_CONTROLS_VISIBLE; ++i, ++aInitialSelection) + { + weld::ComboBox* pListbox = m_pImpl->pFields[i].get(); + sSaveSelection = pListbox->get_active_text(); + + pListbox->clear(); + + // the one entry for "no selection" + pListbox->append_text(m_sNoFieldSelection); + // as it's entry data, set the index of the list box in our array + pListbox->set_id(0, OUString::number(i)); + + // the field names + for (const OUString& rColumnName : std::as_const(aColumnNames)) + pListbox->append_text(rColumnName); + + if (!aInitialSelection->isEmpty() && (aColumnNameSet.end() != aColumnNameSet.find(*aInitialSelection))) + // we can select the entry as specified in our field assignment array + pListbox->set_active_text(*aInitialSelection); + else + // try to restore the selection + if (aColumnNameSet.end() != aColumnNameSet.find(sSaveSelection)) + // the old selection is a valid column name + pListbox->set_active_text(sSaveSelection); + else + // select the <none> entry + pListbox->set_active(0); + } + + // adjust m_pImpl->aFieldAssignments + for (auto & fieldAssignment : m_pImpl->aFieldAssignments) + if (!fieldAssignment.isEmpty()) + if (aColumnNameSet.end() == aColumnNameSet.find(fieldAssignment)) + fieldAssignment.clear(); + } + + IMPL_LINK(AddressBookSourceDialog, OnFieldSelect, weld::ComboBox&, rListbox, void) + { + // the index of the affected list box in our array + sal_Int32 nListBoxIndex = rListbox.get_id(0).toInt32(); + DBG_ASSERT(nListBoxIndex >= 0 && nListBoxIndex < FIELD_CONTROLS_VISIBLE, + "AddressBookSourceDialog::OnFieldScroll: invalid list box entry!"); + + // update the array where we remember the field selections + if (0 == rListbox.get_active()) + // it's the "no field selection" entry + m_pImpl->aFieldAssignments[m_pImpl->nFieldScrollPos * 2 + nListBoxIndex].clear(); + else + // it's a regular field entry + m_pImpl->aFieldAssignments[m_pImpl->nFieldScrollPos * 2 + nListBoxIndex] = rListbox.get_active_text(); + } + + + void AddressBookSourceDialog::implScrollFields(sal_Int32 _nPos, bool _bAdjustFocus, bool _bAdjustScrollbar) + { + if (_nPos == m_pImpl->nFieldScrollPos) + // nothing to do + return; + + // loop through our field control rows and do some adjustments + // for the new texts + auto pLeftLabelControl = m_pImpl->pFieldLabels.begin(); + auto pRightLabelControl = pLeftLabelControl+1; + auto pLeftColumnLabel = m_pImpl->aFieldLabels.cbegin() + 2 * _nPos; + auto pRightColumnLabel = pLeftColumnLabel + 1; + + // for the focus movement and the selection scroll + auto pLeftListControl = m_pImpl->pFields.begin(); + auto pRightListControl = pLeftListControl + 1; + + // for the focus movement + sal_Int32 nOldFocusRow = -1; + sal_Int32 nOldFocusColumn = 0; + + // for the selection scroll + auto pLeftAssignment = m_pImpl->aFieldAssignments.cbegin() + 2 * _nPos; + auto pRightAssignment = pLeftAssignment + 1; + + // loop + for (sal_Int32 i=0; i<FIELD_PAIRS_VISIBLE; ++i) + { + if ((*pLeftListControl)->has_focus()) + { + nOldFocusRow = i; + nOldFocusColumn = 0; + } + else if ((*pRightListControl)->has_focus()) + { + nOldFocusRow = i; + nOldFocusColumn = 1; + } + + // the new texts of the label controls + (*pLeftLabelControl)->set_label(*pLeftColumnLabel); + (*pRightLabelControl)->set_label(*pRightColumnLabel); + + // we may have to hide the controls in the right column, if we have no label text for it + // (which means we have an odd number of fields, though we forced our internal arrays to + // be even-sized for easier handling) + // (If sometimes we support an arbitrary number of field assignments, we would have to care for + // an invisible left hand side column, too. But right now, the left hand side controls are always + // visible) + bool bHideRightColumn = pRightColumnLabel->isEmpty(); + (*pRightLabelControl)->set_visible(!bHideRightColumn); + (*pRightListControl)->set_visible(!bHideRightColumn); + // the new selections of the listboxes + implSelectField(pLeftListControl->get(), *pLeftAssignment); + implSelectField(pRightListControl->get(), *pRightAssignment); + + // increment ... + if ( i < FIELD_PAIRS_VISIBLE - 1 ) + { // (not in the very last round, here the +=2 could result in an invalid + // iterator position, which causes an abort in a non-product version + pLeftLabelControl += 2; + pRightLabelControl += 2; + pLeftColumnLabel += 2; + pRightColumnLabel += 2; + + pLeftListControl += 2; + pRightListControl += 2; + pLeftAssignment += 2; + pRightAssignment += 2; + } + } + + if (_bAdjustFocus && (nOldFocusRow >= 0)) + { // we have to adjust the focus and one of the list boxes has the focus + sal_Int32 nDelta = m_pImpl->nFieldScrollPos - _nPos; + // the new row for the focus + sal_Int32 nNewFocusRow = nOldFocusRow + nDelta; + // normalize + nNewFocusRow = std::min(nNewFocusRow, sal_Int32(FIELD_PAIRS_VISIBLE - 1), ::std::less< sal_Int32 >()); + nNewFocusRow = std::max(nNewFocusRow, sal_Int32(0), ::std::less< sal_Int32 >()); + // set the new focus (in the same column) + m_pImpl->pFields[nNewFocusRow * 2 + nOldFocusColumn]->grab_focus(); + } + + m_pImpl->nFieldScrollPos = _nPos; + + if (_bAdjustScrollbar) + m_xFieldScroller->vadjustment_set_value(m_pImpl->nFieldScrollPos); + } + + void AddressBookSourceDialog::implSelectField(weld::ComboBox* pBox, const OUString& rText) + { + if (!rText.isEmpty()) + // a valid field name + pBox->set_active_text(rText); + else + // no selection for this item + pBox->set_active(0); + } + + IMPL_LINK_NOARG(AddressBookSourceDialog, OnDelayedInitialize, void*, void) + { + // load the initial data from the configuration + loadConfiguration(); + resetTables(); + // will reset the tables/fields implicitly + + if ( !m_pImpl->bWorkingPersistent ) + if ( m_pImpl->pFields[0] ) + m_pImpl->pFields[0]->grab_focus(); + } + + IMPL_LINK(AddressBookSourceDialog, OnComboSelect, weld::ComboBox&, rBox, void) + { + if (&rBox == m_xDatasource.get()) + resetTables(); + else + resetFields(); + } + + IMPL_STATIC_LINK(AddressBookSourceDialog, OnComboGetFocus, weld::Widget&, rBox, void) + { + dynamic_cast<weld::ComboBox&>(rBox).save_value(); + } + + IMPL_LINK(AddressBookSourceDialog, OnComboLoseFocus, weld::Widget&, rControl, void) + { + weld::ComboBox& rBox = dynamic_cast<weld::ComboBox&>(rControl); + if (rBox.get_value_changed_from_saved()) + { + if (&rBox == m_xDatasource.get()) + resetTables(); + else + resetFields(); + } + } + + IMPL_LINK_NOARG(AddressBookSourceDialog, OnOkClicked, weld::Button&, void) + { + OUString sSelectedDS = lcl_getSelectedDataSource(*m_xDatasource); + if ( m_pImpl->bWorkingPersistent ) + { + m_pImpl->pConfigData->setDatasourceName(sSelectedDS); + m_pImpl->pConfigData->setCommand(m_xTable->get_active_text()); + } + + // AddressBookSourceDialog::loadConfiguration: inconsistence between field names and field assignments! + assert(m_pImpl->aLogicalFieldNames.size() == m_pImpl->aFieldAssignments.size()); + + // set the field assignments + auto aAssignment = m_pImpl->aFieldAssignments.cbegin(); + for (auto const& logicalFieldName : m_pImpl->aLogicalFieldNames) + { + m_pImpl->pConfigData->setFieldAssignment(logicalFieldName, *aAssignment); + ++aAssignment; + } + + m_xDialog->response(RET_OK); + } + + IMPL_LINK_NOARG(AddressBookSourceDialog, OnAdministrateDatasources, weld::Button&, void) + { + // create the dialog object + Reference< XExecutableDialog > xAdminDialog; + try + { + xAdminDialog = AddressBookSourcePilot::createWithParent(m_xORB, m_xDialog->GetXWindow()); + } + catch(const Exception&) { } + if (!xAdminDialog.is()) + { + ShowServiceNotAvailableError(m_xDialog.get(), "com.sun.star.ui.dialogs.AddressBookSourcePilot", true); + return; + } + + // execute the dialog + try + { + if ( xAdminDialog->execute() == RET_OK ) + { + Reference<XPropertySet> xProp(xAdminDialog,UNO_QUERY); + if ( xProp.is() ) + { + OUString sName; + xProp->getPropertyValue("DataSourceName") >>= sName; + + INetURLObject aURL( sName ); + if( aURL.GetProtocol() != INetProtocol::NotValid ) + { + OFileNotation aFileNotation( aURL.GetMainURL( INetURLObject::DecodeMechanism::NONE ) ); + sName = aFileNotation.get(OFileNotation::N_SYSTEM); + } + m_xDatasource->append_text(sName); + m_pImpl->pConfigData.reset( new AssignmentPersistentData ); + loadConfiguration(); + resetTables(); + // will reset the fields implicitly + } + } + } + catch(const Exception&) + { + OSL_FAIL("AddressBookSourceDialog::OnAdministrateDatasources: an error occurred while executing the administration dialog!"); + } + + // re-fill the data source list + // try to preserve the current selection + +// initializeDatasources(); + } + +} // namespace svt + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/dialogs/colrdlg.cxx b/svtools/source/dialogs/colrdlg.cxx new file mode 100644 index 000000000..ea448ffd8 --- /dev/null +++ b/svtools/source/dialogs/colrdlg.cxx @@ -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 . + */ + + +#include <com/sun/star/awt/XWindow.hpp> +#include <com/sun/star/beans/XPropertyAccess.hpp> +#include <com/sun/star/ui/dialogs/XExecutableDialog.hpp> +#include <com/sun/star/cui/ColorPicker.hpp> + +#include <comphelper/processfactory.hxx> + +#include <svtools/colrdlg.hxx> +#include <vcl/weld.hxx> +#include <osl/diagnose.h> + +using namespace ::com::sun::star::uno; +using namespace ::com::sun::star::lang; +using namespace ::com::sun::star::beans; +using namespace ::com::sun::star::ui::dialogs; + + +SvColorDialog::SvColorDialog() + : meMode(svtools::ColorPickerMode::Select) +{ +} + +SvColorDialog::~SvColorDialog() +{ +} +void SvColorDialog::SetColor( const Color& rColor ) +{ + maColor = rColor; +} + +void SvColorDialog::SetMode( svtools::ColorPickerMode eMode ) +{ + meMode = eMode; +} + +short SvColorDialog::Execute(weld::Window* pParent) +{ + short ret = 0; + try + { + const OUString sColor( "Color" ); + Reference< XComponentContext > xContext( ::comphelper::getProcessComponentContext() ); + + Reference<css::awt::XWindow> xParent; + if (pParent) + xParent = pParent->GetXWindow(); + + Reference< XExecutableDialog > xDialog = css::cui::ColorPicker::createWithParent(xContext, xParent); + Reference< XPropertyAccess > xPropertyAccess( xDialog, UNO_QUERY_THROW ); + + Sequence< PropertyValue > props( 2 ); + props[0].Name = sColor; + props[0].Value <<= maColor; + props[1].Name = "Mode"; + props[1].Value <<= static_cast<sal_Int16>(meMode); + + xPropertyAccess->setPropertyValues( props ); + + ret = xDialog->execute(); + + if( ret ) + { + props = xPropertyAccess->getPropertyValues(); + for( const auto& rProp : std::as_const(props) ) + { + if( rProp.Name == sColor ) + { + rProp.Value >>= maColor; + } + } + } + } + catch(Exception&) + { + OSL_ASSERT(false); + } + + return ret; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/dialogs/insdlg.cxx b/svtools/source/dialogs/insdlg.cxx new file mode 100644 index 000000000..4c0701406 --- /dev/null +++ b/svtools/source/dialogs/insdlg.cxx @@ -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 . + */ + +#include <svtools/insdlg.hxx> +#include <svtools/strings.hrc> +#include <svtools/svtresid.hxx> + +#include <unotools/configmgr.hxx> +#include <comphelper/classids.hxx> +#include <sot/stg.hxx> +#include <sal/macros.h> + +#include <com/sun/star/lang/XMultiServiceFactory.hpp> +#include <com/sun/star/configuration/theDefaultProvider.hpp> +#include <comphelper/processfactory.hxx> +#include <comphelper/propertysequence.hxx> +#include <com/sun/star/container/XNameAccess.hpp> + +using namespace ::com::sun::star; + + +// this struct conforms to the Microsoft +// OBJECTDESCRIPTOR -> see oleidl.h +// (MS platform sdk) + +namespace { + +struct OleObjectDescriptor +{ + sal_uInt32 cbSize; + ClsId clsid; + sal_uInt32 dwDrawAspect; + Size sizel; + Point pointl; + sal_uInt32 dwStatus; + sal_uInt32 dwFullUserTypeName; + sal_uInt32 dwSrcOfCopy; +}; + +} + +/********************** SvObjectServerList ******************************** +**************************************************************************/ + +const SvObjectServer * SvObjectServerList::Get( const OUString & rHumanName ) const +{ + for(const auto & i : aObjectServerList) + { + if( rHumanName == i.GetHumanName() ) + return &i; + } + return nullptr; +} + +const SvObjectServer * SvObjectServerList::Get( const SvGlobalName & rName ) const +{ + for(const auto & i : aObjectServerList) + { + if( rName == i.GetClassName() ) + return &i; + } + return nullptr; +} + +void SvObjectServerList::Remove( const SvGlobalName & rName ) +{ + aObjectServerList.erase(std::remove_if(aObjectServerList.begin(), aObjectServerList.end(), + [rName](const SvObjectServer& rServer) { return rServer.GetClassName() == rName; }), + aObjectServerList.end()); +} + + +void SvObjectServerList::FillInsertObjects() +/* [Description] + + The list is filled with all types which can be selected in the insert-dialog. +*/ +{ + try{ + uno::Reference< uno::XComponentContext > xContext = comphelper::getProcessComponentContext(); + + uno::Reference< lang::XMultiServiceFactory > sProviderMSFactory = + configuration::theDefaultProvider::get(xContext); + + uno::Sequence<uno::Any> aArguments(comphelper::InitAnyPropertySequence( + { + {"nodepath", uno::Any(OUString( "/org.openoffice.Office.Embedding/ObjectNames" ))} + })); + uno::Reference< container::XNameAccess > xNameAccess( + sProviderMSFactory->createInstanceWithArguments( "com.sun.star.configuration.ConfigurationAccess", aArguments ), + uno::UNO_QUERY ); + + if( xNameAccess.is()) + { + const uno::Sequence< OUString > seqNames= xNameAccess->getElementNames(); + + OUString aStringProductName( "%PRODUCTNAME" ); + sal_Int32 nStringProductNameLength = aStringProductName.getLength(); + + OUString aStringProductVersion( "%PRODUCTVERSION" ); + sal_Int32 nStringProductVersionLength = aStringProductVersion.getLength(); + + for( const auto& rName : seqNames ) + { + uno::Reference< container::XNameAccess > xEntry ; + xNameAccess->getByName( rName ) >>= xEntry; + if ( xEntry.is() ) + { + OUString aUIName; + OUString aClassID; + xEntry->getByName("ObjectUIName") >>= aUIName; + xEntry->getByName("ClassID") >>= aClassID; + + if ( !aUIName.isEmpty() ) + { + // replace %PRODUCTNAME + sal_Int32 nIndex = aUIName.indexOf( aStringProductName ); + while( nIndex != -1 ) + { + aUIName = aUIName.replaceAt( + nIndex, nStringProductNameLength, + utl::ConfigManager::getProductName() ); + nIndex = aUIName.indexOf( aStringProductName ); + } + + // replace %PRODUCTVERSION + nIndex = aUIName.indexOf( aStringProductVersion ); + while( nIndex != -1 ) + { + aUIName = aUIName.replaceAt( + nIndex, nStringProductVersionLength, + utl::ConfigManager::getProductVersion() ); + nIndex = aUIName.indexOf( aStringProductVersion ); + } + } + + SvGlobalName aClassName; + if( aClassName.MakeId( aClassID) ) + { + if( !Get( aClassName ) ) + // not entered yet + aObjectServerList.emplace_back( aClassName, aUIName ); + } + } + } + } + + +#ifdef _WIN32 + SvGlobalName aOleFact( SO3_OUT_CLASSID ); + OUString aOleObj( SvtResId( STR_FURTHER_OBJECT ) ); + aObjectServerList.push_back( SvObjectServer( aOleFact, aOleObj ) ); +#endif + + }catch(const container::NoSuchElementException&) + { + }catch(const uno::Exception&) + { + } + catch(...) + { + } +} + +OUString SvPasteObjectHelper::GetSotFormatUIName( SotClipboardFormatId nId ) +{ + struct SotResourcePair + { + SotClipboardFormatId mnSotId; + const char* mpResId; + }; + + static const SotResourcePair aSotResourcePairs[] = + { + { SotClipboardFormatId::STRING, STR_FORMAT_STRING }, + { SotClipboardFormatId::BITMAP, STR_FORMAT_BITMAP }, + { SotClipboardFormatId::GDIMETAFILE, STR_FORMAT_GDIMETAFILE }, + { SotClipboardFormatId::RTF, STR_FORMAT_RTF }, + { SotClipboardFormatId::DRAWING, STR_FORMAT_ID_DRAWING }, + { SotClipboardFormatId::SVXB, STR_FORMAT_ID_SVXB }, + { SotClipboardFormatId::INTERNALLINK_STATE, STR_FORMAT_ID_INTERNALLINK_STATE }, + { SotClipboardFormatId::SOLK, STR_FORMAT_ID_SOLK }, + { SotClipboardFormatId::NETSCAPE_BOOKMARK, STR_FORMAT_ID_NETSCAPE_BOOKMARK }, + { SotClipboardFormatId::STARSERVER, STR_FORMAT_ID_STARSERVER }, + { SotClipboardFormatId::STAROBJECT, STR_FORMAT_ID_STAROBJECT }, + { SotClipboardFormatId::APPLETOBJECT, STR_FORMAT_ID_APPLETOBJECT }, + { SotClipboardFormatId::PLUGIN_OBJECT, STR_FORMAT_ID_PLUGIN_OBJECT }, + { SotClipboardFormatId::STARWRITER_30, STR_FORMAT_ID_STARWRITER_30 }, + { SotClipboardFormatId::STARWRITER_40, STR_FORMAT_ID_STARWRITER_40 }, + { SotClipboardFormatId::STARWRITER_50, STR_FORMAT_ID_STARWRITER_50 }, + { SotClipboardFormatId::STARWRITERWEB_40, STR_FORMAT_ID_STARWRITERWEB_40 }, + { SotClipboardFormatId::STARWRITERWEB_50, STR_FORMAT_ID_STARWRITERWEB_50 }, + { SotClipboardFormatId::STARWRITERGLOB_40, STR_FORMAT_ID_STARWRITERGLOB_40 }, + { SotClipboardFormatId::STARWRITERGLOB_50, STR_FORMAT_ID_STARWRITERGLOB_50 }, + { SotClipboardFormatId::STARDRAW, STR_FORMAT_ID_STARDRAW }, + { SotClipboardFormatId::STARDRAW_40, STR_FORMAT_ID_STARDRAW_40 }, + { SotClipboardFormatId::STARIMPRESS_50, STR_FORMAT_ID_STARIMPRESS_50 }, + { SotClipboardFormatId::STARDRAW_50, STR_FORMAT_ID_STARDRAW_50 }, + { SotClipboardFormatId::STARCALC, STR_FORMAT_ID_STARCALC }, + { SotClipboardFormatId::STARCALC_40, STR_FORMAT_ID_STARCALC_40 }, + { SotClipboardFormatId::STARCALC_50, STR_FORMAT_ID_STARCALC_50 }, + { SotClipboardFormatId::STARCHART, STR_FORMAT_ID_STARCHART }, + { SotClipboardFormatId::STARCHART_40, STR_FORMAT_ID_STARCHART_40 }, + { SotClipboardFormatId::STARCHART_50, STR_FORMAT_ID_STARCHART_50 }, + { SotClipboardFormatId::STARIMAGE, STR_FORMAT_ID_STARIMAGE }, + { SotClipboardFormatId::STARIMAGE_40, STR_FORMAT_ID_STARIMAGE_40 }, + { SotClipboardFormatId::STARIMAGE_50, STR_FORMAT_ID_STARIMAGE_50 }, + { SotClipboardFormatId::STARMATH, STR_FORMAT_ID_STARMATH }, + { SotClipboardFormatId::STARMATH_40, STR_FORMAT_ID_STARMATH_40 }, + { SotClipboardFormatId::STARMATH_50, STR_FORMAT_ID_STARMATH_50 }, + { SotClipboardFormatId::STAROBJECT_PAINTDOC, STR_FORMAT_ID_STAROBJECT_PAINTDOC }, + { SotClipboardFormatId::HTML, STR_FORMAT_ID_HTML }, + { SotClipboardFormatId::HTML_SIMPLE, STR_FORMAT_ID_HTML_SIMPLE }, + { SotClipboardFormatId::BIFF_5, STR_FORMAT_ID_BIFF_5 }, + { SotClipboardFormatId::BIFF_8, STR_FORMAT_ID_BIFF_8 }, + { SotClipboardFormatId::SYLK, STR_FORMAT_ID_SYLK }, + { SotClipboardFormatId::LINK, STR_FORMAT_ID_LINK }, + { SotClipboardFormatId::DIF, STR_FORMAT_ID_DIF }, + { SotClipboardFormatId::MSWORD_DOC, STR_FORMAT_ID_MSWORD_DOC }, + { SotClipboardFormatId::STAR_FRAMESET_DOC, STR_FORMAT_ID_STAR_FRAMESET_DOC }, + { SotClipboardFormatId::OFFICE_DOC, STR_FORMAT_ID_OFFICE_DOC }, + { SotClipboardFormatId::NOTES_DOCINFO, STR_FORMAT_ID_NOTES_DOCINFO }, + { SotClipboardFormatId::SFX_DOC, STR_FORMAT_ID_SFX_DOC }, + { SotClipboardFormatId::STARCHARTDOCUMENT_50,STR_FORMAT_ID_STARCHARTDOCUMENT_50 }, + { SotClipboardFormatId::GRAPHOBJ, STR_FORMAT_ID_GRAPHOBJ }, + { SotClipboardFormatId::STARWRITER_60, STR_FORMAT_ID_STARWRITER_60 }, + { SotClipboardFormatId::STARWRITERWEB_60, STR_FORMAT_ID_STARWRITERWEB_60 }, + { SotClipboardFormatId::STARWRITERGLOB_60, STR_FORMAT_ID_STARWRITERGLOB_60 }, + { SotClipboardFormatId::STARDRAW_60, STR_FORMAT_ID_STARDRAW_60 }, + { SotClipboardFormatId::STARIMPRESS_60, STR_FORMAT_ID_STARIMPRESS_60 }, + { SotClipboardFormatId::STARCALC_60, STR_FORMAT_ID_STARCALC_60 }, + { SotClipboardFormatId::STARCHART_60, STR_FORMAT_ID_STARCHART_60 }, + { SotClipboardFormatId::STARMATH_60, STR_FORMAT_ID_STARMATH_60 }, + { SotClipboardFormatId::WMF, STR_FORMAT_ID_WMF }, + { SotClipboardFormatId::DBACCESS_QUERY, STR_FORMAT_ID_DBACCESS_QUERY }, + { SotClipboardFormatId::DBACCESS_TABLE, STR_FORMAT_ID_DBACCESS_TABLE }, + { SotClipboardFormatId::DBACCESS_COMMAND, STR_FORMAT_ID_DBACCESS_COMMAND }, + { SotClipboardFormatId::DIALOG_60, STR_FORMAT_ID_DIALOG_60 }, + { SotClipboardFormatId::FILEGRPDESCRIPTOR, STR_FORMAT_ID_FILEGRPDESCRIPTOR }, + { SotClipboardFormatId::HTML_NO_COMMENT, STR_FORMAT_ID_HTML_NO_COMMENT }, + { SotClipboardFormatId::RICHTEXT, STR_FORMAT_ID_RICHTEXT }, + { SotClipboardFormatId::STRING_TSVC, STR_FORMAT_ID_STRING_TSVC }, + { SotClipboardFormatId::PNG, STR_FORMAT_ID_PNG_BITMAP }, + }; + + const char* pResId = nullptr; + + sal_uInt32 const nCount = SAL_N_ELEMENTS( aSotResourcePairs ); + for (sal_uInt32 i = 0; ( i < nCount ) && !pResId; ++i) + { + if( aSotResourcePairs[ i ].mnSotId == nId ) + pResId = aSotResourcePairs[ i ].mpResId; + } + + OUString aUIName; + if (pResId) + aUIName = SvtResId(pResId); + else + aUIName = SotExchange::GetFormatName( nId ); + + return aUIName; +} + +bool SvPasteObjectHelper::GetEmbeddedName(const TransferableDataHelper& rData, OUString& _rName, OUString& _rSource, SotClipboardFormatId const & _nFormat) +{ + if( _nFormat != SotClipboardFormatId::EMBED_SOURCE_OLE && _nFormat != SotClipboardFormatId::EMBEDDED_OBJ_OLE ) + return false; + + datatransfer::DataFlavor aFlavor; + SotExchange::GetFormatDataFlavor( SotClipboardFormatId::OBJECTDESCRIPTOR_OLE, aFlavor ); + + if( !rData.HasFormat( aFlavor ) ) + return false; + + uno::Any aAny = rData.GetAny(aFlavor, OUString()); + if (!aAny.hasValue()) + return false; + + uno::Sequence< sal_Int8 > anySequence; + aAny >>= anySequence; + + OleObjectDescriptor* pOleObjDescr = + reinterpret_cast< OleObjectDescriptor* >( anySequence.getArray( ) ); + + // determine the user friendly description of the embedded object + if ( pOleObjDescr->dwFullUserTypeName ) + { + // we set the pointer to the start of user friendly description + // string. it starts at &OleObjectDescriptor + dwFullUserTypeName. + // dwFullUserTypeName is the offset in bytes. + // the user friendly description string is '\0' terminated. + const sal_Unicode* pUserTypeName = + reinterpret_cast< sal_Unicode* >( + reinterpret_cast< char* >( pOleObjDescr ) + + pOleObjDescr->dwFullUserTypeName ); + + _rName += pUserTypeName; + // the following statement was here for historical reasons, it is commented out since it causes bug i49460 + // _nFormat = SotClipboardFormatId::EMBED_SOURCE_OLE; + } + + // determine the source of the embedded object + if ( pOleObjDescr->dwSrcOfCopy ) + { + // we set the pointer to the start of source string + // it starts at &OleObjectDescriptor + dwSrcOfCopy. + // dwSrcOfCopy is the offset in bytes. + // the source string is '\0' terminated. + const sal_Unicode* pSrcOfCopy = + reinterpret_cast< sal_Unicode* >( + reinterpret_cast< char* >( pOleObjDescr ) + + pOleObjDescr->dwSrcOfCopy ); + + _rSource += pSrcOfCopy; + } + else + _rSource = SvtResId(STR_UNKNOWN_SOURCE); + + return true; +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/dialogs/prnsetup.cxx b/svtools/source/dialogs/prnsetup.cxx new file mode 100644 index 000000000..03afe9eef --- /dev/null +++ b/svtools/source/dialogs/prnsetup.cxx @@ -0,0 +1,344 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <svtools/prnsetup.hxx> +#include <svtools/strings.hrc> +#include <svtools/svtresid.hxx> +#include <vcl/svapp.hxx> +#include <vcl/print.hxx> +#include <vcl/event.hxx> +#include <sal/log.hxx> + +void ImplFillPrnDlgListBox( const Printer* pPrinter, + weld::ComboBox* pBox, weld::Button* pPropBtn ) +{ + ImplFreePrnDlgListBox( pBox ); + + const std::vector<OUString>& rPrinters = Printer::GetPrinterQueues(); + unsigned int nCount = rPrinters.size(); + if ( nCount ) + { + for( unsigned int i = 0; i < nCount; i++ ) + pBox->append_text( rPrinters[i] ); + pBox->set_active_text(pPrinter->GetName()); + } + + pBox->set_sensitive(nCount != 0); + pPropBtn->set_visible( pPrinter->HasSupport( PrinterSupport::SetupDialog ) ); +} + + +void ImplFreePrnDlgListBox( weld::ComboBox* pBox, bool bClear ) +{ + if ( bClear ) + pBox->clear(); +} + + +Printer* ImplPrnDlgListBoxSelect( const weld::ComboBox* pBox, weld::Button* pPropBtn, + Printer const * pPrinter, Printer* pTempPrinterIn ) +{ + VclPtr<Printer> pTempPrinter( pTempPrinterIn ); + if ( pBox->get_active() != -1 ) + { + const QueueInfo* pInfo = Printer::GetQueueInfo( pBox->get_active_text(), true ); + if( pInfo) + { + if ( !pTempPrinter ) + { + if ( (pPrinter->GetName() == pInfo->GetPrinterName()) && + (pPrinter->GetDriverName() == pInfo->GetDriver()) ) + pTempPrinter = VclPtr<Printer>::Create( pPrinter->GetJobSetup() ); + else + pTempPrinter = VclPtr<Printer>::Create( *pInfo ); + } + else + { + if ( (pTempPrinter->GetName() != pInfo->GetPrinterName()) || + (pTempPrinter->GetDriverName() != pInfo->GetDriver()) ) + { + pTempPrinter.disposeAndClear(); + pTempPrinter = VclPtr<Printer>::Create( *pInfo ); + } + } + + pPropBtn->set_sensitive(pTempPrinter->HasSupport(PrinterSupport::SetupDialog)); + } + else + pPropBtn->set_sensitive(false); + } + else + pPropBtn->set_sensitive(false); + + return pTempPrinter; +} + + +Printer* ImplPrnDlgUpdatePrinter( Printer const * pPrinter, Printer* pTempPrinterIn ) +{ + VclPtr<Printer> pTempPrinter( pTempPrinterIn ); + OUString aPrnName; + if ( pTempPrinter ) + aPrnName = pTempPrinter->GetName(); + else + aPrnName = pPrinter->GetName(); + + if ( ! Printer::GetQueueInfo( aPrnName, false ) ) + { + pTempPrinter.disposeAndClear(); + pTempPrinter = VclPtr<Printer>::Create(); + } + + return pTempPrinter; +} + + +void ImplPrnDlgUpdateQueueInfo( const weld::ComboBox* pBox, QueueInfo& rInfo ) +{ + if ( pBox->get_active() != -1 ) + { + const QueueInfo* pInfo = Printer::GetQueueInfo( pBox->get_active_text(), true ); + if( pInfo ) + rInfo = *pInfo; + } +} + + +static OUString ImplPrnDlgAddString(const OUString& rStr, const OUString& rAddStr) +{ + OUString aStr(rStr); + if (!aStr.isEmpty()) + aStr += "; " ; + return aStr + rAddStr; +} + + +static OUString ImplPrnDlgAddResString(const OUString& rStr, const char* pResId) +{ + return ImplPrnDlgAddString(rStr, SvtResId(pResId)); +} + + +OUString ImplPrnDlgGetStatusText( const QueueInfo& rInfo ) +{ + OUString aStr; + PrintQueueFlags nStatus = rInfo.GetStatus(); + + // Default-Printer + if ( !rInfo.GetPrinterName().isEmpty() && + (rInfo.GetPrinterName() == Printer::GetDefaultPrinterName()) ) + aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_DEFPRINTER ); + + // Status + if ( nStatus & PrintQueueFlags::Ready ) + aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_READY ); + if ( nStatus & PrintQueueFlags::Paused ) + aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAUSED ); + if ( nStatus & PrintQueueFlags::PendingDeletion ) + aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PENDING ); + if ( nStatus & PrintQueueFlags::Busy ) + aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_BUSY ); + if ( nStatus & PrintQueueFlags::Initializing ) + aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_INITIALIZING ); + if ( nStatus & PrintQueueFlags::Waiting ) + aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_WAITING ); + if ( nStatus & PrintQueueFlags::WarmingUp ) + aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_WARMING_UP ); + if ( nStatus & PrintQueueFlags::Processing ) + aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PROCESSING ); + if ( nStatus & PrintQueueFlags::Printing ) + aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PRINTING ); + if ( nStatus & PrintQueueFlags::Offline ) + aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_OFFLINE ); + if ( nStatus & PrintQueueFlags::Error ) + aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_ERROR ); + if ( nStatus & PrintQueueFlags::StatusUnknown ) + aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_SERVER_UNKNOWN ); + if ( nStatus & PrintQueueFlags::PaperJam ) + aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAPER_JAM ); + if ( nStatus & PrintQueueFlags::PaperOut ) + aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAPER_OUT ); + if ( nStatus & PrintQueueFlags::ManualFeed ) + aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_MANUAL_FEED ); + if ( nStatus & PrintQueueFlags::PaperProblem ) + aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAPER_PROBLEM ); + if ( nStatus & PrintQueueFlags::IOActive ) + aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_IO_ACTIVE ); + if ( nStatus & PrintQueueFlags::OutputBinFull ) + aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_OUTPUT_BIN_FULL ); + if ( nStatus & PrintQueueFlags::TonerLow ) + aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_TONER_LOW ); + if ( nStatus & PrintQueueFlags::NoToner ) + aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_NO_TONER ); + if ( nStatus & PrintQueueFlags::PagePunt ) + aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAGE_PUNT ); + if ( nStatus & PrintQueueFlags::UserIntervention ) + aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_USER_INTERVENTION ); + if ( nStatus & PrintQueueFlags::OutOfMemory ) + aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_OUT_OF_MEMORY ); + if ( nStatus & PrintQueueFlags::DoorOpen ) + aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_DOOR_OPEN ); + if ( nStatus & PrintQueueFlags::PowerSave ) + aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_POWER_SAVE ); + + // Number of jobs + sal_uInt32 nJobs = rInfo.GetJobs(); + if ( nJobs && (nJobs != QUEUE_JOBS_DONTKNOW) ) + { + OUString aJobStr( SvtResId( STR_SVT_PRNDLG_JOBCOUNT ) ); + OUString aJobs( OUString::number( nJobs ) ); + aStr = ImplPrnDlgAddString(aStr, aJobStr.replaceAll("%d", aJobs)); + } + + return aStr; +} + +PrinterSetupDialog::PrinterSetupDialog(weld::Window* pParent) + : GenericDialogController(pParent, "svt/ui/printersetupdialog.ui", "PrinterSetupDialog") + , m_xLbName(m_xBuilder->weld_combo_box("name")) + , m_xBtnProperties(m_xBuilder->weld_button("properties")) + , m_xBtnOptions(m_xBuilder->weld_button("options")) + , m_xFiStatus(m_xBuilder->weld_label("status")) + , m_xFiType(m_xBuilder->weld_label("type")) + , m_xFiLocation(m_xBuilder->weld_label("location")) + , m_xFiComment(m_xBuilder->weld_label("comment")) +{ + m_xLbName->make_sorted(); + + // show options button only if link is set + m_xBtnOptions->hide(); + + mpPrinter = nullptr; + mpTempPrinter = nullptr; + + maStatusTimer.SetTimeout( IMPL_PRINTDLG_STATUS_UPDATE ); + maStatusTimer.SetInvokeHandler( LINK( this, PrinterSetupDialog, ImplStatusHdl ) ); + m_xBtnProperties->connect_clicked( LINK( this, PrinterSetupDialog, ImplPropertiesHdl ) ); + m_xLbName->connect_changed( LINK( this, PrinterSetupDialog, ImplChangePrinterHdl ) ); + m_xDialog->connect_focus_in( LINK( this, PrinterSetupDialog, ImplGetFocusHdl ) ); + Application::AddEventListener(LINK( this, PrinterSetupDialog, ImplDataChangedHdl ) ); +} + +PrinterSetupDialog::~PrinterSetupDialog() +{ + Application::RemoveEventListener(LINK( this, PrinterSetupDialog, ImplDataChangedHdl ) ); + ImplFreePrnDlgListBox(m_xLbName.get(), false); +} + +void PrinterSetupDialog::SetOptionsHdl(const Link<weld::Button&, void>& rLink) +{ + m_xBtnOptions->connect_clicked(rLink); + m_xBtnOptions->set_visible(rLink.IsSet()); +} + +void PrinterSetupDialog::ImplSetInfo() +{ + const QueueInfo* pInfo = Printer::GetQueueInfo(m_xLbName->get_active_text(), true); + if ( pInfo ) + { + m_xFiType->set_label( pInfo->GetDriver() ); + m_xFiLocation->set_label( pInfo->GetLocation() ); + m_xFiComment->set_label( pInfo->GetComment() ); + m_xFiStatus->set_label( ImplPrnDlgGetStatusText( *pInfo ) ); + } + else + { + OUString aTempStr; + m_xFiType->set_label( aTempStr ); + m_xFiLocation->set_label( aTempStr ); + m_xFiComment->set_label( aTempStr ); + m_xFiStatus->set_label( aTempStr ); + } +} + +IMPL_LINK_NOARG(PrinterSetupDialog, ImplStatusHdl, Timer *, void) +{ + QueueInfo aInfo; + ImplPrnDlgUpdateQueueInfo(m_xLbName.get(), aInfo); + m_xFiStatus->set_label( ImplPrnDlgGetStatusText( aInfo ) ); +} + + +IMPL_LINK_NOARG(PrinterSetupDialog, ImplPropertiesHdl, weld::Button&, void) +{ + if ( !mpTempPrinter ) + mpTempPrinter = VclPtr<Printer>::Create( mpPrinter->GetJobSetup() ); + mpTempPrinter->Setup(m_xDialog.get()); +} + +IMPL_LINK_NOARG(PrinterSetupDialog, ImplChangePrinterHdl, weld::ComboBox&, void) +{ + mpTempPrinter = ImplPrnDlgListBoxSelect(m_xLbName.get(), m_xBtnProperties.get(), + mpPrinter, mpTempPrinter); + ImplSetInfo(); +} + +IMPL_LINK(PrinterSetupDialog, ImplGetFocusHdl, weld::Widget&, rWidget, void) +{ + if (rWidget.is_visible()) + ImplStatusHdl(&maStatusTimer); +} + +IMPL_LINK(PrinterSetupDialog, ImplDataChangedHdl, VclSimpleEvent&, rEvt, void) +{ + VclEventId nEvent = rEvt.GetId(); + if (nEvent != VclEventId::ApplicationDataChanged) + return; + + DataChangedEvent* pData = static_cast<DataChangedEvent*>(static_cast<VclWindowEvent&>(rEvt).GetData()); + if (!pData || pData->GetType() != DataChangedEventType::PRINTER) + return; + + mpTempPrinter = ImplPrnDlgUpdatePrinter(mpPrinter, mpTempPrinter); + Printer* pPrn; + if (mpTempPrinter) + pPrn = mpTempPrinter; + else + pPrn = mpPrinter; + ImplFillPrnDlgListBox(pPrn, m_xLbName.get(), m_xBtnProperties.get()); + ImplSetInfo(); +} + +short PrinterSetupDialog::run() +{ + if ( !mpPrinter || mpPrinter->IsPrinting() || mpPrinter->IsJobActive() ) + { + SAL_WARN( "svtools.dialogs", "PrinterSetupDialog::execute() - No Printer or printer is printing" ); + return RET_CANCEL; + } + + Printer::updatePrinters(); + + ImplFillPrnDlgListBox(mpPrinter, m_xLbName.get(), m_xBtnProperties.get()); + ImplSetInfo(); + maStatusTimer.Start(); + + // start dialog + short nRet = GenericDialogController::run(); + + // update data if the dialog was terminated with OK + if ( nRet == RET_OK && mpTempPrinter ) + mpPrinter->SetPrinterProps( mpTempPrinter ); + + maStatusTimer.Stop(); + + return nRet; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/dialogs/restartdialog.cxx b/svtools/source/dialogs/restartdialog.cxx new file mode 100644 index 000000000..419b0e55d --- /dev/null +++ b/svtools/source/dialogs/restartdialog.cxx @@ -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/. + */ + +#include <sal/config.h> + +#include <cassert> + +#include <com/sun/star/task/OfficeRestartManager.hpp> +#include <com/sun/star/task/XInteractionHandler.hpp> +#include <com/sun/star/uno/Reference.hxx> +#include <com/sun/star/uno/XComponentContext.hpp> +#include <svtools/restartdialog.hxx> +#include <tools/link.hxx> +#include <vcl/weld.hxx> + +namespace { + +class RestartDialog : public weld::GenericDialogController{ +public: + RestartDialog(weld::Window* parent, svtools::RestartReason reason) + : GenericDialogController(parent, "svt/ui/restartdialog.ui", "RestartDialog") + , btnYes_(m_xBuilder->weld_button("yes")) + , btnNo_(m_xBuilder->weld_button("no")) + { + switch (reason) { + case svtools::RESTART_REASON_JAVA: + reason_ = m_xBuilder->weld_widget("reason_java"); + break; + case svtools::RESTART_REASON_PDF_AS_STANDARD_JOB_FORMAT: + reason_ = m_xBuilder->weld_widget("reason_pdf"); + break; + case svtools::RESTART_REASON_BIBLIOGRAPHY_INSTALL: + reason_ = m_xBuilder->weld_widget("reason_bibliography_install"); + break; + case svtools::RESTART_REASON_MAILMERGE_INSTALL: + reason_ = m_xBuilder->weld_widget("reason_mailmerge_install"); + break; + case svtools::RESTART_REASON_LANGUAGE_CHANGE: + reason_ = m_xBuilder->weld_widget("reason_language_change"); + break; + case svtools::RESTART_REASON_ADDING_PATH: + reason_ = m_xBuilder->weld_widget("reason_adding_path"); + break; + case svtools::RESTART_REASON_ASSIGNING_JAVAPARAMETERS: + reason_ = m_xBuilder->weld_widget("reason_assigning_javaparameters"); + break; + case svtools::RESTART_REASON_ASSIGNING_FOLDERS: + reason_ = m_xBuilder->weld_widget("reason_assigning_folders"); + break; + case svtools::RESTART_REASON_EXP_FEATURES: + reason_ = m_xBuilder->weld_widget("reason_exp_features"); + break; + case svtools::RESTART_REASON_EXTENSION_INSTALL: + reason_ = m_xBuilder->weld_widget("reason_extension_install"); + break; + case svtools::RESTART_REASON_OPENGL: + reason_ = m_xBuilder->weld_widget("reason_opengl"); + break; + case svtools::RESTART_REASON_SKIA: + reason_ = m_xBuilder->weld_widget("reason_skia"); + break; + case svtools::RESTART_REASON_OPENCL: + reason_ = m_xBuilder->weld_widget("reason_opencl"); + break; + case svtools::RESTART_REASON_THREADING: + reason_ = m_xBuilder->weld_widget("reason_threading"); + break; + case svtools::RESTART_REASON_MSCOMPATIBLE_FORMS_MENU: + reason_ = m_xBuilder->weld_widget("reason_mscompatible_formsmenu"); + break; + default: + assert(false); // this cannot happen + } + reason_->show(); + btnYes_->connect_clicked(LINK(this, RestartDialog, hdlYes)); + btnNo_->connect_clicked(LINK(this, RestartDialog, hdlNo)); + } +private: + DECL_LINK(hdlYes, weld::Button&, void); + DECL_LINK(hdlNo, weld::Button&, void); + + std::unique_ptr<weld::Widget> reason_; + std::unique_ptr<weld::Button> btnYes_; + std::unique_ptr<weld::Button> btnNo_; +}; + +IMPL_LINK_NOARG(RestartDialog, hdlYes, weld::Button&, void) +{ + m_xDialog->response(RET_OK); +} + +IMPL_LINK_NOARG(RestartDialog, hdlNo, weld::Button&, void) +{ + m_xDialog->response(RET_CANCEL); +} + +} + +bool svtools::executeRestartDialog( + css::uno::Reference< css::uno::XComponentContext > const & context, + weld::Window* parent, RestartReason reason) +{ + auto xRestartManager = css::task::OfficeRestartManager::get(context); + if (xRestartManager->isRestartRequested(false)) + return true; // don't try to show another dialog when restart is already in progress + RestartDialog aDlg(parent, reason); + if (aDlg.run()) { + xRestartManager->requestRestart( + css::uno::Reference< css::task::XInteractionHandler >()); + return true; + } + return false; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/edit/editsyntaxhighlighter.cxx b/svtools/source/edit/editsyntaxhighlighter.cxx new file mode 100644 index 000000000..b32d80e1a --- /dev/null +++ b/svtools/source/edit/editsyntaxhighlighter.cxx @@ -0,0 +1,180 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <vcl/event.hxx> +#include <vcl/xtextedt.hxx> +#include <vcl/textview.hxx> +#include <svtools/editsyntaxhighlighter.hxx> +#include <vcl/txtattr.hxx> + +MultiLineEditSyntaxHighlight::MultiLineEditSyntaxHighlight( vcl::Window* pParent, WinBits nWinStyle, + HighlighterLanguage aLanguage): VclMultiLineEdit(pParent,nWinStyle), aHighlighter(aLanguage) +{ + EnableUpdateData(300); +} + +void MultiLineEditSyntaxHighlight::SetText(const OUString& rNewText) +{ + VclMultiLineEdit::SetText(rNewText); + UpdateData(); +} + +void MultiLineEditSyntaxHighlight::DoBracketHilight(sal_uInt16 nKey) +{ + TextSelection aCurrentPos = GetTextView()->GetSelection(); + sal_Int32 nStartPos = aCurrentPos.GetStart().GetIndex(); + const sal_uInt32 nStartPara = aCurrentPos.GetStart().GetPara(); + sal_uInt16 nCount = 0; + int nChar = -1; + + switch (nKey) + { + case '\'': // no break + case '"': + { + nChar = nKey; + break; + } + case '}' : + { + nChar = '{'; + break; + } + case ')': + { + nChar = '('; + break; + } + case ']': + { + nChar = '['; + break; + } + } + + if (nChar == -1) + return; + + sal_uInt32 nPara = nStartPara; + do + { + if (nPara == nStartPara && nStartPos == 0) + continue; + + OUString aLine( GetTextEngine()->GetText( nPara ) ); + + if (aLine.isEmpty()) + continue; + + for (sal_Int32 i = (nPara==nStartPara) ? nStartPos-1 : aLine.getLength()-1; i>0; --i) + { + if (aLine[i] == nChar) + { + if (!nCount) + { + GetTextEngine()->SetAttrib( TextAttribFontWeight( WEIGHT_ULTRABOLD ), nPara, i, i+1 ); + GetTextEngine()->SetAttrib( TextAttribFontColor( Color(0,0,0) ), nPara, i, i+1 ); + GetTextEngine()->SetAttrib( TextAttribFontWeight( WEIGHT_ULTRABOLD ), nStartPara, nStartPos, nStartPos ); + GetTextEngine()->SetAttrib( TextAttribFontColor( Color(0,0,0) ), nStartPara, nStartPos, nStartPos ); + return; + } + else + --nCount; + } + if (aLine[i] == nKey) + ++nCount; + } + } while (nPara--); +} + +bool MultiLineEditSyntaxHighlight::PreNotify( NotifyEvent& rNEvt ) +{ + if ( rNEvt.GetType() == MouseNotifyEvent::KEYINPUT ) + DoBracketHilight(rNEvt.GetKeyEvent()->GetCharCode()); + + return VclMultiLineEdit::PreNotify(rNEvt); +} + +Color MultiLineEditSyntaxHighlight::GetSyntaxHighlightColor(const svtools::ColorConfig& rColorConfig, HighlighterLanguage eLanguage, TokenType aToken) +{ + Color aColor; + switch (eLanguage) + { + case HighlighterLanguage::SQL: + { + switch (aToken) + { + case TokenType::Identifier: aColor = rColorConfig.GetColorValue(svtools::SQLIDENTIFIER).nColor; break; + case TokenType::Number: aColor = rColorConfig.GetColorValue(svtools::SQLNUMBER).nColor; break; + case TokenType::String: aColor = rColorConfig.GetColorValue(svtools::SQLSTRING).nColor; break; + case TokenType::Operator: aColor = rColorConfig.GetColorValue(svtools::SQLOPERATOR).nColor; break; + case TokenType::Keywords: aColor = rColorConfig.GetColorValue(svtools::SQLKEYWORD).nColor; break; + case TokenType::Parameter: aColor = rColorConfig.GetColorValue(svtools::SQLPARAMETER).nColor; break; + case TokenType::Comment: aColor = rColorConfig.GetColorValue(svtools::SQLCOMMENT).nColor; break; + default: aColor = Color(0,0,0); + } + break; + } + case HighlighterLanguage::Basic: + { + switch (aToken) + { + case TokenType::Identifier: aColor = Color(255,0,0); break; + case TokenType::Comment: aColor = Color(0,0,45); break; + case TokenType::Number: aColor = Color(204,102,204); break; + case TokenType::String: aColor = Color(0,255,45); break; + case TokenType::Operator: aColor = Color(0,0,100); break; + case TokenType::Keywords: aColor = Color(0,0,255); break; + case TokenType::Error : aColor = Color(0,255,255); break; + default: aColor = Color(0,0,0); + } + break; + } + default: aColor = Color(0,0,0); + + } + return aColor; +} + +Color MultiLineEditSyntaxHighlight::GetColorValue(TokenType aToken) +{ + return GetSyntaxHighlightColor(m_aColorConfig, aHighlighter.GetLanguage(), aToken); +} + +void MultiLineEditSyntaxHighlight::UpdateData() +{ + // syntax highlighting + // this must be possible improved by using notifychange correctly + bool bTempModified = GetTextEngine()->IsModified(); + for (sal_uInt32 nLine=0; nLine < GetTextEngine()->GetParagraphCount(); ++nLine) + { + OUString aLine( GetTextEngine()->GetText( nLine ) ); + GetTextEngine()->RemoveAttribs( nLine ); + std::vector<HighlightPortion> aPortions; + aHighlighter.getHighlightPortions( aLine, aPortions ); + for (auto const& portion : aPortions) + { + GetTextEngine()->SetAttrib( TextAttribFontColor( GetColorValue(portion.tokenType) ), nLine, portion.nBegin, portion.nEnd ); + } + } + GetTextView()->ShowCursor( false ); + GetTextEngine()->SetModified(bTempModified); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/edit/svmedit.cxx b/svtools/source/edit/svmedit.cxx new file mode 100644 index 000000000..207cbdb89 --- /dev/null +++ b/svtools/source/edit/svmedit.cxx @@ -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 <svmedit.hxx> +#include <unoiface.hxx> + +MultiLineEdit::MultiLineEdit( vcl::Window* pParent, WinBits nWinStyle ) + : VclMultiLineEdit( pParent,nWinStyle ) +{ +} + +// virtual +css::uno::Reference< css::awt::XWindowPeer > +MultiLineEdit::GetComponentInterface(bool bCreate) +{ + css::uno::Reference< css::awt::XWindowPeer > xPeer( + VclMultiLineEdit::GetComponentInterface(false)); + if (!xPeer.is() && bCreate) + { + rtl::Reference< VCLXMultiLineEdit > xVCLMEdit(new VCLXMultiLineEdit); + xVCLMEdit->SetWindow(this); + xPeer = xVCLMEdit.get(); + SetComponentInterface(xPeer); + } + return xPeer; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/edit/svmedit2.cxx b/svtools/source/edit/svmedit2.cxx new file mode 100644 index 000000000..fde13f6c7 --- /dev/null +++ b/svtools/source/edit/svmedit2.cxx @@ -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 . + */ + + +#include <svmedit2.hxx> +#include <vcl/xtextedt.hxx> +#include <vcl/textview.hxx> + +ExtMultiLineEdit::ExtMultiLineEdit( vcl::Window* pParent, WinBits nWinStyle ) : + MultiLineEdit( pParent, nWinStyle ) +{ +} + +void ExtMultiLineEdit::InsertText( const OUString& rNew ) +{ + GetTextView()->InsertText( rNew ); +} + +void ExtMultiLineEdit::SetAutoScroll( bool bAutoScroll ) +{ + GetTextView()->SetAutoScroll( bAutoScroll ); +} + +void ExtMultiLineEdit::SetAttrib( const TextAttrib& rAttr, sal_uInt32 nPara, sal_Int32 nStart, sal_Int32 nEnd ) +{ + GetTextEngine()->SetAttrib( rAttr, nPara, nStart, nEnd ); +} + +void ExtMultiLineEdit::SetLeftMargin( sal_uInt16 nLeftMargin ) +{ + GetTextEngine()->SetLeftMargin( nLeftMargin ); +} + +sal_uInt32 ExtMultiLineEdit::GetParagraphCount() const +{ + return GetTextEngine()->GetParagraphCount(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/edit/textwindowpeer.cxx b/svtools/source/edit/textwindowpeer.cxx new file mode 100644 index 000000000..f0291a8a8 --- /dev/null +++ b/svtools/source/edit/textwindowpeer.cxx @@ -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 . + */ + +#include <sal/config.h> + +#include <vcl/svtaccessiblefactory.hxx> +#include <vcl/accessiblefactory.hxx> + +#include <com/sun/star/accessibility/XAccessibleContext.hpp> +#include <com/sun/star/awt/XWindowPeer.hpp> +#include <com/sun/star/uno/Reference.hxx> +#include <svtools/textwindowpeer.hxx> +#include <toolkit/awt/vclxwindow.hxx> +#include <vcl/texteng.hxx> +#include <vcl/textview.hxx> + +namespace { + +class TextWindowPeer: public VCLXWindow { +public: + explicit TextWindowPeer(TextView & view); + + TextWindowPeer(const TextWindowPeer&) = delete; + TextWindowPeer& operator=(const TextWindowPeer&) = delete; + +private: + virtual css::uno::Reference<css::accessibility::XAccessibleContext> + CreateAccessibleContext() override; + + TextEngine & m_rEngine; + TextView & m_rView; + vcl::AccessibleFactoryAccess m_aFactoryAccess; +}; + +TextWindowPeer::TextWindowPeer(TextView & view): + m_rEngine(*view.GetTextEngine()), m_rView(view) +{ + SetWindow(view.GetWindow()); +} + +css::uno::Reference<css::accessibility::XAccessibleContext> +TextWindowPeer::CreateAccessibleContext() { + return m_aFactoryAccess.getFactory().createAccessibleTextWindowContext( + this, m_rEngine, m_rView); +} + +} + +css::uno::Reference<css::awt::XWindowPeer> svt::createTextWindowPeer( + TextView & view) +{ + return new TextWindowPeer(view); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/filter/DocumentToGraphicRenderer.cxx b/svtools/source/filter/DocumentToGraphicRenderer.cxx new file mode 100644 index 000000000..415ab353e --- /dev/null +++ b/svtools/source/filter/DocumentToGraphicRenderer.cxx @@ -0,0 +1,360 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <svtools/DocumentToGraphicRenderer.hxx> + +#include <vcl/gdimtf.hxx> +#include <vcl/graphicfilter.hxx> +#include <vcl/svapp.hxx> +#include <vcl/outdev.hxx> +#include <vcl/pdfextoutdevdata.hxx> + +#include <tools/fract.hxx> + +#include <com/sun/star/awt/XDevice.hpp> +#include <com/sun/star/awt/XToolkit.hpp> +#include <com/sun/star/text/XPageCursor.hpp> +#include <com/sun/star/text/XTextViewCursorSupplier.hpp> +#include <com/sun/star/view/XRenderable.hpp> +#include <com/sun/star/view/XSelectionSupplier.hpp> +#include <com/sun/star/beans/PropertyValues.hpp> +#include <com/sun/star/lang/XServiceInfo.hpp> +#include <com/sun/star/drawing/XShapes.hpp> +#include <com/sun/star/drawing/XShape.hpp> +#include <com/sun/star/frame/XModel.hpp> + +#include <toolkit/helper/vclunohelper.hxx> + +using namespace css; +using namespace css::uno; +using namespace css::lang; +using namespace css::beans; + +DocumentToGraphicRenderer::DocumentToGraphicRenderer( const Reference<XComponent>& rxDocument, bool bSelectionOnly ) : + mxDocument(rxDocument), + mxModel( mxDocument, uno::UNO_QUERY ), + mxController( mxModel->getCurrentController() ), + mxRenderable (mxDocument, uno::UNO_QUERY ), + mxToolkit( VCLUnoHelper::CreateToolkit() ), + meDocType( UNKNOWN ) +{ + try + { + uno::Reference< lang::XServiceInfo > xServiceInfo( mxDocument, uno::UNO_QUERY); + if (xServiceInfo.is()) + { + if (xServiceInfo->supportsService("com.sun.star.text.TextDocument")) + meDocType = WRITER; + else if (xServiceInfo->supportsService("com.sun.star.sheet.SpreadsheetDocument")) + meDocType = CALC; + else if (xServiceInfo->supportsService("com.sun.star.presentation.PresentationDocument")) + meDocType = IMPRESS; + else + meDocType = UNKNOWN; + } + } + catch (const uno::Exception&) + { + } + + if (!(bSelectionOnly && mxController.is())) + return; + + try + { + uno::Reference< view::XSelectionSupplier > xSelSup( mxController, uno::UNO_QUERY); + if (xSelSup.is()) + { + uno::Any aViewSelection( xSelSup->getSelection()); + if (aViewSelection.hasValue()) + { + /* FIXME: Writer always has a selection even if nothing is + * selected, but passing a selection to + * XRenderable::render() it always renders an empty page. + * So disable the selection already here. The current page + * the cursor is on is rendered. */ + if (!isWriter()) + maSelection = aViewSelection; + } + } + } + catch (const uno::Exception&) + { + } +} + +DocumentToGraphicRenderer::~DocumentToGraphicRenderer() +{ +} + +Size DocumentToGraphicRenderer::getDocumentSizeInPixels(sal_Int32 nCurrentPage) +{ + Size aSize100mm = getDocumentSizeIn100mm(nCurrentPage); + return Application::GetDefaultDevice()->LogicToPixel(aSize100mm, MapMode(MapUnit::Map100thMM)); +} + +bool DocumentToGraphicRenderer::hasSelection() const +{ + return maSelection.hasValue(); +} + +uno::Any DocumentToGraphicRenderer::getSelection() const +{ + uno::Any aSelection; + if (hasSelection()) + aSelection = maSelection; + else + aSelection <<= mxDocument; // default: render whole document + return aSelection; +} + +Size DocumentToGraphicRenderer::getDocumentSizeIn100mm(sal_Int32 nCurrentPage, + Point* pDocumentPosition, Point* pCalcPagePosition, Size* pCalcPageSize) +{ + Reference< awt::XDevice > xDevice(mxToolkit->createScreenCompatibleDevice( 32, 32 ) ); + + uno::Any selection( getSelection()); + + PropertyValues renderProperties; + + renderProperties.realloc( 4 ); + renderProperties[0].Name = "IsPrinter"; + renderProperties[0].Value <<= true; + renderProperties[1].Name = "RenderDevice"; + renderProperties[1].Value <<= xDevice; + renderProperties[2].Name = "View"; + renderProperties[2].Value <<= mxController; + renderProperties[3].Name = "RenderToGraphic"; + renderProperties[3].Value <<= true; + + awt::Size aSize; + awt::Size aCalcPageSize; + awt::Point aPos; + awt::Point aCalcPos; + + sal_Int32 nPages = mxRenderable->getRendererCount( selection, renderProperties ); + if (nPages >= nCurrentPage) + { + const Sequence< beans::PropertyValue > aResult = mxRenderable->getRenderer(nCurrentPage - 1, selection, renderProperties ); + for( const auto& rProperty : aResult ) + { + if ( rProperty.Name == "PageSize" ) + { + rProperty.Value >>= aSize; + } + else if (rProperty.Name == "PagePos") + { + rProperty.Value >>= aPos; + } + else if (rProperty.Name == "CalcPagePos") + { + rProperty.Value >>= aCalcPos; + } + else if (rProperty.Name == "CalcPageContentSize") + { + rProperty.Value >>= aCalcPageSize; + } + } + } + + if (pDocumentPosition) + { + *pDocumentPosition = Point(aPos.X, aPos.Y); + } + if (pCalcPagePosition) + { + *pCalcPagePosition = Point(aCalcPos.X, aCalcPos.Y); + } + if (pCalcPageSize) + { + *pCalcPageSize = Size(aCalcPageSize.Width, aCalcPageSize.Height); + } + + return Size( aSize.Width, aSize.Height ); +} + +Graphic DocumentToGraphicRenderer::renderToGraphic( + sal_Int32 nCurrentPage, + Size aDocumentSizePixel, + Size aTargetSizePixel, + Color aPageColor, + bool bExtOutDevData) + +{ + if (!mxModel.is() || !mxController.is() || !mxRenderable.is()) + return Graphic(); + + Reference< awt::XDevice > xDevice(mxToolkit->createScreenCompatibleDevice( aTargetSizePixel.Width(), aTargetSizePixel.Height() ) ); + if (!xDevice.is()) + return Graphic(); + + assert( !aDocumentSizePixel.IsEmpty() && !aTargetSizePixel.IsEmpty()); + + double fScaleX = aTargetSizePixel.Width() / static_cast<double>(aDocumentSizePixel.Width()); + double fScaleY = aTargetSizePixel.Height() / static_cast<double>(aDocumentSizePixel.Height()); + + PropertyValues renderProps; + renderProps.realloc( 6 ); + renderProps[0].Name = "IsPrinter"; + renderProps[0].Value <<= true; + renderProps[1].Name = "RenderDevice"; + renderProps[1].Value <<= xDevice; + renderProps[2].Name = "View"; + renderProps[2].Value <<= mxController; + renderProps[3].Name = "RenderToGraphic"; + renderProps[3].Value <<= true; + renderProps[4].Name = "HasPDFExtOutDevData"; + renderProps[4].Value <<= bExtOutDevData; + renderProps[5].Name = "PageRange"; + renderProps[5].Value <<= OUString::number(nCurrentPage); + + GDIMetaFile aMtf; + + OutputDevice* pOutputDev = VCLUnoHelper::GetOutputDevice( xDevice ); + + vcl::PDFExtOutDevData aPDFExtOutDevData(*pOutputDev); + if (bExtOutDevData) + { + aPDFExtOutDevData.SetIsExportBookmarks(true); + pOutputDev->SetExtOutDevData(&aPDFExtOutDevData); + } + + pOutputDev->SetAntialiasing(pOutputDev->GetAntialiasing() | AntialiasingFlags::EnableB2dDraw); + MapMode mm = pOutputDev->GetMapMode(); + mm.SetScaleX( Fraction(fScaleX) ); + mm.SetScaleY( Fraction(fScaleY) ); + pOutputDev->SetMapMode( mm ); + + aMtf.Record( pOutputDev ); + + if (aPageColor != COL_TRANSPARENT) + { + pOutputDev->SetBackground(Wallpaper(aPageColor)); + pOutputDev->Erase(); + } + + uno::Any aSelection( getSelection()); + mxRenderable->render(nCurrentPage - 1, aSelection, renderProps ); + + aMtf.Stop(); + aMtf.WindStart(); + aMtf.SetPrefSize( aTargetSizePixel ); + + if (bExtOutDevData) + maChapterNames = aPDFExtOutDevData.GetChapterNames(); + + return Graphic(aMtf); +} + +const std::vector<OUString>& DocumentToGraphicRenderer::getChapterNames() const +{ + return maChapterNames; +} + +sal_Int32 DocumentToGraphicRenderer::getCurrentPage() +{ + if (hasSelection()) + return 1; + + if (isWriter()) + return getCurrentPageWriter(); + + /* TODO: other application specific page detection? */ + return 1; +} + +sal_Int32 DocumentToGraphicRenderer::getPageCount() +{ + Reference< awt::XDevice > xDevice(mxToolkit->createScreenCompatibleDevice( 32, 32 ) ); + + uno::Any selection( getSelection() ); + + PropertyValues renderProperties; + + renderProperties.realloc( 4 ); + renderProperties[0].Name = "IsPrinter"; + renderProperties[0].Value <<= true; + renderProperties[1].Name = "RenderDevice"; + renderProperties[1].Value <<= xDevice; + renderProperties[2].Name = "View"; + renderProperties[2].Value <<= mxController; + renderProperties[3].Name = "RenderToGraphic"; + renderProperties[3].Value <<= true; + + sal_Int32 nPages = mxRenderable->getRendererCount( selection, renderProperties ); + + return nPages; +} + +sal_Int32 DocumentToGraphicRenderer::getCurrentPageWriter() +{ + Reference<text::XTextViewCursorSupplier> xTextViewCursorSupplier(mxModel->getCurrentController(), UNO_QUERY); + if (!xTextViewCursorSupplier.is()) + return 1; + Reference<text::XPageCursor> xCursor(xTextViewCursorSupplier->getViewCursor(), UNO_QUERY); + return xCursor.is() ? xCursor->getPage() : 1; +} + +// static +bool DocumentToGraphicRenderer::isShapeSelected( + css::uno::Reference< css::drawing::XShapes > & rxShapes, + css::uno::Reference< css::drawing::XShape > & rxShape, + const css::uno::Reference< css::frame::XController > & rxController ) +{ + bool bShape = false; + if (rxController.is()) + { + uno::Reference< view::XSelectionSupplier > xSelectionSupplier( rxController, uno::UNO_QUERY); + if (xSelectionSupplier.is()) + { + uno::Any aAny( xSelectionSupplier->getSelection()); + if (aAny >>= rxShapes) + bShape = true; + else if (aAny >>= rxShape) + bShape = true; + } + } + return bShape; +} + +bool DocumentToGraphicRenderer::isWriter() const +{ + if (meDocType == WRITER) + return true; + else + return false; +} + +bool DocumentToGraphicRenderer::isCalc() const +{ + if (meDocType == CALC) + return true; + else + return false; +} + +bool DocumentToGraphicRenderer::isImpress() const +{ + if (meDocType == IMPRESS) + return true; + else + return false; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/filter/SvFilterOptionsDialog.cxx b/svtools/source/filter/SvFilterOptionsDialog.cxx new file mode 100644 index 000000000..7203cfd5e --- /dev/null +++ b/svtools/source/filter/SvFilterOptionsDialog.cxx @@ -0,0 +1,289 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <vcl/FilterConfigItem.hxx> +#include <vcl/graphicfilter.hxx> +#include <vcl/svapp.hxx> +#include <FltCallDialogParameter.hxx> +#include "exportdialog.hxx" +#include <tools/fldunit.hxx> +#include <com/sun/star/awt/XWindow.hpp> +#include <com/sun/star/beans/XPropertyAccess.hpp> +#include <com/sun/star/document/XExporter.hpp> +#include <com/sun/star/graphic/XGraphic.hpp> +#include <com/sun/star/lang/XInitialization.hpp> +#include <com/sun/star/lang/XServiceInfo.hpp> +#include <com/sun/star/uno/Sequence.h> +#include <com/sun/star/uno/Any.h> +#include <com/sun/star/ui/dialogs/XExecutableDialog.hpp> +#include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp> +#include <com/sun/star/uno/XComponentContext.hpp> +#include <unotools/localedatawrapper.hxx> +#include <unotools/syslocale.hxx> +#include <cppuhelper/implbase.hxx> +#include <cppuhelper/supportsservice.hxx> + +using namespace ::com::sun::star; + +namespace { + +class SvFilterOptionsDialog : public cppu::WeakImplHelper +< + document::XExporter, + ui::dialogs::XExecutableDialog, + beans::XPropertyAccess, + lang::XInitialization, + lang::XServiceInfo +> +{ + const uno::Reference< uno::XComponentContext > + mxContext; + uno::Sequence< beans::PropertyValue > + maMediaDescriptor; + uno::Sequence< beans::PropertyValue > + maFilterDataSequence; + uno::Reference< lang::XComponent > + mxSourceDocument; + + css::uno::Reference<css::awt::XWindow> mxParent; + FieldUnit meFieldUnit; + bool mbExportSelection; + bool mbGraphicsSource; + +public: + + explicit SvFilterOptionsDialog( const uno::Reference< uno::XComponentContext >& _rxORB ); + + // XInterface + virtual void SAL_CALL acquire() throw() override; + virtual void SAL_CALL release() throw() override; + + // XInitialization + virtual void SAL_CALL initialize( const uno::Sequence< uno::Any > & aArguments ) override; + + // XServiceInfo + virtual OUString SAL_CALL getImplementationName() override; + virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) override; + virtual uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() override; + + // XPropertyAccess + virtual uno::Sequence< beans::PropertyValue > SAL_CALL getPropertyValues() override; + virtual void SAL_CALL setPropertyValues( const uno::Sequence< beans::PropertyValue > & aProps ) override; + + // XExecuteDialog + virtual sal_Int16 SAL_CALL execute() override; + virtual void SAL_CALL setTitle( const OUString& aTitle ) override; + + // XExporter + virtual void SAL_CALL setSourceDocument( const uno::Reference< lang::XComponent >& xDoc ) override; + +}; + +SvFilterOptionsDialog::SvFilterOptionsDialog( const uno::Reference< uno::XComponentContext >& rxContext ) : + mxContext ( rxContext ), + meFieldUnit ( FieldUnit::CM ), + mbExportSelection ( false ), + mbGraphicsSource ( true ) +{ +} + +void SAL_CALL SvFilterOptionsDialog::acquire() throw() +{ + OWeakObject::acquire(); +} + + +void SAL_CALL SvFilterOptionsDialog::release() throw() +{ + OWeakObject::release(); +} + +// XInitialization +void SAL_CALL SvFilterOptionsDialog::initialize(const uno::Sequence<uno::Any>& rArguments) +{ + for(const uno::Any& rArgument : rArguments) + { + beans::PropertyValue aProperty; + if (rArgument >>= aProperty) + { + if( aProperty.Name == "ParentWindow" ) + { + aProperty.Value >>= mxParent; + } + } + } +} + +// XServiceInfo +OUString SAL_CALL SvFilterOptionsDialog::getImplementationName() +{ + return "com.sun.star.svtools.SvFilterOptionsDialog"; +} +sal_Bool SAL_CALL SvFilterOptionsDialog::supportsService( const OUString& rServiceName ) +{ + return cppu::supportsService(this, rServiceName); +} +uno::Sequence< OUString > SAL_CALL SvFilterOptionsDialog::getSupportedServiceNames() +{ + return { "com.sun.star.ui.dialogs.FilterOptionsDialog" }; +} + +// XPropertyAccess +uno::Sequence< beans::PropertyValue > SvFilterOptionsDialog::getPropertyValues() +{ + auto pProp = std::find_if(maMediaDescriptor.begin(), maMediaDescriptor.end(), + [](const beans::PropertyValue& rProp) { return rProp.Name == "FilterData"; }); + auto i = static_cast<sal_Int32>(std::distance(maMediaDescriptor.begin(), pProp)); + sal_Int32 nCount = maMediaDescriptor.getLength(); + if ( i == nCount ) + maMediaDescriptor.realloc( ++nCount ); + + // the "FilterData" Property is an Any that will contain our PropertySequence of Values + maMediaDescriptor[ i ].Name = "FilterData"; + maMediaDescriptor[ i ].Value <<= maFilterDataSequence; + return maMediaDescriptor; +} + +void SvFilterOptionsDialog::setPropertyValues( const uno::Sequence< beans::PropertyValue > & aProps ) +{ + maMediaDescriptor = aProps; + + for ( const auto& rProp : std::as_const(maMediaDescriptor) ) + { + if ( rProp.Name == "FilterData" ) + { + rProp.Value >>= maFilterDataSequence; + } + else if ( rProp.Name == "SelectionOnly" ) + { + rProp.Value >>= mbExportSelection; + } + } +} + +// XExecutableDialog +void SvFilterOptionsDialog::setTitle( const OUString& ) +{ +} + +sal_Int16 SvFilterOptionsDialog::execute() +{ + sal_Int16 nRet = ui::dialogs::ExecutableDialogResults::CANCEL; + + OUString aInternalFilterName; + uno::Reference<graphic::XGraphic> xGraphic; + for ( const auto& rProp : std::as_const(maMediaDescriptor) ) + { + const OUString& rName = rProp.Name; + if ( rName == "FilterName" ) + { + OUString aStr; + rProp.Value >>= aStr; + aInternalFilterName = aStr.replaceFirst( "draw_", "" ); + aInternalFilterName = aInternalFilterName.replaceFirst( "impress_", "" ); + aInternalFilterName = aInternalFilterName.replaceFirst( "calc_", "" ); + aInternalFilterName = aInternalFilterName.replaceFirst( "writer_", "" ); + break; + } + else if ( rName == "Graphic" ) + { + rProp.Value >>= xGraphic; + } + } + if ( !aInternalFilterName.isEmpty() ) + { + GraphicFilter aGraphicFilter( true ); + + sal_uInt16 nFormat, nFilterCount = aGraphicFilter.GetExportFormatCount(); + for ( nFormat = 0; nFormat < nFilterCount; nFormat++ ) + { + if ( aGraphicFilter.GetExportInternalFilterName( nFormat ) == aInternalFilterName ) + break; + } + if ( nFormat < nFilterCount ) + { + FltCallDialogParameter aFltCallDlgPara(Application::GetFrameWeld(mxParent), meFieldUnit); + aFltCallDlgPara.aFilterData = maFilterDataSequence; + aFltCallDlgPara.aFilterExt = aGraphicFilter.GetExportFormatShortName( nFormat ); + bool bIsPixelFormat( aGraphicFilter.IsExportPixelFormat( nFormat ) ); + + ExportDialog aDialog(aFltCallDlgPara, mxContext, mxSourceDocument, mbExportSelection, + bIsPixelFormat, mbGraphicsSource, xGraphic); + if (aDialog.run() == RET_OK) + nRet = ui::dialogs::ExecutableDialogResults::OK; + + // taking the out parameter from the dialog + maFilterDataSequence = aFltCallDlgPara.aFilterData; + } + } + return nRet; +} + +// XEmporter +void SvFilterOptionsDialog::setSourceDocument( const uno::Reference< lang::XComponent >& xDoc ) +{ + mxSourceDocument = xDoc; + + mbGraphicsSource = true; // default Draw and Impress like it was before + + // try to set the corresponding metric unit + OUString aConfigPath; + uno::Reference< lang::XServiceInfo > xServiceInfo + ( xDoc, uno::UNO_QUERY ); + if ( !xServiceInfo.is() ) + return; + + if ( xServiceInfo->supportsService("com.sun.star.presentation.PresentationDocument") ) + aConfigPath = "Office.Impress/Layout/Other/MeasureUnit"; + else if ( xServiceInfo->supportsService("com.sun.star.drawing.DrawingDocument") ) + aConfigPath = "Office.Draw/Layout/Other/MeasureUnit"; + else + { + mbGraphicsSource = false; + if ( xServiceInfo->supportsService("com.sun.star.sheet.SpreadsheetDocument") ) + aConfigPath = "Office.Calc/Layout/Other/MeasureUnit"; + else if ( xServiceInfo->supportsService("com.sun.star.text.TextDocument") ) + aConfigPath = "Office.Writer/Layout/Other/MeasureUnit"; + } + if ( !aConfigPath.isEmpty() ) + { + FilterConfigItem aConfigItem( aConfigPath ); + OUString aPropertyName; + SvtSysLocale aSysLocale; + if ( aSysLocale.GetLocaleDataPtr()->getMeasurementSystemEnum() == MeasurementSystem::Metric ) + aPropertyName = "Metric"; + else + aPropertyName = "NonMetric"; + meFieldUnit = static_cast<FieldUnit>( + aConfigItem.ReadInt32(aPropertyName, sal_Int32(FieldUnit::CM))); + } +} + +} + +extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface * +com_sun_star_svtools_SvFilterOptionsDialog_get_implementation( + css::uno::XComponentContext * context, + css::uno::Sequence<css::uno::Any> const &) +{ + return cppu::acquire(new SvFilterOptionsDialog(context)); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/filter/exportdialog.cxx b/svtools/source/filter/exportdialog.cxx new file mode 100644 index 000000000..b355a16f8 --- /dev/null +++ b/svtools/source/filter/exportdialog.cxx @@ -0,0 +1,1087 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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/config.h> + +#include <algorithm> + +#include <o3tl/safeint.hxx> +#include <tools/stream.hxx> +#include <tools/fract.hxx> +#include <vcl/graphicfilter.hxx> +#include <vcl/FilterConfigItem.hxx> +#include <svtools/strings.hrc> +#include <svtools/svtresid.hxx> +#include <svtools/DocumentToGraphicRenderer.hxx> +#include <com/sun/star/beans/XPropertySet.hpp> +#include <com/sun/star/awt/Size.hpp> +#include <com/sun/star/drawing/GraphicExportFilter.hpp> +#include <com/sun/star/drawing/XDrawView.hpp> +#include <com/sun/star/frame/XModel.hpp> +#include <com/sun/star/frame/XController.hpp> +#include <com/sun/star/graphic/PrimitiveFactory2D.hpp> +#include <com/sun/star/geometry/AffineMatrix2D.hpp> +#include <com/sun/star/io/XStream.hpp> +#include <unotools/streamwrap.hxx> +#include <vcl/svapp.hxx> +#include <vcl/outdev.hxx> +#include <vcl/graph.hxx> +#include <rtl/ustrbuf.hxx> +#include <basegfx/matrix/b2dhommatrix.hxx> +#include "exportdialog.hxx" + +#define FORMAT_UNKNOWN 0 +#define FORMAT_JPG 1 +#define FORMAT_PNG 2 +#define FORMAT_BMP 3 +#define FORMAT_GIF 4 +#define FORMAT_TIF 10 +#define FORMAT_WMF 12 +#define FORMAT_EMF 13 +#define FORMAT_EPS 14 +#define FORMAT_SVG 16 + +#define UNIT_DEFAULT -1 +#define UNIT_INCH 0 +#define UNIT_CM 1 +#define UNIT_MM 2 +#define UNIT_POINT 3 +#define UNIT_PIXEL 4 +#define UNIT_MAX_ID UNIT_PIXEL + +using namespace ::com::sun::star; + +static sal_Int16 GetFilterFormat(const OUString& rExt) +{ + sal_Int16 nFormat = FORMAT_UNKNOWN; + if ( rExt == "JPG" ) + nFormat = FORMAT_JPG; + else if ( rExt == "PNG" ) + nFormat = FORMAT_PNG; + else if ( rExt == "BMP" ) + nFormat = FORMAT_BMP; + else if ( rExt == "GIF" ) + nFormat = FORMAT_GIF; + else if ( rExt == "TIF" ) + nFormat = FORMAT_TIF; + else if ( rExt == "WMF" ) + nFormat = FORMAT_WMF; + else if ( rExt == "EMF" ) + nFormat = FORMAT_EMF; + else if ( rExt == "EPS" ) + nFormat = FORMAT_EPS; + else if ( rExt == "SVG" ) + nFormat = FORMAT_SVG; + return nFormat; +} + +static MapUnit GetMapUnit( sal_Int32 nUnit ) +{ + MapUnit aMapUnit( MapUnit::MapPixel ); + switch( nUnit ) + { + case UNIT_INCH : aMapUnit = MapUnit::MapInch; break; + case UNIT_CM : aMapUnit = MapUnit::MapCM; break; + case UNIT_MM : aMapUnit = MapUnit::MapMM; break; + case UNIT_POINT : aMapUnit = MapUnit::MapPoint; break; + case UNIT_PIXEL : aMapUnit = MapUnit::MapPixel; break; + } + return aMapUnit; +} + +sal_Int32 ExportDialog::GetDefaultUnit() const +{ + sal_Int32 nDefaultUnit = UNIT_CM; + switch( mrFltCallPara.eFieldUnit ) + { +// case FieldUnit::NONE : +// case FieldUnit::PERCENT : +// case FieldUnit::CUSTOM : + default: nDefaultUnit = UNIT_CM; break; + + case FieldUnit::MILE : // PASSTHROUGH INTENDED + case FieldUnit::FOOT : + case FieldUnit::TWIP : + case FieldUnit::PICA : nDefaultUnit = UNIT_INCH; break; + + case FieldUnit::KM : // PASSTHROUGH INTENDED + case FieldUnit::M : + case FieldUnit::MM_100TH : nDefaultUnit = UNIT_CM; break; + + case FieldUnit::INCH : nDefaultUnit = UNIT_INCH; break; + case FieldUnit::CM : nDefaultUnit = UNIT_CM; break; + case FieldUnit::MM : nDefaultUnit = UNIT_MM; break; + case FieldUnit::POINT : nDefaultUnit = UNIT_POINT; break; + } + return nDefaultUnit; +} + +static basegfx::B2DRange GetShapeRangeForXShape( const uno::Reference< drawing::XShape >& rxShape, + const uno::Reference< graphic::XPrimitiveFactory2D >& rxPrimitiveFactory2D, const uno::Sequence< beans::PropertyValue >& rViewInformation ) +{ + basegfx::B2DRange aShapeRange; + + const uno::Sequence< beans::PropertyValue > aParams; + const uno::Sequence< uno::Reference< graphic::XPrimitive2D > > aPrimitiveSequence( rxPrimitiveFactory2D->createPrimitivesFromXShape( rxShape, aParams ) ); + + for( const auto& rPrimitive : aPrimitiveSequence ) + { + const geometry::RealRectangle2D aRect( rPrimitive->getRange( rViewInformation ) ); + aShapeRange.expand( basegfx::B2DTuple( aRect.X1, aRect.Y1 ) ); + aShapeRange.expand( basegfx::B2DTuple( aRect.X2, aRect.Y2 ) ); + } + return aShapeRange; +} + +uno::Sequence< beans::PropertyValue > ExportDialog::GetFilterData( bool bUpdateConfig ) +{ + if ( bUpdateConfig ) + { + sal_Int32 nUnit = mxLbSizeX->get_active(); + if ( nUnit < 0 ) + nUnit = UNIT_CM; + + if ( ( mnInitialResolutionUnit == UNIT_DEFAULT ) && ( nUnit == GetDefaultUnit() ) ) + nUnit = UNIT_DEFAULT; + + // updating ui configuration + if ( mbIsPixelFormat ) + { + if ( nUnit > UNIT_MAX_ID ) + nUnit = UNIT_PIXEL; + + sal_Int32 nResolution = mxNfResolution->get_value(); + if ( nResolution < 1 ) + nResolution = 96; + + mpOptionsItem->WriteInt32("PixelExportUnit", nUnit); + mpOptionsItem->WriteInt32("PixelExportResolution", nResolution); + mpOptionsItem->WriteInt32("PixelExportResolutionUnit", mxLbResolution->get_active()); + } + else + { + if ( nUnit >= UNIT_PIXEL ) + nUnit = UNIT_CM; + + mpOptionsItem->WriteInt32("VectorExportUnit", nUnit); + } + } + + FilterConfigItem* pFilterOptions; + if ( bUpdateConfig ) + pFilterOptions = mpFilterOptionsItem.get(); + else + { + uno::Sequence< beans::PropertyValue > aFilterData( mpFilterOptionsItem->GetFilterData() ); + pFilterOptions = new FilterConfigItem( &aFilterData ); + } + + const OUString sLogicalWidth("LogicalWidth"); + const OUString sLogicalHeight("LogicalHeight"); + if ( mbIsPixelFormat ) + { + pFilterOptions->WriteInt32("PixelWidth", maSize.Width ); + pFilterOptions->WriteInt32("PixelHeight", maSize.Height ); + if ( maResolution.Width && maResolution.Height ) + { + const double f100thmmPerPixelX = 100000.0 / maResolution.Width; + const double f100thmmPerPixelY = 100000.0 / maResolution.Height; + sal_Int32 nLogicalWidth = static_cast< sal_Int32 >( f100thmmPerPixelX * maSize.Width ); + sal_Int32 nLogicalHeight= static_cast< sal_Int32 >( f100thmmPerPixelY * maSize.Height ); + if ( nLogicalWidth && nLogicalHeight ) + { + pFilterOptions->WriteInt32( sLogicalWidth, nLogicalWidth ); + pFilterOptions->WriteInt32( sLogicalHeight, nLogicalHeight ); + } + } + } + else + { + pFilterOptions->WriteInt32( sLogicalWidth, maSize.Width ); + pFilterOptions->WriteInt32( sLogicalHeight, maSize.Height ); + } + switch ( mnFormat ) + { + case FORMAT_JPG : + { + sal_Int32 nColor = mxLbColorDepth->get_active(); + if ( nColor == 1 ) + nColor = 0; + else + nColor = 1; + pFilterOptions->WriteInt32("ColorMode", nColor); + assert(mpSbCompression); + pFilterOptions->WriteInt32("Quality", static_cast<sal_Int32>(mpSbCompression->get_value())); + } + break; + + case FORMAT_PNG : + { + assert(mpSbCompression); + pFilterOptions->WriteInt32("Compression", static_cast<sal_Int32>(mpSbCompression->get_value())); + sal_Int32 nInterlace = 0; + if ( mxCbInterlaced->get_active() ) + nInterlace++; + pFilterOptions->WriteInt32("Interlaced", nInterlace); + sal_Int32 nValue = 0; + if ( mxCbSaveTransparency->get_active() ) + nValue++; + pFilterOptions->WriteInt32("Translucent", nValue); + } + break; + + case FORMAT_BMP : + { + pFilterOptions->WriteInt32("Color", mxLbColorDepth->get_active() + 1); + pFilterOptions->WriteBool("RLE_Coding", mxCbRLEEncoding->get_active()); + } + break; + + case FORMAT_GIF : + { + sal_Int32 nValue = 0; + if ( mxCbInterlaced->get_active() ) + nValue++; + pFilterOptions->WriteInt32("Interlaced", nValue); + + nValue = 0; + if (mxCbSaveTransparency->get_active()) + nValue++; + pFilterOptions->WriteInt32("Translucent", nValue); + } + break; + + case FORMAT_EPS : + { + sal_Int32 nCheck = 0; + if ( mxCbEPSPreviewTIFF->get_active() ) + nCheck++; + if ( mxCbEPSPreviewEPSI->get_active() ) + nCheck += 2; + pFilterOptions->WriteInt32("Preview", nCheck); + + nCheck = 1; + if ( mxRbEPSLevel2->get_active() ) + nCheck++; + pFilterOptions->WriteInt32("Version", nCheck); + + nCheck = 1; + if ( mxRbEPSColorFormat2->get_active() ) + nCheck++; + pFilterOptions->WriteInt32("ColorFormat", nCheck); + + nCheck = 1; + if ( mxRbEPSCompressionNone->get_active() ) + nCheck++; + pFilterOptions->WriteInt32("CompressionMode", nCheck); + } + break; + } + + uno::Sequence< beans::PropertyValue > aRet( pFilterOptions->GetFilterData() ); + if ( !bUpdateConfig ) + delete pFilterOptions; + return aRet; +} + + +awt::Size ExportDialog::GetOriginalSize() +{ + basegfx::B2DRange aShapesRange; + + if ( mxPage.is () ) + { + uno::Reference< beans::XPropertySet > xPagePropSet( mxPage, uno::UNO_QUERY ); + if ( xPagePropSet.is() ) + { + sal_Int32 nWidth = 0; + sal_Int32 nHeight= 0; + css::uno::Any aAny; + aAny = xPagePropSet->getPropertyValue("Width"); + aAny >>= nWidth; + aAny = xPagePropSet->getPropertyValue("Height"); + aAny >>= nHeight; + aShapesRange = basegfx::B2DRange( 0, 0, nWidth, nHeight ); + } + } + else if (mxShapes.is() || mxShape.is()) + { + uno::Reference< graphic::XPrimitiveFactory2D > xPrimitiveFactory = graphic::PrimitiveFactory2D::create( mxContext ); + + basegfx::B2DHomMatrix aViewTransformation( Application::GetDefaultDevice()->GetViewTransformation() ); + css::geometry::AffineMatrix2D aTransformation; + aTransformation.m00 = aViewTransformation.get(0,0); + aTransformation.m01 = aViewTransformation.get(0,1); + aTransformation.m02 = aViewTransformation.get(0,2); + aTransformation.m10 = aViewTransformation.get(1,0); + aTransformation.m11 = aViewTransformation.get(1,1); + aTransformation.m12 = aViewTransformation.get(1,2); + + const OUString sViewTransformation( "ViewTransformation" ); + uno::Sequence< beans::PropertyValue > aViewInformation( 1 ); + aViewInformation[ 0 ].Value <<= aTransformation; + aViewInformation[ 0 ].Name = sViewTransformation; + + if ( mxShape.is() ) + aShapesRange = GetShapeRangeForXShape( mxShape, xPrimitiveFactory, aViewInformation ); + else if ( mxShapes.is() ) + { + const sal_Int32 nCount = mxShapes->getCount(); + for( sal_Int32 nIndex = 0; nIndex < nCount; nIndex++ ) + { + uno::Reference< drawing::XShape > xShape; + mxShapes->getByIndex( nIndex ) >>= xShape; + aShapesRange.expand( GetShapeRangeForXShape( xShape, xPrimitiveFactory, aViewInformation ) ); + } + } + } + else if (!mbGraphicsSource) + { + DocumentToGraphicRenderer aRenderer( mxSourceDocument, mbExportSelection); + const sal_Int32 nCurrentPage = aRenderer.getCurrentPage(); + const Size aSize = aRenderer.getDocumentSizeIn100mm( nCurrentPage); + return awt::Size( aSize.Width(), aSize.Height()); + } + return awt::Size( static_cast<sal_Int32>(aShapesRange.getWidth()), static_cast<sal_Int32>(aShapesRange.getHeight()) ); +} + +void ExportDialog::GetGraphicSource() +{ + if (mxGraphic.is()) + return; + + if ( !mxSourceDocument.is() ) + return; + + uno::Reference< frame::XModel > xModel( mxSourceDocument, uno::UNO_QUERY ); + if ( !xModel.is() ) + return; + + uno::Reference< frame::XController > xController( xModel->getCurrentController() ); + if ( !xController.is() ) + return; + + if ( mbExportSelection ) // check if there is a selection + { + if (DocumentToGraphicRenderer::isShapeSelected( mxShapes, mxShape, xController)) + mbGraphicsSource = true; + } + if ( !mxShape.is() && !mxShapes.is() && mbGraphicsSource ) + { + uno::Reference< drawing::XDrawView > xDrawView( xController, uno::UNO_QUERY ); + if ( xDrawView.is() ) + { + uno::Reference< drawing::XDrawPage > xCurrentPage( xDrawView->getCurrentPage() ); + if ( xCurrentPage.is() ) + { + mxPage = xCurrentPage; // exporting whole page + } + } + } + // For !mbGraphicsSource the mxSourceDocument is used, from + // which XRenderable can query XController and + // XSelectionSupplier the same. +} + +void ExportDialog::GetGraphicStream() +{ + if ( !IsTempExportAvailable() ) + { + mpTempStream.reset(new SvMemoryStream()); + return; + } + + bool bRecreateOutputStream = mpTempStream->Tell() == 0; + + static uno::Sequence< beans::PropertyValue > aOldFilterData; + uno::Sequence< beans::PropertyValue > aNewFilterData( GetFilterData( false ) ); + if ( aOldFilterData != aNewFilterData ) + { + aOldFilterData = aNewFilterData; + bRecreateOutputStream = true; + } + try + { + if ( bRecreateOutputStream ) + { + mpTempStream.reset(new SvMemoryStream()); + + uno::Reference< graphic::XGraphic > xGraphic; + if (!mbGraphicsSource && !mxGraphic.is()) + { + // Create a Graphic to be used below. + DocumentToGraphicRenderer aRenderer( mxSourceDocument, mbExportSelection); + const sal_Int32 nCurrentPage = aRenderer.getCurrentPage(); + const Size aDocumentSizePixel = aRenderer.getDocumentSizeInPixels( nCurrentPage); + + const Size aTargetSizePixel( mbIsPixelFormat ? + Size( maSize.Width, maSize.Height) : + aDocumentSizePixel ); + + Graphic aGraphic( aRenderer.renderToGraphic( nCurrentPage, + aDocumentSizePixel, aTargetSizePixel, COL_WHITE, /*bExtOutDevData=*/false)); + xGraphic = aGraphic.GetXGraphic(); + } + + if ( mxGraphic.is() || xGraphic.is() ) + { + Graphic aGraphic( mxGraphic.is() ? mxGraphic : xGraphic ); + + if ( aGraphic.GetType() == GraphicType::Bitmap ) + { + Size aSizePixel( aGraphic.GetSizePixel() ); + if( maSize.Width && maSize.Height && + ( ( maSize.Width != aSizePixel.Width() ) || + ( maSize.Height != aSizePixel.Height() ) ) ) + { + BitmapEx aBmpEx( aGraphic.GetBitmapEx() ); + // export: use highest quality + aBmpEx.Scale( Size( maSize.Width, maSize.Height ), BmpScaleFlag::Lanczos ); + aGraphic = aBmpEx; + } + } + + GraphicFilter& rFilter = GraphicFilter::GetGraphicFilter(); + const sal_uInt16 nFilter = rFilter.GetExportFormatNumberForShortName( maExt ); + if ( rFilter.IsExportPixelFormat( nFilter ) ) + { + mpTempStream->SetResizeOffset(1024); + mpTempStream->SetStreamSize(1024); + rFilter.ExportGraphic( aGraphic, "", *mpTempStream, nFilter, &aNewFilterData ); + } + } + else + { + uno::Reference< lang::XComponent > xSourceDoc; + if ( mxPage.is() ) + xSourceDoc.set( mxPage, uno::UNO_QUERY_THROW ); + else if ( mxShapes.is() ) + xSourceDoc.set( mxShapes, uno::UNO_QUERY_THROW ); + else if ( mxShape.is() ) + xSourceDoc.set( mxShape, uno::UNO_QUERY_THROW ); + if ( xSourceDoc.is() ) + { + uno::Reference < io::XStream > xStream( new utl::OStreamWrapper( *mpTempStream ) ); + uno::Reference < io::XOutputStream > xOutputStream( xStream->getOutputStream() ); + + OUString sFormat( maExt ); + uno::Sequence< beans::PropertyValue > aDescriptor( 3 ); + aDescriptor[0].Name = "OutputStream"; + aDescriptor[0].Value <<= xOutputStream; + aDescriptor[1].Name = "FilterName"; + aDescriptor[1].Value <<= sFormat; + aDescriptor[2].Name = "FilterData"; + aDescriptor[2].Value <<= aNewFilterData; + + uno::Reference< drawing::XGraphicExportFilter > xGraphicExporter = + drawing::GraphicExportFilter::create( mxContext ); + + xGraphicExporter->setSourceDocument( xSourceDoc ); + xGraphicExporter->filter( aDescriptor ); + } + } + } + } + catch( uno::Exception& ) + { + + // ups + + } +} + +sal_uInt32 ExportDialog::GetRawFileSize() const +{ + sal_uInt64 nRawFileSize = 0; + if ( mbIsPixelFormat ) + { + sal_Int32 nBitsPerPixel = 24; + OUString aEntry(mxLbColorDepth->get_active_text()); + if ( ms1BitThreshold == aEntry ) + nBitsPerPixel = 1; + else if ( ms1BitDithered == aEntry ) + nBitsPerPixel = 1; + else if ( ms4BitGrayscale == aEntry ) + nBitsPerPixel = 4; + else if ( ms4BitColorPalette == aEntry ) + nBitsPerPixel = 8; + else if ( ms8BitGrayscale == aEntry ) + nBitsPerPixel = 8; + else if ( ms8BitColorPalette == aEntry ) + nBitsPerPixel = 8; + else if ( ms24BitColor == aEntry ) + nBitsPerPixel = 24; + + if ( mbIsPixelFormat ) + { + nRawFileSize = ( maSize.Width * nBitsPerPixel + 7 ) &~ 7; // rounding up to 8 bits + nRawFileSize /= 8; // in bytes + nRawFileSize *= maSize.Height; + } + if ( nRawFileSize > SAL_MAX_UINT32 ) + nRawFileSize = 0; + } + return static_cast< sal_uInt32 >( nRawFileSize ); +} + +// checks if the source dimension/resolution is not too big +// to determine the exact graphic output size and preview for jpg +bool ExportDialog::IsTempExportAvailable() const +{ + return GetRawFileSize() < o3tl::make_unsigned( mnMaxFilesizeForRealtimePreview ); +} + +ExportDialog::ExportDialog(FltCallDialogParameter& rPara, + const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const css::uno::Reference< css::lang::XComponent >& rxSourceDocument, + bool bExportSelection, bool bIsPixelFormat, bool bGraphicsSource, + const css::uno::Reference< css::graphic::XGraphic >& rxGraphic) + : GenericDialogController(rPara.pWindow, "svt/ui/graphicexport.ui", "GraphicExportDialog") + , mrFltCallPara(rPara) + , mxContext(rxContext) + , mxSourceDocument(rxSourceDocument) + , mxGraphic(rxGraphic) + , msEstimatedSizePix1(SvtResId(STR_SVT_ESTIMATED_SIZE_PIX_1)) + , msEstimatedSizePix2(SvtResId(STR_SVT_ESTIMATED_SIZE_PIX_2)) + , msEstimatedSizeVec(SvtResId(STR_SVT_ESTIMATED_SIZE_VEC)) + , ms1BitThreshold(SvtResId(STR_SVT_1BIT_THRESHOLD)) + , ms1BitDithered(SvtResId(STR_SVT_1BIT_DITHERED)) + , ms4BitGrayscale(SvtResId(STR_SVT_4BIT_GRAYSCALE)) + , ms4BitColorPalette(SvtResId(STR_SVT_4BIT_COLOR_PALETTE)) + , ms8BitGrayscale(SvtResId(STR_SVT_8BIT_GRAYSCALE)) + , ms8BitColorPalette(SvtResId(STR_SVT_8BIT_COLOR_PALETTE)) + , ms24BitColor(SvtResId(STR_SVT_24BIT_TRUE_COLOR)) + , maExt(rPara.aFilterExt) + , mnFormat(FORMAT_UNKNOWN) + , mnMaxFilesizeForRealtimePreview(0) + , mpTempStream(new SvMemoryStream()) + , maOriginalSize(awt::Size(0, 0)) + , mbIsPixelFormat(bIsPixelFormat) + , mbExportSelection(bExportSelection) + , mbGraphicsSource(bGraphicsSource) + , mpSbCompression(nullptr) + , mpNfCompression(nullptr) + , mxMfSizeX(m_xBuilder->weld_spin_button("widthmf")) + , mxLbSizeX(m_xBuilder->weld_combo_box("widthlb")) + , mxMfSizeY(m_xBuilder->weld_spin_button( "heightmf")) + , mxFtResolution(m_xBuilder->weld_label("resolutionft")) + , mxNfResolution(m_xBuilder->weld_spin_button("resolutionmf")) + , mxLbResolution(m_xBuilder->weld_combo_box("resolutionlb")) + , mxColorDepth(m_xBuilder->weld_widget("colordepth")) + , mxLbColorDepth(m_xBuilder->weld_combo_box("colordepthlb")) + , mxJPGQuality(m_xBuilder->weld_widget("jpgquality")) + , mxPNGCompression(m_xBuilder->weld_widget("pngcompression")) + , mxSbPngCompression(m_xBuilder->weld_scale("compressionpngsb")) + , mxNfPngCompression(m_xBuilder->weld_spin_button("compressionpngnf")) + , mxSbJpgCompression(m_xBuilder->weld_scale("compressionjpgsb")) + , mxNfJpgCompression(m_xBuilder->weld_spin_button("compressionjpgnf")) + , mxMode(m_xBuilder->weld_widget("mode")) + , mxCbInterlaced(m_xBuilder->weld_check_button("interlacedcb")) + , mxBMPCompression(m_xBuilder->weld_widget("bmpcompression")) + , mxCbRLEEncoding(m_xBuilder->weld_check_button("rlecb")) + , mxDrawingObjects(m_xBuilder->weld_widget("drawingobjects")) + , mxCbSaveTransparency(m_xBuilder->weld_check_button("savetransparencycb")) + , mxEncoding(m_xBuilder->weld_widget("encoding")) + , mxRbBinary(m_xBuilder->weld_radio_button("binarycb")) + , mxRbText(m_xBuilder->weld_radio_button("textcb")) + , mxEPSGrid(m_xBuilder->weld_widget("epsgrid")) + , mxCbEPSPreviewTIFF(m_xBuilder->weld_check_button("tiffpreviewcb")) + , mxCbEPSPreviewEPSI(m_xBuilder->weld_check_button("epsipreviewcb")) + , mxRbEPSLevel1(m_xBuilder->weld_radio_button("level1rb")) + , mxRbEPSLevel2(m_xBuilder->weld_radio_button("level2rb")) + , mxRbEPSColorFormat1(m_xBuilder->weld_radio_button("color1rb")) + , mxRbEPSColorFormat2(m_xBuilder->weld_radio_button("color2rb")) + , mxRbEPSCompressionLZW(m_xBuilder->weld_radio_button("compresslzw")) + , mxRbEPSCompressionNone(m_xBuilder->weld_radio_button("compressnone")) + , mxInfo(m_xBuilder->weld_widget("information")) + , mxFtEstimatedSize(m_xBuilder->weld_label("estsizeft")) + , mxBtnOK(m_xBuilder->weld_button("ok")) +{ + GetGraphicSource(); + + maExt = maExt.toAsciiUpperCase(); + + OUString aFilterConfigPath( "Office.Common/Filter/Graphic/Export/" ); + mpOptionsItem.reset(new FilterConfigItem( aFilterConfigPath, &rPara.aFilterData )); + aFilterConfigPath += maExt; + mpFilterOptionsItem.reset(new FilterConfigItem( aFilterConfigPath, &rPara.aFilterData )); + + mnInitialResolutionUnit = mbIsPixelFormat + ? mpOptionsItem->ReadInt32("PixelExportUnit", UNIT_DEFAULT) + : mpOptionsItem->ReadInt32("VectorExportUnit", UNIT_DEFAULT); + + mnMaxFilesizeForRealtimePreview = std::max( + mpOptionsItem->ReadInt32("MaxFilesizeForRealtimePreview", 0), sal_Int32(0)); + mxFtEstimatedSize->set_label(" \n "); + + m_xDialog->set_title(m_xDialog->get_title().replaceFirst("%1", maExt)); //Set dialog title + + mnFormat = GetFilterFormat( maExt ); + + Size aResolution( Application::GetDefaultDevice()->LogicToPixel(Size(100, 100), MapMode(MapUnit::MapCM)) ); + maResolution.Width = aResolution.Width(); + maResolution.Height= aResolution.Height(); + + if ( mxGraphic.is() ) + { + Graphic aGraphic(mxGraphic); + Size aSize = aGraphic.GetSizePixel(); + maSize = awt::Size(aSize.getWidth(), aSize.getHeight()); + double f100thmmPerPixel = 100000.0 / static_cast< double >( maResolution.Width ); + maOriginalSize = awt::Size( + static_cast< sal_Int32 >( f100thmmPerPixel * maSize.Width ), + static_cast< sal_Int32 >( f100thmmPerPixel * maSize.Height ) ); + } + else + { + maOriginalSize = GetOriginalSize(); + if ( bIsPixelFormat ) + { + double fPixelsPer100thmm = static_cast< double >( maResolution.Width ) / 100000.0; + maSize = awt::Size( static_cast< sal_Int32 >( ( fPixelsPer100thmm * maOriginalSize.Width ) + 0.5 ), + static_cast< sal_Int32 >( ( fPixelsPer100thmm * maOriginalSize.Height ) + 0.5 ) ); + } + else + { + maSize = maOriginalSize; + } + } + setupControls(); + + // Size + mxLbSizeX->connect_changed( LINK( this, ExportDialog, SelectListBoxHdl ) ); + + if (mpSbCompression) + mpSbCompression->connect_value_changed(LINK(this, ExportDialog, SbCompressionUpdateHdl)); + if (mpNfCompression) + mpNfCompression->connect_value_changed(LINK(this, ExportDialog, SelectHdl)); + + mxMfSizeX->connect_value_changed( LINK( this, ExportDialog, UpdateHdlMtfSizeX ) ); + mxMfSizeY->connect_value_changed( LINK( this, ExportDialog, UpdateHdlMtfSizeY ) ); + + mxNfResolution->connect_value_changed( LINK( this, ExportDialog, UpdateHdlNfResolution ) ); + mxLbResolution->connect_changed( LINK( this, ExportDialog, SelectListBoxHdl ) ); + + mxLbColorDepth->connect_changed( LINK( this, ExportDialog, SelectListBoxHdl ) ); + + mxCbInterlaced->connect_toggled( LINK( this, ExportDialog, UpdateHdl ) ); + + mxCbSaveTransparency->connect_toggled( LINK( this, ExportDialog, UpdateHdl ) ); + + mxCbEPSPreviewTIFF->connect_toggled( LINK( this, ExportDialog, UpdateHdl ) ); + mxCbEPSPreviewEPSI->connect_toggled( LINK( this, ExportDialog, UpdateHdl ) ); + + mxRbEPSCompressionLZW->connect_toggled( LINK( this, ExportDialog, UpdateHdl ) ); + mxRbEPSCompressionNone->connect_toggled( LINK( this, ExportDialog, UpdateHdl ) ); + + mxRbBinary->connect_toggled( LINK( this, ExportDialog, UpdateHdl ) ); + mxRbText->connect_toggled( LINK( this, ExportDialog, UpdateHdl ) ); + + // BMP + mxCbRLEEncoding->connect_toggled( LINK( this, ExportDialog, UpdateHdl ) ); + + // EPS + mxRbEPSLevel1->connect_toggled( LINK( this, ExportDialog, UpdateHdl ) ); + mxRbEPSLevel2->connect_toggled( LINK( this, ExportDialog, UpdateHdl ) ); + + mxBtnOK->connect_clicked( LINK( this, ExportDialog, OK ) ); + + updateControls(); +} + +void ExportDialog::setupSizeControls() +{ + sal_Int32 nUnit = mnInitialResolutionUnit; + if (nUnit == UNIT_DEFAULT) + nUnit = GetDefaultUnit(); + + if (!mbIsPixelFormat) + { + mxFtResolution->hide(); + mxNfResolution->hide(); + mxLbResolution->hide(); + mxLbSizeX->remove( UNIT_PIXEL ); // removing pixel + if ( nUnit >= UNIT_PIXEL ) + nUnit = UNIT_CM; + } + else if ( nUnit > UNIT_MAX_ID ) + nUnit = UNIT_PIXEL; + if ( nUnit < 0 ) + nUnit = UNIT_CM; + mxLbSizeX->set_active( static_cast< sal_uInt16 >( nUnit ) ); + + if ( !mbIsPixelFormat ) // TODO: (metafileresolutionsupport) should be supported for vector formats also... this makes + return; + +// sense eg for bitmap fillings in metafiles, to preserve high dpi output + // (atm without special vector support the bitmaps are rendered with 96dpi) + sal_Int32 nResolution = mpOptionsItem->ReadInt32("PixelExportResolution", 96); + if ( nResolution < 1 ) + nResolution = 96; + mxNfResolution->set_value( nResolution ); + + sal_Int32 nResolutionUnit = mpOptionsItem->ReadInt32("PixelExportResolutionUnit", 1); + if ( ( nResolutionUnit < 0 ) || ( nResolutionUnit > 2 ) ) + nResolutionUnit = 1; + mxLbResolution->set_active( static_cast< sal_uInt16 >( nResolutionUnit ) ); +} + +void ExportDialog::createFilterOptions() +{ + switch( mnFormat ) + { + case FORMAT_JPG : + { + sal_Int32 nColor = mpFilterOptionsItem->ReadInt32("ColorMode", 0); + if ( nColor == 1 ) + nColor = 0; + else + nColor = 1; + mxLbColorDepth->append_text( ms8BitGrayscale ); + mxLbColorDepth->append_text( ms24BitColor ); + mxLbColorDepth->set_active( nColor ); + mxColorDepth->show(); + + // Quality + mxJPGQuality->show(); + sal_Int32 nQuality = mpFilterOptionsItem->ReadInt32("Quality", 75); + if ((nQuality < 1 ) || (nQuality > 100)) + nQuality = 75; + mpSbCompression = mxSbJpgCompression.get(); + mpNfCompression = mxNfJpgCompression.get(); + mpSbCompression->set_range(1, 100); + mpNfCompression->set_range(1, 100); + mpNfCompression->set_value(nQuality); + } + break; + case FORMAT_PNG : + { + // Compression 1..9 + mxPNGCompression->show(); + sal_Int32 nCompression = mpFilterOptionsItem->ReadInt32("Compression", 6); + if ( ( nCompression < 1 ) || ( nCompression > 9 ) ) + nCompression = 6; + + mpSbCompression = mxSbPngCompression.get(); + mpNfCompression = mxNfPngCompression.get(); + mpSbCompression->set_range(1, 9); + mpNfCompression->set_range(1, 9); + mpNfCompression->set_value(nCompression); + + // Interlaced + mxMode->show(); + mxCbInterlaced->set_active(mpFilterOptionsItem->ReadInt32("Interlaced", 0) != 0); + + // Transparency + mxDrawingObjects->show(); + mxCbSaveTransparency->set_active(mpFilterOptionsItem->ReadInt32("Translucent", 1) != 0); + } + break; + case FORMAT_BMP : + { + sal_Int32 nColor = mpFilterOptionsItem->ReadInt32("Color", 0); + if ( nColor == 0 ) + nColor = 6; + else + nColor--; + mxLbColorDepth->append_text( ms1BitThreshold ); + mxLbColorDepth->append_text( ms1BitDithered ); + mxLbColorDepth->append_text( ms4BitGrayscale ); + mxLbColorDepth->append_text( ms4BitColorPalette ); + mxLbColorDepth->append_text( ms8BitGrayscale ); + mxLbColorDepth->append_text( ms8BitColorPalette ); + mxLbColorDepth->append_text( ms24BitColor ); + mxLbColorDepth->set_active( nColor ); + mxColorDepth->show(); + + // RLE coding + mxBMPCompression->show(); + mxCbRLEEncoding->set_active(mpFilterOptionsItem->ReadBool("RLE_Coding", true)); + } + break; + case FORMAT_GIF : + { + // Interlaced + mxMode->show(); + mxCbInterlaced->set_active(mpFilterOptionsItem->ReadInt32("Interlaced", 1) != 0); + + // Transparency + mxDrawingObjects->show(); + mxCbSaveTransparency->set_active(mpFilterOptionsItem->ReadInt32("Translucent", 1) != 0); + } + break; + case FORMAT_EPS : + { + mxEPSGrid->show(); + + sal_Int32 nPreview = mpFilterOptionsItem->ReadInt32("Preview", 0); + sal_Int32 nVersion = mpFilterOptionsItem->ReadInt32("Version", 2); + sal_Int32 nColor = mpFilterOptionsItem->ReadInt32("ColorFormat", 0); + sal_Int32 nCompr = mpFilterOptionsItem->ReadInt32("CompressionMode", 2); + + mpFilterOptionsItem->ReadInt32("TextMode", 0); + + mxCbEPSPreviewTIFF->set_active( ( nPreview & 1 ) != 0 ); + mxCbEPSPreviewEPSI->set_active( ( nPreview & 2 ) != 0 ); + + mxRbEPSLevel1->set_active( nVersion == 1 ); + mxRbEPSLevel2->set_active( nVersion == 2 ); + + mxRbEPSColorFormat1->set_active( nColor == 1 ); + mxRbEPSColorFormat2->set_active( nColor != 1 ); + + mxRbEPSCompressionLZW->set_active( nCompr == 1 ); + mxRbEPSCompressionNone->set_active( nCompr != 1 ); + } + break; + } +} + +void ExportDialog::setupControls() +{ + setupSizeControls(); + createFilterOptions(); + + if (mnMaxFilesizeForRealtimePreview || mbIsPixelFormat) + mxInfo->show(); +} + +static OUString ImpValueOfInKB( sal_Int64 rVal ) +{ + double fVal( static_cast<double>( rVal ) ); + fVal /= ( 1 << 10 ); + fVal += 0.05; + OUStringBuffer aVal( OUString::number( fVal ) ); + sal_Int32 nX( OUString( aVal.getStr() ).indexOf( '.' ) ); + if ( nX > 0 ) + aVal.setLength( nX + 2 ); + return aVal.makeStringAndClear(); +} + +void ExportDialog::updateControls() +{ + // Size Controls + if ( !mbIsPixelFormat ) + { + awt::Size aSize100thmm( maSize ); + Size aSize( OutputDevice::LogicToLogic( Size(aSize100thmm.Width * 100, aSize100thmm.Height * 100), + MapMode(MapUnit::Map100thMM), + MapMode( GetMapUnit( mxLbSizeX->get_active() ) ) ) ); + mxMfSizeX->set_value( aSize.Width() ); + mxMfSizeY->set_value( aSize.Height() ); + } + else + { + MapUnit aMapUnit( GetMapUnit( mxLbSizeX->get_active() ) ); + if ( aMapUnit == MapUnit::MapPixel ) + { // calculating pixel count via resolution and original graphic size + mxMfSizeX->set_digits( 0 ); + mxMfSizeY->set_digits( 0 ); + mxMfSizeX->set_value( maSize.Width ); + mxMfSizeY->set_value( maSize.Height ); + } + else + { + mxMfSizeX->set_digits( 2 ); + mxMfSizeY->set_digits( 2 ); + double fRatio; + switch( GetMapUnit( mxLbSizeX->get_active() ) ) + { + case MapUnit::MapInch : fRatio = static_cast< double >( maResolution.Width ) * 0.0254; break; + case MapUnit::MapMM : fRatio = static_cast< double >( maResolution.Width ) * 0.001; break; + case MapUnit::MapPoint :fRatio = ( static_cast< double >( maResolution.Width ) * 0.0254 ) / 72.0; break; + default: + case MapUnit::MapCM : fRatio = static_cast< double >( maResolution.Width ) * 0.01; break; + } + mxMfSizeX->set_value( static_cast< sal_Int32 >( ( static_cast< double >( maSize.Width * 100 ) / fRatio ) + 0.5 ) ); + mxMfSizeY->set_value( static_cast< sal_Int32 >( ( static_cast< double >( maSize.Height * 100 ) / fRatio ) + 0.5 ) ); + } + } + sal_Int32 nResolution = 0; + switch( mxLbResolution->get_active() ) + { + case 0 : nResolution = maResolution.Width / 100; break; // pixels / cm + case 2 : nResolution = maResolution.Width; break; // pixels / meter + default: + case 1 : nResolution = static_cast< sal_Int32 >(maResolution.Width * 0.0254); break; // pixels / inch + } + mxNfResolution->set_value( nResolution ); + + if (mpSbCompression && mpSbCompression->get_visible() && mpNfCompression) + mpSbCompression->set_value(mpNfCompression->get_value()); + + GetGraphicStream(); + + // updating estimated size + sal_Int64 nRealFileSize( mpTempStream->Tell() ); + if ( mbIsPixelFormat ) + { + OUString aEst( nRealFileSize ? msEstimatedSizePix2 : msEstimatedSizePix1 ); + sal_Int64 nRawFileSize( GetRawFileSize() ); + sal_Int32 nInd = aEst.indexOf( "%" ); + if (nInd != -1) + aEst = aEst.replaceAt( nInd, 2, ImpValueOfInKB( nRawFileSize ) ); + + if ( nRealFileSize && nInd != -1 ) + { + nInd = aEst.indexOf( "%", nInd ); + if (nInd != -1) + aEst = aEst.replaceAt( nInd, 2, ImpValueOfInKB( nRealFileSize ) ); + } + mxFtEstimatedSize->set_label( aEst ); + } + else + { + if ( mnMaxFilesizeForRealtimePreview ) + { + OUString aEst( msEstimatedSizeVec ); + sal_Int32 nInd = aEst.indexOf( "%" ); + if (nInd != -1) + aEst = aEst.replaceAt( nInd, 2, ImpValueOfInKB( nRealFileSize ) ); + mxFtEstimatedSize->set_label( aEst ); + } + } + + // EPS + if ( mxRbEPSLevel1->get_visible() ) + { + bool bEnabled = !mxRbEPSLevel1->get_active(); + mxRbEPSColorFormat1->set_sensitive( bEnabled ); + mxRbEPSColorFormat2->set_sensitive( bEnabled ); + mxRbEPSCompressionLZW->set_sensitive( bEnabled ); + mxRbEPSCompressionNone->set_sensitive( bEnabled ); + } +} + +ExportDialog::~ExportDialog() +{ +} + +/************************************************************************* +|* +|* stores values set in the ini-file +|* +\************************************************************************/ +IMPL_LINK_NOARG(ExportDialog, SelectHdl, weld::SpinButton&, void) +{ + updateControls(); +} + +IMPL_LINK_NOARG(ExportDialog, SelectListBoxHdl, weld::ComboBox&, void) +{ + updateControls(); +} + +IMPL_LINK_NOARG(ExportDialog, UpdateHdl, weld::ToggleButton&, void) +{ + updateControls(); +} + +IMPL_LINK_NOARG(ExportDialog, UpdateHdlMtfSizeX, weld::SpinButton&, void) +{ + double fRatio = static_cast< double >( maOriginalSize.Height ) / maOriginalSize.Width; + + if ( mbIsPixelFormat ) + { + switch( GetMapUnit( mxLbSizeX->get_active() ) ) + { + case MapUnit::MapInch : maSize.Width = static_cast< sal_Int32 >( static_cast< double >( maResolution.Width ) * 0.0254 * mxMfSizeX->get_value() / 100.0 + 0.5 ); break; + case MapUnit::MapCM : maSize.Width = static_cast< sal_Int32 >( static_cast< double >( maResolution.Width ) * 0.01 * mxMfSizeX->get_value() / 100.0 + 0.5 ); break; + case MapUnit::MapMM : maSize.Width = static_cast< sal_Int32 >( static_cast< double >( maResolution.Width ) * 0.001 * mxMfSizeX->get_value() / 100.0 + 0.5 ); break; + case MapUnit::MapPoint : maSize.Width = static_cast< sal_Int32 >( static_cast< double >( maResolution.Width ) * 0.0254 * mxMfSizeX->get_value() / 100.0 * 72 + 0.5 ); break; + default: + case MapUnit::MapPixel : maSize.Width = mxMfSizeX->get_value(); break; + } + maSize.Height = static_cast< sal_Int32 >( fRatio * maSize.Width + 0.5 ); + } + else + { + Fraction aFract( 1, 100 ); + sal_Int32 nWidth = mxMfSizeX->get_value(); + sal_Int32 nHeight= static_cast< sal_Int32 >( nWidth * fRatio ); + const Size aSource( nWidth, nHeight ); + MapMode aSourceMapMode( GetMapUnit( mxLbSizeX->get_active() ),Point(), aFract, aFract ); + Size aDest(OutputDevice::LogicToLogic(aSource, aSourceMapMode, MapMode(MapUnit::Map100thMM))); + + maSize.Width = aDest.Width(); + maSize.Height = aDest.Height(); + } + updateControls(); +} + +IMPL_LINK_NOARG(ExportDialog, UpdateHdlMtfSizeY, weld::SpinButton&, void) +{ + double fRatio = static_cast< double >( maOriginalSize.Width ) / maOriginalSize.Height; + + if ( mbIsPixelFormat ) + { + switch( GetMapUnit( mxLbSizeX->get_active() ) ) + { + case MapUnit::MapInch : maSize.Height = static_cast< sal_Int32 >( static_cast< double >( maResolution.Height ) * 0.0254 * mxMfSizeY->get_value() / 100.0 + 0.5 ); break; + case MapUnit::MapCM : maSize.Height = static_cast< sal_Int32 >( static_cast< double >( maResolution.Height ) * 0.01 * mxMfSizeY->get_value() / 100.0 + 0.5 ); break; + case MapUnit::MapMM : maSize.Height = static_cast< sal_Int32 >( static_cast< double >( maResolution.Height ) * 0.001 * mxMfSizeY->get_value() / 100.0 + 0.5 ); break; + case MapUnit::MapPoint : maSize.Height = static_cast< sal_Int32 >( static_cast< double >( maResolution.Height ) * 0.0254 * mxMfSizeY->get_value() / 100.0 * 72 + 0.5 ); break; + default: + case MapUnit::MapPixel : maSize.Height = mxMfSizeY->get_value(); break; + } + maSize.Width = static_cast< sal_Int32 >( fRatio * maSize.Height + 0.5 ); + } + else + { + Fraction aFract( 1, 100 ); + sal_Int32 nHeight= mxMfSizeY->get_value(); + sal_Int32 nWidth = static_cast< sal_Int32 >( nHeight * fRatio ); + const Size aSource( nWidth, nHeight ); + MapMode aSourceMapMode( GetMapUnit( mxLbSizeX->get_active() ),Point(), aFract, aFract ); + Size aDest( OutputDevice::LogicToLogic(aSource, aSourceMapMode, MapMode(MapUnit::Map100thMM)) ); + + maSize.Height = aDest.Height(); + maSize.Width = aDest.Width(); + } + updateControls(); +} + +IMPL_LINK_NOARG(ExportDialog, UpdateHdlNfResolution, weld::SpinButton&, void) +{ + auto nResolution = mxNfResolution->get_value(); + if ( mxLbResolution->get_active() == 0 ) // pixels / cm + nResolution *= 100; + else if ( mxLbResolution->get_active() == 1 ) // pixels / inch + nResolution = static_cast< sal_Int32 >( ( ( static_cast< double >( nResolution ) + 0.5 ) / 0.0254 ) ); + maResolution.Width = nResolution; + maResolution.Height= nResolution; + + updateControls(); +} + +IMPL_LINK_NOARG(ExportDialog, SbCompressionUpdateHdl, weld::Scale&, void) +{ + mpNfCompression->set_value(mpSbCompression->get_value()); + updateControls(); +} + +IMPL_LINK_NOARG(ExportDialog, OK, weld::Button&, void) +{ + // writing config parameter + + mrFltCallPara.aFilterData = GetFilterData( true ); + m_xDialog->response(RET_OK); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/filter/exportdialog.hxx b/svtools/source/filter/exportdialog.hxx new file mode 100644 index 000000000..137279ee6 --- /dev/null +++ b/svtools/source/filter/exportdialog.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 . + */ + + +#pragma once + +#include <FltCallDialogParameter.hxx> +#include <vcl/weld.hxx> +#include <tools/stream.hxx> +#include <com/sun/star/lang/XComponent.hpp> +#include <com/sun/star/drawing/XShape.hpp> +#include <com/sun/star/drawing/XShapes.hpp> +#include <com/sun/star/drawing/XDrawPage.hpp> +#include <com/sun/star/uno/XComponentContext.hpp> + +#include <memory> + +/************************************************************************* +|* +|* dialog to set filter options for pixel formats +|* +\************************************************************************/ + +class FilterConfigItem; +class ExportDialog : public weld::GenericDialogController +{ +private: + + FltCallDialogParameter& mrFltCallPara; + + const css::uno::Reference< css::uno::XComponentContext > + mxContext; + const css::uno::Reference< css::lang::XComponent >& + mxSourceDocument; + const css::uno::Reference< css::graphic::XGraphic >& + mxGraphic; + + OUString msEstimatedSizePix1; + OUString msEstimatedSizePix2; + OUString msEstimatedSizeVec; + + OUString ms1BitThreshold; + OUString ms1BitDithered; + OUString ms4BitGrayscale; + OUString ms4BitColorPalette; + OUString ms8BitGrayscale; + OUString ms8BitColorPalette; + OUString ms24BitColor; + + std::unique_ptr<FilterConfigItem> mpOptionsItem; + std::unique_ptr<FilterConfigItem> mpFilterOptionsItem; + + OUString maExt; + sal_Int16 mnFormat; + sal_Int32 mnMaxFilesizeForRealtimePreview; + + std::unique_ptr<SvMemoryStream> mpTempStream; + + css::awt::Size maOriginalSize; // the original graphic size in 1/100mm + css::awt::Size maSize; // for vector graphics it always contains the logical size in 1/100mm + + bool mbIsPixelFormat; + bool mbExportSelection; + bool mbGraphicsSource; // whether source document is graphics (Draw, Impress) or not (Calc, Writer) + + sal_Int32 mnInitialResolutionUnit; + + // for pixel graphics it always contains the pixel count + css::awt::Size maResolution; // it always contains the number of pixels per meter + + css::uno::Reference< css::drawing::XShape > + mxShape; + css::uno::Reference< css::drawing::XShapes > + mxShapes; + css::uno::Reference< css::drawing::XDrawPage > + mxPage; + + weld::Scale* mpSbCompression; + weld::SpinButton* mpNfCompression; + + std::unique_ptr<weld::SpinButton> mxMfSizeX; + std::unique_ptr<weld::ComboBox> mxLbSizeX; + std::unique_ptr<weld::SpinButton> mxMfSizeY; + std::unique_ptr<weld::Label> mxFtResolution; + std::unique_ptr<weld::SpinButton> mxNfResolution; + std::unique_ptr<weld::ComboBox> mxLbResolution; + + std::unique_ptr<weld::Widget> mxColorDepth; + std::unique_ptr<weld::ComboBox> mxLbColorDepth; + + std::unique_ptr<weld::Widget> mxJPGQuality; + std::unique_ptr<weld::Widget> mxPNGCompression; + + std::unique_ptr<weld::Scale> mxSbPngCompression; + std::unique_ptr<weld::SpinButton> mxNfPngCompression; + + std::unique_ptr<weld::Scale> mxSbJpgCompression; + std::unique_ptr<weld::SpinButton> mxNfJpgCompression; + + std::unique_ptr<weld::Widget> mxMode; + std::unique_ptr<weld::CheckButton> mxCbInterlaced; + + std::unique_ptr<weld::Widget> mxBMPCompression; + std::unique_ptr<weld::CheckButton> mxCbRLEEncoding; + + std::unique_ptr<weld::Widget> mxDrawingObjects; + std::unique_ptr<weld::CheckButton> mxCbSaveTransparency; + + std::unique_ptr<weld::Widget> mxEncoding; + std::unique_ptr<weld::RadioButton> mxRbBinary; + std::unique_ptr<weld::RadioButton> mxRbText; + + std::unique_ptr<weld::Widget> mxEPSGrid; + std::unique_ptr<weld::CheckButton> mxCbEPSPreviewTIFF; + std::unique_ptr<weld::CheckButton> mxCbEPSPreviewEPSI; + std::unique_ptr<weld::RadioButton> mxRbEPSLevel1; + std::unique_ptr<weld::RadioButton> mxRbEPSLevel2; + std::unique_ptr<weld::RadioButton> mxRbEPSColorFormat1; + std::unique_ptr<weld::RadioButton> mxRbEPSColorFormat2; + std::unique_ptr<weld::RadioButton> mxRbEPSCompressionLZW; + std::unique_ptr<weld::RadioButton> mxRbEPSCompressionNone; + + std::unique_ptr<weld::Widget> mxInfo; + std::unique_ptr<weld::Label> mxFtEstimatedSize; + + std::unique_ptr<weld::Button> mxBtnOK; + + DECL_LINK(UpdateHdl, weld::ToggleButton&, void); + DECL_LINK(SelectListBoxHdl, weld::ComboBox&, void); + DECL_LINK(SelectHdl, weld::SpinButton&, void); + DECL_LINK(UpdateHdlMtfSizeX, weld::SpinButton&, void); + DECL_LINK(UpdateHdlMtfSizeY, weld::SpinButton&, void); + DECL_LINK(UpdateHdlNfResolution, weld::SpinButton&, void); + DECL_LINK(SbCompressionUpdateHdl, weld::Scale&, void); + + DECL_LINK(OK, weld::Button&, void); + + void setupSizeControls(); + void createFilterOptions(); + void setupControls(); + void updateControls(); + + void GetGraphicSource(); + void GetGraphicStream(); + css::uno::Sequence< css::beans::PropertyValue > + GetFilterData( bool bUpdateConfig ); + + sal_uInt32 GetRawFileSize() const; + bool IsTempExportAvailable() const; + + css::awt::Size GetOriginalSize(); + + sal_Int32 GetDefaultUnit() const; + +public: + ExportDialog( FltCallDialogParameter& rPara, + const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const css::uno::Reference< css::lang::XComponent >& rxSourceDocument, + bool bExportSelection, bool bIsExportVectorFormat, bool bGraphicsSource, + const css::uno::Reference< css::graphic::XGraphic >& rxGraphic); + virtual ~ExportDialog() override; +}; + + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/graphic/renderer.cxx b/svtools/source/graphic/renderer.cxx new file mode 100644 index 000000000..c197e6e0c --- /dev/null +++ b/svtools/source/graphic/renderer.cxx @@ -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 . + */ + + +#include <com/sun/star/awt/Rectangle.hpp> +#include <com/sun/star/awt/XDevice.hpp> +#include <com/sun/star/graphic/XGraphic.hpp> +#include <com/sun/star/graphic/XGraphicRenderer.hpp> +#include <com/sun/star/lang/XServiceInfo.hpp> +#include <com/sun/star/uno/XComponentContext.hpp> +#include <tools/gen.hxx> +#include <vcl/svapp.hxx> +#include <toolkit/helper/vclunohelper.hxx> +#include <comphelper/propertysethelper.hxx> +#include <comphelper/propertysetinfo.hxx> +#include <cppuhelper/supportsservice.hxx> +#include <cppuhelper/weakagg.hxx> +#include <rtl/ref.hxx> +#include <vcl/GraphicObject.hxx> +#include <vcl/outdev.hxx> + +#define UNOGRAPHIC_DEVICE 1 +#define UNOGRAPHIC_DESTINATIONRECT 2 +#define UNOGRAPHIC_RENDERDATA 3 + +using namespace ::com::sun::star; + +namespace { + +class GraphicRendererVCL : public ::cppu::OWeakAggObject, + public css::lang::XServiceInfo, + public css::lang::XTypeProvider, + public ::comphelper::PropertySetHelper, + public css::graphic::XGraphicRenderer +{ + static rtl::Reference<::comphelper::PropertySetInfo> createPropertySetInfo(); + +public: + + GraphicRendererVCL(); + + // 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() throw() override; + virtual void SAL_CALL release() throw() 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; + + // XTypeProvider + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes( ) override; + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) override; + + // PropertySetHelper + virtual void _setPropertyValues( const comphelper::PropertyMapEntry** ppEntries, const css::uno::Any* pValues ) override; + virtual void _getPropertyValues( const comphelper::PropertyMapEntry** ppEntries, css::uno::Any* pValue ) override; + + // XGraphicRenderer + virtual void SAL_CALL render( const css::uno::Reference< css::graphic::XGraphic >& Graphic ) override; + +private: + + css::uno::Reference< css::awt::XDevice > mxDevice; + + VclPtr<OutputDevice> mpOutDev; + tools::Rectangle maDestRect; + css::uno::Any maRenderData; +}; + +GraphicRendererVCL::GraphicRendererVCL() : + ::comphelper::PropertySetHelper( createPropertySetInfo() ), + mpOutDev( nullptr ) +{ +} + +uno::Any SAL_CALL GraphicRendererVCL::queryAggregation( const uno::Type & rType ) +{ + uno::Any aAny; + + if( rType == cppu::UnoType<lang::XServiceInfo>::get()) + aAny <<= uno::Reference< lang::XServiceInfo >(this); + else if( rType == cppu::UnoType<lang::XTypeProvider>::get()) + aAny <<= uno::Reference< lang::XTypeProvider >(this); + else if( rType == cppu::UnoType<beans::XPropertySet>::get()) + aAny <<= uno::Reference< beans::XPropertySet >(this); + else if( rType == cppu::UnoType<beans::XPropertyState>::get()) + aAny <<= uno::Reference< beans::XPropertyState >(this); + else if( rType == cppu::UnoType<beans::XMultiPropertySet>::get()) + aAny <<= uno::Reference< beans::XMultiPropertySet >(this); + else if( rType == cppu::UnoType<graphic::XGraphicRenderer>::get()) + aAny <<= uno::Reference< graphic::XGraphicRenderer >(this); + else + aAny = OWeakAggObject::queryAggregation( rType ); + + return aAny; +} + + +uno::Any SAL_CALL GraphicRendererVCL::queryInterface( const uno::Type & rType ) +{ + return OWeakAggObject::queryInterface( rType ); +} + + +void SAL_CALL GraphicRendererVCL::acquire() + throw() +{ + OWeakAggObject::acquire(); +} + + +void SAL_CALL GraphicRendererVCL::release() + throw() +{ + OWeakAggObject::release(); +} + + +OUString SAL_CALL GraphicRendererVCL::getImplementationName() +{ + return "com.sun.star.comp.graphic.GraphicRendererVCL"; +} + +sal_Bool SAL_CALL GraphicRendererVCL::supportsService( const OUString& ServiceName ) +{ + return cppu::supportsService(this, ServiceName); +} + + +uno::Sequence< OUString > SAL_CALL GraphicRendererVCL::getSupportedServiceNames() +{ + return { "com.sun.star.graphic.GraphicRendererVCL" }; +} + + +uno::Sequence< uno::Type > SAL_CALL GraphicRendererVCL::getTypes() +{ + static const uno::Sequence< uno::Type > aTypes { + cppu::UnoType<uno::XAggregation>::get(), + cppu::UnoType<lang::XServiceInfo>::get(), + cppu::UnoType<lang::XTypeProvider>::get(), + cppu::UnoType<beans::XPropertySet>::get(), + cppu::UnoType<beans::XPropertyState>::get(), + cppu::UnoType<beans::XMultiPropertySet>::get(), + cppu::UnoType<graphic::XGraphicRenderer>::get() }; + return aTypes; +} + +uno::Sequence< sal_Int8 > SAL_CALL GraphicRendererVCL::getImplementationId() +{ + return css::uno::Sequence<sal_Int8>(); +} + + +rtl::Reference<::comphelper::PropertySetInfo> GraphicRendererVCL::createPropertySetInfo() +{ + static ::comphelper::PropertyMapEntry const aEntries[] = + { + { OUString("Device"), UNOGRAPHIC_DEVICE, cppu::UnoType<uno::Any>::get(), 0, 0 }, + { OUString("DestinationRect"), UNOGRAPHIC_DESTINATIONRECT, cppu::UnoType<awt::Rectangle>::get(), 0, 0 }, + { OUString("RenderData"), UNOGRAPHIC_RENDERDATA, cppu::UnoType<uno::Any>::get(), 0, 0 }, + { OUString(), 0, css::uno::Type(), 0, 0 } + }; + + return rtl::Reference<::comphelper::PropertySetInfo>( new ::comphelper::PropertySetInfo(aEntries) ); +} + + +void GraphicRendererVCL::_setPropertyValues( const comphelper::PropertyMapEntry** ppEntries, const uno::Any* pValues ) +{ + SolarMutexGuard aGuard; + + while( *ppEntries ) + { + switch( (*ppEntries)->mnHandle ) + { + case UNOGRAPHIC_DEVICE: + { + uno::Reference< awt::XDevice > xDevice; + + if( ( *pValues >>= xDevice ) && xDevice.is() ) + { + mxDevice = xDevice; + mpOutDev = VCLUnoHelper::GetOutputDevice( xDevice ); + } + else + { + mxDevice.clear(); + mpOutDev = nullptr; + } + } + break; + + case UNOGRAPHIC_DESTINATIONRECT: + { + awt::Rectangle aAWTRect; + + if( *pValues >>= aAWTRect ) + { + maDestRect = tools::Rectangle( Point( aAWTRect.X, aAWTRect.Y ), + Size( aAWTRect.Width, aAWTRect.Height ) ); + } + } + break; + + case UNOGRAPHIC_RENDERDATA: + { + maRenderData = *pValues; + } + break; + } + + ++ppEntries; + ++pValues; + } +} + + +void GraphicRendererVCL::_getPropertyValues( const comphelper::PropertyMapEntry** ppEntries, uno::Any* pValues ) +{ + SolarMutexGuard aGuard; + + while( *ppEntries ) + { + switch( (*ppEntries)->mnHandle ) + { + case UNOGRAPHIC_DEVICE: + { + if( mxDevice.is() ) + *pValues <<= mxDevice; + } + break; + + case UNOGRAPHIC_DESTINATIONRECT: + { + const awt::Rectangle aAWTRect( maDestRect.Left(), maDestRect.Top(), + maDestRect.GetWidth(), maDestRect.GetHeight() ); + + *pValues <<= aAWTRect; + } + break; + + case UNOGRAPHIC_RENDERDATA: + { + *pValues = maRenderData; + } + break; + } + + ++ppEntries; + ++pValues; + } +} + + +void SAL_CALL GraphicRendererVCL::render( const uno::Reference< graphic::XGraphic >& rxGraphic ) +{ + if( mpOutDev && mxDevice.is() && rxGraphic.is() ) + { + Graphic aGraphic(rxGraphic); + if (!aGraphic.IsNone()) + { + GraphicObject aGraphicObject(aGraphic); + aGraphicObject.Draw( mpOutDev, maDestRect.TopLeft(), maDestRect.GetSize() ); + } + } +} + +} + +extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface * +com_sun_star_comp_graphic_GraphicRendererVCL_get_implementation( + css::uno::XComponentContext *, + css::uno::Sequence<css::uno::Any> const &) +{ + return cppu::acquire(new GraphicRendererVCL); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/hatchwindow/documentcloser.cxx b/svtools/source/hatchwindow/documentcloser.cxx new file mode 100644 index 000000000..6e014dd7e --- /dev/null +++ b/svtools/source/hatchwindow/documentcloser.cxx @@ -0,0 +1,234 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <com/sun/star/uno/XComponentContext.hpp> +#include <com/sun/star/util/XCloseable.hpp> +#include <com/sun/star/lang/DisposedException.hpp> +#include <com/sun/star/lang/IllegalArgumentException.hpp> +#include <com/sun/star/lang/XComponent.hpp> +#include <com/sun/star/lang/XServiceInfo.hpp> +#include <com/sun/star/frame/XFrame.hpp> +#include <com/sun/star/awt/XVclWindowPeer.hpp> +#include <cppuhelper/implbase.hxx> +#include <comphelper/interfacecontainer2.hxx> +#include <cppuhelper/supportsservice.hxx> +#include <osl/mutex.hxx> +#include <vcl/svapp.hxx> +#include <vcl/dialoghelper.hxx> +#include <vcl/window.hxx> +#include <tools/link.hxx> +#include <toolkit/helper/vclunohelper.hxx> + +using namespace ::com::sun::star; + +namespace { + +// the service is implemented as a wrapper to be able to die by refcount +// the disposing mechanics is required for java related scenarios +class ODocumentCloser : public ::cppu::WeakImplHelper< css::lang::XComponent, + css::lang::XServiceInfo > +{ + ::osl::Mutex m_aMutex; + css::uno::Reference< css::frame::XFrame > m_xFrame; + std::unique_ptr<::comphelper::OInterfaceContainerHelper2> m_pListenersContainer; // list of listeners + + bool m_bDisposed; + +public: + explicit ODocumentCloser(const css::uno::Sequence< css::uno::Any >& aArguments); + +// 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; + +// 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; +}; + +class MainThreadFrameCloserRequest +{ + uno::Reference< frame::XFrame > m_xFrame; + + public: + explicit MainThreadFrameCloserRequest( const uno::Reference< frame::XFrame >& xFrame ) + : m_xFrame( xFrame ) + {} + + DECL_STATIC_LINK( MainThreadFrameCloserRequest, worker, void*, void ); + + static void Start( MainThreadFrameCloserRequest* pRequest ); +}; + + +void MainThreadFrameCloserRequest::Start( MainThreadFrameCloserRequest* pMTRequest ) +{ + if ( pMTRequest ) + { + if ( Application::IsMainThread() ) + { + // this is the main thread + worker( nullptr, pMTRequest ); + } + else + Application::PostUserEvent( LINK( nullptr, MainThreadFrameCloserRequest, worker ), pMTRequest ); + } +} + + +IMPL_STATIC_LINK( MainThreadFrameCloserRequest, worker, void*, p, void ) +{ + MainThreadFrameCloserRequest* pMTRequest = static_cast<MainThreadFrameCloserRequest*>(p); + if ( !pMTRequest ) + return; + + if ( pMTRequest->m_xFrame.is() ) + { + // this is the main thread, the solar mutex must be locked + SolarMutexGuard aGuard; + + try + { + uno::Reference< awt::XWindow > xWindow = pMTRequest->m_xFrame->getContainerWindow(); + uno::Reference< awt::XVclWindowPeer > xWinPeer( xWindow, uno::UNO_QUERY_THROW ); + + xWindow->setVisible( false ); + + // reparent the window + xWinPeer->setProperty( "PluginParent", uno::makeAny( sal_Int64(0) ) ); + + VclPtr<vcl::Window> pWindow = VCLUnoHelper::GetWindow( xWindow ); + if (pWindow) + vcl::EndAllDialogs(pWindow); + } + catch( uno::Exception& ) + { + // ignore all the errors + } + + try + { + uno::Reference< util::XCloseable > xCloseable( pMTRequest->m_xFrame, uno::UNO_QUERY_THROW ); + xCloseable->close( true ); + } + catch( uno::Exception& ) + { + // ignore all the errors + } + } + + delete pMTRequest; +} + +ODocumentCloser::ODocumentCloser(const css::uno::Sequence< css::uno::Any >& aArguments) +: m_bDisposed( false ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + if ( !m_refCount ) + throw uno::RuntimeException(); // the object must be refcounted already! + + sal_Int32 nLen = aArguments.getLength(); + if ( nLen != 1 ) + throw lang::IllegalArgumentException( + "Wrong count of parameters!", + uno::Reference< uno::XInterface >(), + 0 ); + + if ( !( aArguments[0] >>= m_xFrame ) || !m_xFrame.is() ) + throw lang::IllegalArgumentException( + "Nonempty reference is expected as the first argument!", + uno::Reference< uno::XInterface >(), + 0 ); +} + + +// XComponent + +void SAL_CALL ODocumentCloser::dispose() +{ + ::osl::MutexGuard aGuard( m_aMutex ); + + if ( m_bDisposed ) + throw lang::DisposedException(); + + lang::EventObject aSource( static_cast< ::cppu::OWeakObject* >(this) ); + if ( m_pListenersContainer ) + m_pListenersContainer->disposeAndClear( aSource ); + + // TODO: trigger a main thread execution to close the frame + if ( m_xFrame.is() ) + { + // the created object will be deleted after thread execution + MainThreadFrameCloserRequest* pCloser = new MainThreadFrameCloserRequest( m_xFrame ); + MainThreadFrameCloserRequest::Start( pCloser ); + } + + m_bDisposed = true; +} + + +void SAL_CALL ODocumentCloser::addEventListener( const uno::Reference< lang::XEventListener >& xListener ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + if ( m_bDisposed ) + throw lang::DisposedException(); // TODO + + if ( !m_pListenersContainer ) + m_pListenersContainer.reset( new ::comphelper::OInterfaceContainerHelper2( m_aMutex ) ); + + m_pListenersContainer->addInterface( xListener ); +} + + +void SAL_CALL ODocumentCloser::removeEventListener( const uno::Reference< lang::XEventListener >& xListener ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + if ( m_pListenersContainer ) + m_pListenersContainer->removeInterface( xListener ); +} + +// XServiceInfo +OUString SAL_CALL ODocumentCloser::getImplementationName( ) +{ + return "com.sun.star.comp.embed.DocumentCloser"; +} + +sal_Bool SAL_CALL ODocumentCloser::supportsService( const OUString& ServiceName ) +{ + return cppu::supportsService(this, ServiceName); +} + +uno::Sequence< OUString > SAL_CALL ODocumentCloser::getSupportedServiceNames() +{ + return { "com.sun.star.embed.DocumentCloser" }; +} + +} + +extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface * +com_sun_star_comp_embed_DocumentCloser_get_implementation( + SAL_UNUSED_PARAMETER css::uno::XComponentContext *, + css::uno::Sequence<css::uno::Any> const &arguments) +{ + return cppu::acquire(new ODocumentCloser(arguments)); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/hatchwindow/hatchwindow.cxx b/svtools/source/hatchwindow/hatchwindow.cxx new file mode 100644 index 000000000..1402fde5a --- /dev/null +++ b/svtools/source/hatchwindow/hatchwindow.cxx @@ -0,0 +1,201 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <com/sun/star/embed/XHatchWindowController.hpp> +#include <com/sun/star/lang/IllegalArgumentException.hpp> + +#include <hatchwindow.hxx> +#include "ipwin.hxx" + +#include <toolkit/helper/convert.hxx> +#include <cppuhelper/queryinterface.hxx> +#include <cppuhelper/typeprovider.hxx> +#include <osl/diagnose.h> +#include <vcl/svapp.hxx> + +using namespace ::com::sun::star; + +VCLXHatchWindow::VCLXHatchWindow() +: VCLXWindow() +, pHatchWindow(nullptr) +{ +} + +VCLXHatchWindow::~VCLXHatchWindow() +{ +} + +void VCLXHatchWindow::initializeWindow( const uno::Reference< awt::XWindowPeer >& xParent, + const awt::Rectangle& aBounds, + const awt::Size& aSize ) +{ + SolarMutexGuard aGuard; + + VclPtr<vcl::Window> pParent; + VCLXWindow* pParentComponent = comphelper::getUnoTunnelImplementation<VCLXWindow>( xParent ); + + if ( pParentComponent ) + pParent = pParentComponent->GetWindow(); + + OSL_ENSURE( pParent, "No parent window is provided!" ); + if ( !pParent ) + throw lang::IllegalArgumentException(); // TODO + + pHatchWindow = VclPtr<SvResizeWindow>::Create( pParent, this ); + pHatchWindow->setPosSizePixel( aBounds.X, aBounds.Y, aBounds.Width, aBounds.Height ); + aHatchBorderSize = aSize; + pHatchWindow->SetHatchBorderPixel( Size( aSize.Width, aSize.Height ) ); + + SetWindow( pHatchWindow ); + pHatchWindow->SetComponentInterface( this ); + + //pHatchWindow->Show(); +} + +void VCLXHatchWindow::QueryObjAreaPixel( tools::Rectangle & aRect ) +{ + if ( !m_xController.is() ) + return; + + awt::Rectangle aUnoRequestRect = AWTRectangle( aRect ); + + try { + awt::Rectangle aUnoResultRect = m_xController->calcAdjustedRectangle( aUnoRequestRect ); + aRect = VCLRectangle( aUnoResultRect ); + } + catch( uno::Exception& ) + { + OSL_FAIL( "Can't adjust rectangle size!" ); + } +} + +void VCLXHatchWindow::RequestObjAreaPixel( const tools::Rectangle & aRect ) +{ + if ( m_xController.is() ) + { + awt::Rectangle aUnoRequestRect = AWTRectangle( aRect ); + + try { + m_xController->requestPositioning( aUnoRequestRect ); + } + catch( uno::Exception& ) + { + OSL_FAIL( "Can't request resizing!" ); + } + } +} + +void VCLXHatchWindow::InplaceDeactivate() +{ + if ( m_xController.is() ) + { + // TODO: communicate with controller + } +} + + +uno::Any SAL_CALL VCLXHatchWindow::queryInterface( const uno::Type & rType ) +{ + // Attention: + // Don't use mutex or guard in this method!!! Is a method of XInterface. + + uno::Any aReturn( ::cppu::queryInterface( rType, + static_cast< embed::XHatchWindow* >( this ) ) ); + + if ( aReturn.hasValue() ) + { + return aReturn ; + } + + return VCLXWindow::queryInterface( rType ) ; +} + +void SAL_CALL VCLXHatchWindow::acquire() + throw() +{ + VCLXWindow::acquire(); +} + +void SAL_CALL VCLXHatchWindow::release() + throw() +{ + VCLXWindow::release(); +} + +uno::Sequence< uno::Type > SAL_CALL VCLXHatchWindow::getTypes() +{ + static cppu::OTypeCollection aTypeCollection(cppu::UnoType<embed::XHatchWindow>::get(), + VCLXWindow::getTypes()); + + return aTypeCollection.getTypes(); +} + +uno::Sequence< sal_Int8 > SAL_CALL VCLXHatchWindow::getImplementationId() +{ + return css::uno::Sequence<sal_Int8>(); +} + +css::awt::Size SAL_CALL VCLXHatchWindow::getHatchBorderSize() +{ + return aHatchBorderSize; +} + +void SAL_CALL VCLXHatchWindow::setHatchBorderSize( const css::awt::Size& _hatchbordersize ) +{ + if ( pHatchWindow ) + { + aHatchBorderSize = _hatchbordersize; + pHatchWindow->SetHatchBorderPixel( Size( aHatchBorderSize.Width, aHatchBorderSize.Height ) ); + } +} + +void SAL_CALL VCLXHatchWindow::setController( const uno::Reference< embed::XHatchWindowController >& xController ) +{ + m_xController = xController; +} + +void SAL_CALL VCLXHatchWindow::dispose() +{ + pHatchWindow.clear(); + VCLXWindow::dispose(); +} + +void SAL_CALL VCLXHatchWindow::addEventListener( const uno::Reference< lang::XEventListener >& xListener ) +{ + VCLXWindow::addEventListener( xListener ); +} + +void SAL_CALL VCLXHatchWindow::removeEventListener( const uno::Reference< lang::XEventListener >& xListener ) +{ + VCLXWindow::removeEventListener( xListener ); +} + +void VCLXHatchWindow::Activated() +{ + if ( m_xController.is() ) + m_xController->activated(); +} + +void VCLXHatchWindow::Deactivated() +{ + if ( m_xController.is() ) + m_xController->deactivated(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/hatchwindow/hatchwindowfactory.cxx b/svtools/source/hatchwindow/hatchwindowfactory.cxx new file mode 100644 index 000000000..520cc1a25 --- /dev/null +++ b/svtools/source/hatchwindow/hatchwindowfactory.cxx @@ -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 . + */ + +#include <com/sun/star/embed/XHatchWindowFactory.hpp> +#include <com/sun/star/lang/IllegalArgumentException.hpp> +#include <com/sun/star/lang/XServiceInfo.hpp> +#include <com/sun/star/uno/XComponentContext.hpp> +#include <cppuhelper/implbase.hxx> +#include <cppuhelper/supportsservice.hxx> +#include <vcl/svapp.hxx> + +#include <hatchwindow.hxx> + +using namespace ::com::sun::star; + +namespace { + +class OHatchWindowFactory : public ::cppu::WeakImplHelper< + embed::XHatchWindowFactory, + lang::XServiceInfo > +{ +public: + OHatchWindowFactory() {} + + // XHatchWindowFactory + virtual uno::Reference< embed::XHatchWindow > SAL_CALL createHatchWindowInstance( const uno::Reference< awt::XWindowPeer >& xParent, const awt::Rectangle& aBounds, const awt::Size& aSize ) override; + + // XServiceInfo + virtual OUString SAL_CALL getImplementationName() override; + virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) override; + virtual uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() override; +}; + +uno::Reference< embed::XHatchWindow > SAL_CALL OHatchWindowFactory::createHatchWindowInstance( + const uno::Reference< awt::XWindowPeer >& xParent, + const awt::Rectangle& aBounds, + const awt::Size& aHandlerSize ) +{ + if ( !xParent.is() ) + throw lang::IllegalArgumentException(); // TODO + + SolarMutexGuard aGuard; + VCLXHatchWindow* pResult = new VCLXHatchWindow(); + pResult->initializeWindow( xParent, aBounds, aHandlerSize ); + return uno::Reference< embed::XHatchWindow >( static_cast< embed::XHatchWindow* >( pResult ) ); +} + +OUString SAL_CALL OHatchWindowFactory::getImplementationName() +{ + return "com.sun.star.comp.embed.HatchWindowFactory"; +} + +sal_Bool SAL_CALL OHatchWindowFactory::supportsService( const OUString& ServiceName ) +{ + return cppu::supportsService(this, ServiceName); +} + +uno::Sequence< OUString > SAL_CALL OHatchWindowFactory::getSupportedServiceNames() +{ + return { "com.sun.star.embed.HatchWindowFactory", "com.sun.star.comp.embed.HatchWindowFactory" }; +} + +} + +extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface * +com_sun_star_comp_embed_HatchWindowFactory_get_implementation( + css::uno::XComponentContext *, + css::uno::Sequence<css::uno::Any> const &) +{ + return cppu::acquire(new OHatchWindowFactory); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/hatchwindow/ipwin.cxx b/svtools/source/hatchwindow/ipwin.cxx new file mode 100644 index 000000000..751f3efa5 --- /dev/null +++ b/svtools/source/hatchwindow/ipwin.cxx @@ -0,0 +1,623 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <com/sun/star/accessibility/AccessibleRole.hpp> + +#include <osl/diagnose.h> +#include <vcl/event.hxx> +#include <vcl/settings.hxx> +#include <vcl/ptrstyle.hxx> + +#include "ipwin.hxx" +#include <hatchwindow.hxx> + +/************************************************************************/ +/************************************************************************* +|* SvResizeHelper::SvResizeHelper() +|* +|* Description +*************************************************************************/ +SvResizeHelper::SvResizeHelper() + : aBorder( 5, 5 ) + , nGrab( -1 ) +{ +} + +/************************************************************************* +|* SvResizeHelper::FillHandleRects() +|* +|* Description: the eight handles to magnify +*************************************************************************/ +std::array<tools::Rectangle,8> SvResizeHelper::FillHandleRectsPixel() const +{ + std::array<tools::Rectangle,8> aRects; + + // only because of EMPTY_RECT + Point aBottomRight = aOuter.BottomRight(); + + // upper left + aRects[ 0 ] = tools::Rectangle( aOuter.TopLeft(), aBorder ); + // upper middle + aRects[ 1 ] = tools::Rectangle( Point( aOuter.Center().X() - aBorder.Width() / 2, + aOuter.Top() ), + aBorder ); + // upper right + aRects[ 2 ] = tools::Rectangle( Point( aBottomRight.X() - aBorder.Width() +1, + aOuter.Top() ), + aBorder ); + // middle right + aRects[ 3 ] = tools::Rectangle( Point( aBottomRight.X() - aBorder.Width() +1, + aOuter.Center().Y() - aBorder.Height() / 2 ), + aBorder ); + // lower right + aRects[ 4 ] = tools::Rectangle( Point( aBottomRight.X() - aBorder.Width() +1, + aBottomRight.Y() - aBorder.Height() +1 ), + aBorder ); + // lower middle + aRects[ 5 ] = tools::Rectangle( Point( aOuter.Center().X() - aBorder.Width() / 2, + aBottomRight.Y() - aBorder.Height() +1), + aBorder ); + // lower left + aRects[ 6 ] = tools::Rectangle( Point( aOuter.Left(), + aBottomRight.Y() - aBorder.Height() +1), + aBorder ); + // middle left + aRects[ 7 ] = tools::Rectangle( Point( aOuter.Left(), + aOuter.Center().Y() - aBorder.Height() / 2 ), + aBorder ); + return aRects; +} + +/************************************************************************* +|* SvResizeHelper::FillMoveRectsPixel() +|* +|* Description: the four edges are calculated +*************************************************************************/ +std::array<tools::Rectangle,4> SvResizeHelper::FillMoveRectsPixel() const +{ + std::array<tools::Rectangle,4> aRects; + + // upper + aRects[ 0 ] = aOuter; + aRects[ 0 ].SetBottom( aRects[ 0 ].Top() + aBorder.Height() -1 ); + // right + aRects[ 1 ] = aOuter; + if (!aOuter.IsWidthEmpty()) + aRects[ 1 ].SetLeft( aRects[ 1 ].Right() - aBorder.Width() -1 ); + // lower + aRects[ 2 ] = aOuter; + if (!aOuter.IsHeightEmpty()) + aRects[ 2 ].SetTop( aRects[ 2 ].Bottom() - aBorder.Height() -1 ); + // left + aRects[ 3 ] = aOuter; + aRects[ 3 ].SetRight( aRects[ 3 ].Left() + aBorder.Width() -1 ); + + return aRects; +} + +/************************************************************************* +|* SvResizeHelper::Draw() +|* +|* Description +*************************************************************************/ +void SvResizeHelper::Draw(vcl::RenderContext& rRenderContext) +{ + rRenderContext.Push(); + rRenderContext.SetMapMode( MapMode() ); + + rRenderContext.SetFillColor( COL_LIGHTGRAY ); + rRenderContext.SetLineColor(); + + std::array<tools::Rectangle,4> aMoveRects = FillMoveRectsPixel(); + sal_uInt16 i; + for (i = 0; i < 4; i++) + rRenderContext.DrawRect(aMoveRects[i]); + // draw handles + rRenderContext.SetFillColor(Color()); // black + std::array<tools::Rectangle,8> aRects = FillHandleRectsPixel(); + for (i = 0; i < 8; i++) + rRenderContext.DrawRect( aRects[ i ] ); + rRenderContext.Pop(); +} + +/************************************************************************* +|* SvResizeHelper::InvalidateBorder() +|* +|* Description +*************************************************************************/ +void SvResizeHelper::InvalidateBorder( vcl::Window * pWin ) +{ + std::array<tools::Rectangle,4> aMoveRects = FillMoveRectsPixel(); + for(const auto & rMoveRect : aMoveRects) + pWin->Invalidate( rMoveRect ); +} + +/************************************************************************* +|* SvResizeHelper::SelectBegin() +|* +|* Description +*************************************************************************/ +bool SvResizeHelper::SelectBegin( vcl::Window * pWin, const Point & rPos ) +{ + if( -1 == nGrab ) + { + nGrab = SelectMove( pWin, rPos ); + if( -1 != nGrab ) + { + aSelPos = rPos; // store start position + pWin->CaptureMouse(); + return true; + } + } + return false; +} + +/************************************************************************* +|* SvResizeHelper::SelectMove() +|* +|* Description +*************************************************************************/ +short SvResizeHelper::SelectMove( vcl::Window * pWin, const Point & rPos ) +{ + if( -1 == nGrab ) + { + std::array<tools::Rectangle,8> aRects = FillHandleRectsPixel(); + for( sal_uInt16 i = 0; i < 8; i++ ) + if( aRects[ i ].IsInside( rPos ) ) + return i; + // Move-Rect overlaps Handles + std::array<tools::Rectangle,4> aMoveRects = FillMoveRectsPixel(); + for(const auto & rMoveRect : aMoveRects) + if( rMoveRect.IsInside( rPos ) ) + return 8; + } + else + { + tools::Rectangle aRect( GetTrackRectPixel( rPos ) ); + aRect.SetSize( pWin->PixelToLogic( aRect.GetSize() ) ); + aRect.SetPos( pWin->PixelToLogic( aRect.TopLeft() ) ); + pWin->ShowTracking( aRect ); + } + return nGrab; +} + +Point SvResizeHelper::GetTrackPosPixel( const tools::Rectangle & rRect ) const +{ + // not important how the rectangle is returned, it is important + // which handle has been touched + Point aPos; + tools::Rectangle aRect( rRect ); + aRect.Justify(); + // only because of EMPTY_RECT + Point aBR = aOuter.BottomRight(); + Point aTR = aOuter.TopRight(); + Point aBL = aOuter.BottomLeft(); + bool bRTL = AllSettings::GetLayoutRTL(); + switch( nGrab ) + { + case 0: + // FIXME: disable it for RTL because it's wrong calculations + if( bRTL ) + break; + aPos = aRect.TopLeft() - aOuter.TopLeft(); + break; + case 1: + aPos.setY( aRect.Top() - aOuter.Top() ); + break; + case 2: + // FIXME: disable it for RTL because it's wrong calculations + if( bRTL ) + break; + aPos = aRect.TopRight() - aTR; + break; + case 3: + if( bRTL ) + aPos.setX( aRect.Left() - aTR.X() ); + else + aPos.setX( aRect.Right() - aTR.X() ); + break; + case 4: + // FIXME: disable it for RTL because it's wrong calculations + if( bRTL ) + break; + aPos = aRect.BottomRight() - aBR; + break; + case 5: + aPos.setY( aRect.Bottom() - aBR.Y() ); + break; + case 6: + // FIXME: disable it for RTL because it's wrong calculations + if( bRTL ) + break; + aPos = aRect.BottomLeft() - aBL; + break; + case 7: + if( bRTL ) + aPos.setX( aRect.Right() + aOuter.Right() - aOuter.TopRight().X() ); + else + aPos.setX( aRect.Left() - aOuter.Left() ); + break; + case 8: + aPos = aRect.TopLeft() - aOuter.TopLeft(); + break; + } + return aPos + aSelPos; +} + +/************************************************************************* +|* SvResizeHelper::GetTrackRectPixel() +|* +|* Description +*************************************************************************/ +tools::Rectangle SvResizeHelper::GetTrackRectPixel( const Point & rTrackPos ) const +{ + tools::Rectangle aTrackRect; + if( -1 != nGrab ) + { + Point aDiff = rTrackPos - aSelPos; + aTrackRect = aOuter; + Point aBR = aOuter.BottomRight(); + bool bRTL = AllSettings::GetLayoutRTL(); + switch( nGrab ) + { + case 0: + aTrackRect.AdjustTop(aDiff.Y() ); + // ugly solution for resizing OLE objects in RTL + if( bRTL ) + aTrackRect.SetRight( aBR.X() - aDiff.X() ); + else + aTrackRect.AdjustLeft(aDiff.X() ); + break; + case 1: + aTrackRect.AdjustTop(aDiff.Y() ); + break; + case 2: + aTrackRect.AdjustTop(aDiff.Y() ); + // ugly solution for resizing OLE objects in RTL + if( bRTL ) + aTrackRect.AdjustLeft( -(aDiff.X()) ); + else + aTrackRect.SetRight( aBR.X() + aDiff.X() ); + break; + case 3: + // ugly solution for resizing OLE objects in RTL + if( bRTL ) + aTrackRect.AdjustLeft( -(aDiff.X()) ); + else + aTrackRect.SetRight( aBR.X() + aDiff.X() ); + break; + case 4: + aTrackRect.SetBottom( aBR.Y() + aDiff.Y() ); + // ugly solution for resizing OLE objects in RTL + if( bRTL ) + aTrackRect.AdjustLeft( -(aDiff.X()) ); + else + aTrackRect.SetRight( aBR.X() + aDiff.X() ); + break; + case 5: + aTrackRect.SetBottom( aBR.Y() + aDiff.Y() ); + break; + case 6: + aTrackRect.SetBottom( aBR.Y() + aDiff.Y() ); + // ugly solution for resizing OLE objects in RTL + if( bRTL ) + aTrackRect.SetRight( aBR.X() - aDiff.X() ); + else + aTrackRect.AdjustLeft(aDiff.X() ); + break; + case 7: + // ugly solution for resizing OLE objects in RTL + if( bRTL ) + aTrackRect.SetRight( aBR.X() - aDiff.X() ); + else + aTrackRect.AdjustLeft(aDiff.X() ); + break; + case 8: + if( bRTL ) + aDiff.setX( -aDiff.X() ); // workaround for move in RTL mode + aTrackRect.SetPos( aTrackRect.TopLeft() + aDiff ); + break; + } + } + return aTrackRect; +} + +void SvResizeHelper::ValidateRect( tools::Rectangle & rValidate ) const +{ + switch( nGrab ) + { + case 0: + if( rValidate.Top() > rValidate.Bottom() ) + rValidate.SetTop( rValidate.Bottom() ); + if( rValidate.Left() > rValidate.Right() ) + rValidate.SetLeft( rValidate.Right() ); + break; + case 1: + if( rValidate.Top() > rValidate.Bottom() ) + rValidate.SetTop( rValidate.Bottom() ); + break; + case 2: + if( rValidate.Top() > rValidate.Bottom() ) + rValidate.SetTop( rValidate.Bottom() ); + if( rValidate.Left() > rValidate.Right() ) + rValidate.SetRight( rValidate.Left() ); + break; + case 3: + if( rValidate.Left() > rValidate.Right() ) + rValidate.SetRight( rValidate.Left() ); + break; + case 4: + if( rValidate.Top() > rValidate.Bottom() ) + rValidate.SetBottom( rValidate.Top() ); + if( rValidate.Left() > rValidate.Right() ) + rValidate.SetRight( rValidate.Left() ); + break; + case 5: + if( rValidate.Top() > rValidate.Bottom() ) + rValidate.SetBottom( rValidate.Top() ); + break; + case 6: + if( rValidate.Top() > rValidate.Bottom() ) + rValidate.SetBottom( rValidate.Top() ); + if( rValidate.Left() > rValidate.Right() ) + rValidate.SetLeft( rValidate.Right() ); + break; + case 7: + if( rValidate.Left() > rValidate.Right() ) + rValidate.SetLeft( rValidate.Right() ); + break; + } + + // Mindestgr"osse 5 x 5 + if( rValidate.Left() + 5 > rValidate.Right() ) + rValidate.SetRight( rValidate.Left() + 5 ); + if( rValidate.Top() + 5 > rValidate.Bottom() ) + rValidate.SetBottom( rValidate.Top() + 5 ); +} + +/************************************************************************* +|* SvResizeHelper::SelectRelease() +|* +|* Description +*************************************************************************/ +bool SvResizeHelper::SelectRelease( vcl::Window * pWin, const Point & rPos, + tools::Rectangle & rOutPosSize ) +{ + if( -1 != nGrab ) + { + rOutPosSize = GetTrackRectPixel( rPos ); + rOutPosSize.Justify(); + nGrab = -1; + pWin->ReleaseMouse(); + pWin->HideTracking(); + return true; + } + return false; +} + +/************************************************************************* +|* SvResizeHelper::Release() +|* +|* Description +*************************************************************************/ +void SvResizeHelper::Release( vcl::Window * pWin ) +{ + if( nGrab != -1 ) + { + pWin->ReleaseMouse(); + pWin->HideTracking(); + nGrab = -1; + } +} + +/************************************************************************* +|* SvResizeWindow::SvResizeWindow() +|* +|* Description +*************************************************************************/ +SvResizeWindow::SvResizeWindow +( + vcl::Window * pParent, + VCLXHatchWindow* pWrapper +) + : Window( pParent, WB_CLIPCHILDREN ) + , m_aOldPointer(PointerStyle::Arrow) + , m_nMoveGrab( -1 ) + , m_bActive( false ) + , m_pWrapper( pWrapper ) +{ + OSL_ENSURE( pParent != nullptr && pWrapper != nullptr, "Wrong initialization of hatch window!" ); + SetBackground(); + SetAccessibleRole( css::accessibility::AccessibleRole::EMBEDDED_OBJECT ); + m_aResizer.SetOuterRectPixel( tools::Rectangle( Point(), GetOutputSizePixel() ) ); +} + +/************************************************************************* +|* SvResizeWindow::SetHatchBorderPixel() +|* +|* Description +*************************************************************************/ +void SvResizeWindow::SetHatchBorderPixel( const Size & rSize ) +{ + m_aResizer.SetBorderPixel( rSize ); +} + +/************************************************************************* +|* SvResizeWindow::SelectMouse() +|* +|* Description +*************************************************************************/ +void SvResizeWindow::SelectMouse( const Point & rPos ) +{ + short nGrab = m_aResizer.SelectMove( this, rPos ); + if( nGrab >= 4 ) + nGrab -= 4; + if( m_nMoveGrab == nGrab ) + return; + + // Pointer did change + if( -1 == nGrab ) + SetPointer( m_aOldPointer ); + else + { + PointerStyle aStyle = PointerStyle::Move; + if( nGrab == 3 ) + aStyle = PointerStyle::ESize; + else if( nGrab == 2 ) + aStyle = PointerStyle::NESize; + else if( nGrab == 1 ) + aStyle = PointerStyle::SSize; + else if( nGrab == 0 ) + aStyle = PointerStyle::SESize; + if( m_nMoveGrab == -1 ) // the first time + { + m_aOldPointer = GetPointer(); + SetPointer( aStyle ); + } + else + SetPointer( aStyle ); + } + m_nMoveGrab = nGrab; +} + +/************************************************************************* +|* SvResizeWindow::MouseButtonDown() +|* +|* Description +*************************************************************************/ +void SvResizeWindow::MouseButtonDown( const MouseEvent & rEvt ) +{ + if( m_aResizer.SelectBegin( this, rEvt.GetPosPixel() ) ) + SelectMouse( rEvt.GetPosPixel() ); +} + +/************************************************************************* +|* SvResizeWindow::MouseMove() +|* +|* Description +*************************************************************************/ +void SvResizeWindow::MouseMove( const MouseEvent & rEvt ) +{ + if( m_aResizer.GetGrab() == -1 ) + SelectMouse( rEvt.GetPosPixel() ); + else + { + tools::Rectangle aRect( m_aResizer.GetTrackRectPixel( rEvt.GetPosPixel() ) ); + Point aDiff = GetPosPixel(); + aRect.SetPos( aRect.TopLeft() + aDiff ); + m_aResizer.ValidateRect( aRect ); + + m_pWrapper->QueryObjAreaPixel( aRect ); + aRect.SetPos( aRect.TopLeft() - aDiff ); + Point aPos = m_aResizer.GetTrackPosPixel( aRect ); + + SelectMouse( aPos ); + } +} + +/************************************************************************* +|* SvResizeWindow::MouseButtonUp() +|* +|* Description +*************************************************************************/ +void SvResizeWindow::MouseButtonUp( const MouseEvent & rEvt ) +{ + if( m_aResizer.GetGrab() == -1 ) + return; + + tools::Rectangle aRect( m_aResizer.GetTrackRectPixel( rEvt.GetPosPixel() ) ); + Point aDiff = GetPosPixel(); + aRect.SetPos( aRect.TopLeft() + aDiff ); + // aRect -= GetAllBorderPixel(); + m_aResizer.ValidateRect( aRect ); + + m_pWrapper->QueryObjAreaPixel( aRect ); + + tools::Rectangle aOutRect; + if( m_aResizer.SelectRelease( this, rEvt.GetPosPixel(), aOutRect ) ) + { + m_nMoveGrab = -1; + SetPointer( m_aOldPointer ); + m_pWrapper->RequestObjAreaPixel( aRect ); + } +} + +/************************************************************************* +|* SvResizeWindow::KeyEvent() +|* +|* Description +*************************************************************************/ +void SvResizeWindow::KeyInput( const KeyEvent & rEvt ) +{ + if( rEvt.GetKeyCode().GetCode() == KEY_ESCAPE ) + { + m_aResizer.Release( this ); + m_pWrapper->InplaceDeactivate(); + } +} + +/************************************************************************* +|* SvResizeWindow::Resize() +|* +|* Description +*************************************************************************/ +void SvResizeWindow::Resize() +{ + m_aResizer.InvalidateBorder( this ); // old area + m_aResizer.SetOuterRectPixel( tools::Rectangle( Point(), GetOutputSizePixel() ) ); + m_aResizer.InvalidateBorder( this ); // new area +} + +/************************************************************************* +|* SvResizeWindow::Paint() +|* +|* Description +*************************************************************************/ +void SvResizeWindow::Paint(vcl::RenderContext& rRenderContext, const tools::Rectangle & /*rRect*/ ) +{ + m_aResizer.Draw(rRenderContext); +} + +bool SvResizeWindow::PreNotify( NotifyEvent& rEvt ) +{ + if ( rEvt.GetType() == MouseNotifyEvent::GETFOCUS && !m_bActive ) + { + m_bActive = true; + m_pWrapper->Activated(); + } + + return Window::PreNotify(rEvt); +} + +bool SvResizeWindow::EventNotify( NotifyEvent& rEvt ) +{ + if ( rEvt.GetType() == MouseNotifyEvent::LOSEFOCUS && m_bActive ) + { + bool bHasFocus = HasChildPathFocus(true); + if ( !bHasFocus ) + { + m_bActive = false; + m_pWrapper->Deactivated(); + } + } + + return Window::EventNotify(rEvt); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/hatchwindow/ipwin.hxx b/svtools/source/hatchwindow/ipwin.hxx new file mode 100644 index 000000000..72567ce26 --- /dev/null +++ b/svtools/source/hatchwindow/ipwin.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 <tools/gen.hxx> +#include <vcl/window.hxx> +#include <array> + +/********************** SvResizeHelper *********************************** +*************************************************************************/ +class SvResizeHelper +{ + Size aBorder; + tools::Rectangle aOuter; + short nGrab; // -1 no Grab, 0 - 7, 8 = Move, see FillHandle... + Point aSelPos; +public: + SvResizeHelper(); + + short GetGrab() const + { + return nGrab; + } + void SetBorderPixel(const Size & rBorderP) + { + aBorder = rBorderP; + } + void SetOuterRectPixel(const tools::Rectangle& rRect) + { + aOuter = rRect; + } + // Clockwise, start at upper left + + std::array<tools::Rectangle,8> FillHandleRectsPixel() const; + std::array<tools::Rectangle,4> FillMoveRectsPixel() const; + void Draw(vcl::RenderContext& rRenderContext); + void InvalidateBorder( vcl::Window * ); + bool SelectBegin( vcl::Window *, const Point & rPos ); + short SelectMove( vcl::Window * pWin, const Point & rPos ); + Point GetTrackPosPixel( const tools::Rectangle & rRect ) const; + tools::Rectangle GetTrackRectPixel( const Point & rTrackPos ) const; + void ValidateRect( tools::Rectangle & rValidate ) const; + bool SelectRelease( vcl::Window *, const Point & rPos, tools::Rectangle & rOutPosSize ); + void Release( vcl::Window * pWin ); +}; + +/********************** SvResizeWindow *********************************** +*************************************************************************/ +class VCLXHatchWindow; +class SvResizeWindow : public vcl::Window +{ + PointerStyle m_aOldPointer; + short m_nMoveGrab; // last pointer type + SvResizeHelper m_aResizer; + bool m_bActive; + + VCLXHatchWindow* m_pWrapper; +public: + SvResizeWindow( vcl::Window* pParent, VCLXHatchWindow* pWrapper ); + + void SetHatchBorderPixel( const Size & rSize ); + + void SelectMouse( const Point & rPos ); + virtual void MouseButtonUp( const MouseEvent & rEvt ) override; + virtual void MouseMove( const MouseEvent & rEvt ) override; + virtual void MouseButtonDown( const MouseEvent & rEvt ) override; + virtual void KeyInput( const KeyEvent & rEvt ) override; + virtual void Resize() override; + virtual void Paint( vcl::RenderContext& /*rRenderContext*/, const tools::Rectangle & ) override; + virtual bool EventNotify( NotifyEvent& rNEvt ) override; + virtual bool PreNotify( NotifyEvent& rNEvt ) override; +}; + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/inc/hatchwindow.hxx b/svtools/source/inc/hatchwindow.hxx new file mode 100644 index 000000000..71e3d84f2 --- /dev/null +++ b/svtools/source/inc/hatchwindow.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 <com/sun/star/embed/XHatchWindow.hpp> + +#include <toolkit/awt/vclxwindow.hxx> + +class SvResizeWindow; +class VCLXHatchWindow : public css::embed::XHatchWindow, + public VCLXWindow +{ + css::uno::Reference< css::embed::XHatchWindowController > m_xController; + css::awt::Size aHatchBorderSize; + VclPtr<SvResizeWindow> pHatchWindow; + +public: + VCLXHatchWindow(); + virtual ~VCLXHatchWindow() override; + + void initializeWindow( const css::uno::Reference< css::awt::XWindowPeer >& xParent, + const css::awt::Rectangle& aBounds, + const css::awt::Size& aSize ); + + void QueryObjAreaPixel( tools::Rectangle & ); + void RequestObjAreaPixel( const tools::Rectangle & ); + void InplaceDeactivate(); + void Activated(); + void Deactivated(); + + // XInterface + css::uno::Any SAL_CALL queryInterface( const css::uno::Type& rType ) override; + void SAL_CALL acquire() throw() override; + void SAL_CALL release() throw() override; + + // XTypeProvider + css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() override; + css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() override; + + // XHatchWindow + virtual void SAL_CALL setController( const css::uno::Reference< css::embed::XHatchWindowController >& xController ) override; + virtual css::awt::Size SAL_CALL getHatchBorderSize() override; + virtual void SAL_CALL setHatchBorderSize( const css::awt::Size& _hatchbordersize ) override; + + // 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; +}; + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/inc/unoiface.hxx b/svtools/source/inc/unoiface.hxx new file mode 100644 index 000000000..7813b9ffe --- /dev/null +++ b/svtools/source/inc/unoiface.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 <toolkit/awt/vclxwindow.hxx> +#include <toolkit/awt/vclxwindows.hxx> +#include <toolkit/helper/listenermultiplexer.hxx> + +#include <com/sun/star/awt/XTextArea.hpp> +#include <com/sun/star/awt/XTextComponent.hpp> +#include <com/sun/star/awt/XTextLayoutConstrains.hpp> +#include <tools/lineend.hxx> + +namespace com::sun::star::util { + class XNumberFormatsSupplier; +} + +class SvNumberFormatsSupplierObj; + + + +class VCLXMultiLineEdit : public css::awt::XTextComponent, + public css::awt::XTextArea, + public css::awt::XTextLayoutConstrains, + public VCLXWindow +{ +private: + TextListenerMultiplexer maTextListeners; + LineEnd meLineEndType; + +protected: + void ProcessWindowEvent( const VclWindowEvent& rVclWindowEvent ) override; + +public: + VCLXMultiLineEdit(); + virtual ~VCLXMultiLineEdit() override; + + // css::uno::XInterface + css::uno::Any SAL_CALL queryInterface( const css::uno::Type & rType ) override; + void SAL_CALL acquire() throw() override { VCLXWindow::acquire(); } + void SAL_CALL release() throw() override { VCLXWindow::release(); } + + // css::lang::XTypeProvider + css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() override; + css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() override; + + // css::awt::XTextComponent + void SAL_CALL addTextListener( const css::uno::Reference< css::awt::XTextListener >& l ) override; + void SAL_CALL removeTextListener( const css::uno::Reference< css::awt::XTextListener >& l ) override; + void SAL_CALL setText( const OUString& aText ) override; + void SAL_CALL insertText( const css::awt::Selection& Sel, const OUString& Text ) override; + OUString SAL_CALL getText( ) override; + OUString SAL_CALL getSelectedText( ) override; + void SAL_CALL setSelection( const css::awt::Selection& aSelection ) override; + css::awt::Selection SAL_CALL getSelection( ) override; + sal_Bool SAL_CALL isEditable( ) override; + void SAL_CALL setEditable( sal_Bool bEditable ) override; + void SAL_CALL setMaxTextLen( sal_Int16 nLen ) override; + sal_Int16 SAL_CALL getMaxTextLen( ) override; + + //XTextArea + OUString SAL_CALL getTextLines( ) override; + + // css::awt::XLayoutConstrains + css::awt::Size SAL_CALL getMinimumSize( ) override; + css::awt::Size SAL_CALL getPreferredSize( ) override; + css::awt::Size SAL_CALL calcAdjustedSize( const css::awt::Size& aNewSize ) override; + + // css::awt::XTextLayoutConstrains + css::awt::Size SAL_CALL getMinimumSize( sal_Int16 nCols, sal_Int16 nLines ) override; + void SAL_CALL getColumnsAndLines( sal_Int16& nCols, sal_Int16& nLines ) override; + + // css::awt::XVclWindowPeer + void SAL_CALL setProperty( const OUString& PropertyName, const css::uno::Any& Value ) override; + css::uno::Any SAL_CALL getProperty( const OUString& PropertyName ) override; + + // css::awt::XWindow + void SAL_CALL setFocus( ) override; + + static void ImplGetPropertyIds( std::vector< sal_uInt16 > &aIds ); + virtual void GetPropertyIds( std::vector< sal_uInt16 > &aIds ) override { return ImplGetPropertyIds( aIds ); } +}; + +class SVTXDateField : public VCLXDateField +{ +public: + SVTXDateField(); + virtual ~SVTXDateField() override; + + // css::awt::VclWindowPeer + void SAL_CALL setProperty( const OUString& PropertyName, const css::uno::Any& Value ) override; + + static void ImplGetPropertyIds( std::vector< sal_uInt16 > &aIds ); + virtual void GetPropertyIds( std::vector< sal_uInt16 > &aIds ) override { return ImplGetPropertyIds( aIds ); } +}; + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/java/javacontext.cxx b/svtools/source/java/javacontext.cxx new file mode 100644 index 000000000..f961453f6 --- /dev/null +++ b/svtools/source/java/javacontext.cxx @@ -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 . + */ + +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Type.hxx> +#include <svtools/javacontext.hxx> +#include <svtools/javainteractionhandler.hxx> + +using namespace com::sun::star::uno; +using namespace com::sun::star::task; +namespace svt +{ + +JavaContext::JavaContext( const Reference< XCurrentContext > & ctx) + : m_aRefCount(0), + m_xNextContext( ctx ) +{ +} + +JavaContext::~JavaContext() +{ +} + +Any SAL_CALL JavaContext::queryInterface(const Type& aType ) +{ + if (aType == cppu::UnoType<XInterface>::get()) + return Any(Reference<XInterface>(static_cast<XInterface*>(this))); + else if (aType == cppu::UnoType<XCurrentContext>::get()) + return Any(Reference<XCurrentContext>( static_cast<XCurrentContext*>(this))); + return Any(); +} + +void SAL_CALL JavaContext::acquire( ) throw () +{ + osl_atomic_increment( &m_aRefCount ); +} + +void SAL_CALL JavaContext::release( ) throw () +{ + if (! osl_atomic_decrement( &m_aRefCount )) + delete this; +} + +Any SAL_CALL JavaContext::getValueByName( const OUString& Name) +{ + Any retVal; + + if ( Name == JAVA_INTERACTION_HANDLER_NAME ) + { + { + osl::MutexGuard aGuard(osl::Mutex::getGlobalMutex()); + if (!m_xHandler.is()) + m_xHandler.set( new JavaInteractionHandler ); + } + retVal <<= m_xHandler; + + } + else if( m_xNextContext.is() ) + { + // Call next context in chain if found + retVal = m_xNextContext->getValueByName( Name ); + } + return retVal; +} + + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/java/javainteractionhandler.cxx b/svtools/source/java/javainteractionhandler.cxx new file mode 100644 index 000000000..9dff4a57e --- /dev/null +++ b/svtools/source/java/javainteractionhandler.cxx @@ -0,0 +1,252 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <svtools/strings.hrc> +#include <com/sun/star/task/XInteractionContinuation.hpp> +#include <com/sun/star/task/XInteractionAbort.hpp> +#include <com/sun/star/task/XInteractionRetry.hpp> +#include <com/sun/star/java/JavaNotFoundException.hpp> +#include <com/sun/star/java/InvalidJavaSettingsException.hpp> +#include <com/sun/star/java/JavaDisabledException.hpp> +#include <com/sun/star/java/JavaVMCreationFailureException.hpp> +#include <com/sun/star/java/RestartRequiredException.hpp> +#include <comphelper/processfactory.hxx> +#include <vcl/svapp.hxx> +#include <vcl/weld.hxx> +#include <jvmfwk/framework.hxx> + +#include <svtools/restartdialog.hxx> +#include <svtools/svtresid.hxx> +#include <svtools/javainteractionhandler.hxx> + +using namespace com::sun::star::uno; +using namespace com::sun::star::task; + +namespace +{ +static struct JavaEvents { + bool bDisabledHandled : 1; + bool bInvalidSettingsHandled : 1; + bool bNotFoundHandled : 1; + bool bVMCreationFailureHandled : 1; + bool bRestartRequiredHandled : 1; + sal_uInt16 nResult_JavaDisabled = RET_NO; + JavaEvents() + : bDisabledHandled(false) + , bInvalidSettingsHandled(false) + , bNotFoundHandled(false) + , bVMCreationFailureHandled(false) + , bRestartRequiredHandled(false) + {} +} g_JavaEvents; +} + +namespace svt +{ + +JavaInteractionHandler::JavaInteractionHandler() : + m_aRefCount(0) +{ +} + +JavaInteractionHandler::~JavaInteractionHandler() +{ +} + +Any SAL_CALL JavaInteractionHandler::queryInterface(const Type& aType ) +{ + if (aType == cppu::UnoType<XInterface>::get()) + return Any( static_cast<XInterface*>(this), aType); + else if (aType == cppu::UnoType<XInteractionHandler>::get()) + return Any( static_cast<XInteractionHandler*>(this), aType); + return Any(); +} + +void SAL_CALL JavaInteractionHandler::acquire( ) throw () +{ + osl_atomic_increment( &m_aRefCount ); +} + +void SAL_CALL JavaInteractionHandler::release( ) throw () +{ + if (! osl_atomic_decrement( &m_aRefCount )) + delete this; +} + +void SAL_CALL JavaInteractionHandler::handle( const Reference< XInteractionRequest >& Request ) +{ + Any anyExc = Request->getRequest(); + const Sequence< Reference< XInteractionContinuation > > aSeqCont = Request->getContinuations(); + + Reference< XInteractionAbort > abort; + Reference< XInteractionRetry > retry; + + for ( const auto& rCont : aSeqCont ) + { + abort.set( rCont, UNO_QUERY ); + if ( abort.is() ) + break; + } + + for ( const auto& rCont : aSeqCont ) + { + retry.set( rCont, UNO_QUERY ); + if ( retry.is() ) + break; + } + + css::java::JavaNotFoundException e1; + css::java::InvalidJavaSettingsException e2; + css::java::JavaDisabledException e3; + css::java::JavaVMCreationFailureException e4; + css::java::RestartRequiredException e5; + // Try to recover the Exception type in the any and + // react accordingly. + sal_uInt16 nResult = RET_CANCEL; + + if ( anyExc >>= e1 ) + { + SolarMutexGuard aSolarGuard; + if( !g_JavaEvents.bNotFoundHandled ) + { + // No suitable JRE found + g_JavaEvents.bNotFoundHandled = true; +#if defined( MACOSX ) + std::unique_ptr<weld::MessageDialog> xWarningBox(Application::CreateMessageDialog(nullptr, + VclMessageType::Warning, VclButtonsType::Ok, SvtResId(STR_WARNING_JAVANOTFOUND_MAC))); +#elif defined( _WIN32 ) + std::unique_ptr<weld::MessageDialog> xWarningBox(Application::CreateMessageDialog(nullptr, + VclMessageType::Warning, VclButtonsType::Ok, SvtResId(STR_WARNING_JAVANOTFOUND_WIN))); + OUString sPrimTex = xWarningBox->get_primary_text(); +#if defined( _WIN64 ) + xWarningBox->set_primary_text(sPrimTex.replaceAll( "%BITNESS", "64" )); +#else + xWarningBox->set_primary_text(sPrimTex.replaceAll( "%BITNESS", "32" )); +#endif +#else + std::unique_ptr<weld::MessageDialog> xWarningBox(Application::CreateMessageDialog(nullptr, + VclMessageType::Warning, VclButtonsType::Ok, SvtResId(STR_WARNING_JAVANOTFOUND))); +#endif + xWarningBox->set_title(SvtResId(STR_WARNING_JAVANOTFOUND_TITLE)); + nResult = xWarningBox->run(); + } + else + { + nResult = RET_OK; + } + } + else if ( anyExc >>= e2 ) + { + SolarMutexGuard aSolarGuard; + if( !g_JavaEvents.bInvalidSettingsHandled ) + { + // javavendors.xml was updated and Java has not been configured yet + g_JavaEvents.bInvalidSettingsHandled = true; +#ifdef MACOSX + OUString sWarning(SvtResId(STR_WARNING_INVALIDJAVASETTINGS_MAC)); +#else + OUString sWarning(SvtResId(STR_WARNING_INVALIDJAVASETTINGS)); +#endif + std::unique_ptr<weld::MessageDialog> xWarningBox(Application::CreateMessageDialog(nullptr, + VclMessageType::Warning, VclButtonsType::Ok, sWarning)); + xWarningBox->set_title(SvtResId(STR_WARNING_INVALIDJAVASETTINGS_TITLE)); + nResult = xWarningBox->run(); + } + else + { + nResult = RET_OK; + } + } + else if ( anyExc >>= e3 ) + { + SolarMutexGuard aSolarGuard; + if( !g_JavaEvents.bDisabledHandled ) + { + g_JavaEvents.bDisabledHandled = true; + // Java disabled. Give user a chance to enable Java inside Office. + std::unique_ptr<weld::Builder> xBuilder(Application::CreateBuilder(nullptr, "svt/ui/javadisableddialog.ui")); + std::unique_ptr<weld::MessageDialog> xQueryBox(xBuilder->weld_message_dialog("JavaDisabledDialog")); + nResult = xQueryBox->run(); + if ( nResult == RET_YES ) + { + jfw_setEnabled(true); + } + + g_JavaEvents.nResult_JavaDisabled = nResult; + + } + else + { + nResult = g_JavaEvents.nResult_JavaDisabled; + } + } + else if ( anyExc >>= e4 ) + { + SolarMutexGuard aSolarGuard; + if( !g_JavaEvents.bVMCreationFailureHandled ) + { + // Java not correctly installed, or damaged + g_JavaEvents.bVMCreationFailureHandled = true; +#ifdef MACOSX + OUString sWarning(SvtResId(STR_ERROR_JVMCREATIONFAILED_MAC)); +#else + OUString sWarning(SvtResId(STR_ERROR_JVMCREATIONFAILED)); +#endif + std::unique_ptr<weld::MessageDialog> xErrorBox(Application::CreateMessageDialog(nullptr, + VclMessageType::Warning, VclButtonsType::Ok, sWarning)); + xErrorBox->set_title(SvtResId(STR_ERROR_JVMCREATIONFAILED_TITLE)); + nResult = xErrorBox->run(); + } + else + { + nResult = RET_OK; + } + } + else if ( anyExc >>= e5 ) + { + SolarMutexGuard aSolarGuard; + if( !g_JavaEvents.bRestartRequiredHandled ) + { + // a new JRE was selected, but office needs to be restarted + //before it can be used. + g_JavaEvents.bRestartRequiredHandled = true; + svtools::executeRestartDialog( + comphelper::getProcessComponentContext(), nullptr, + svtools::RESTART_REASON_JAVA); + } + nResult = RET_OK; + } + + if ( nResult == RET_CANCEL || nResult == RET_NO) + { + // Unknown exception type or user wants to cancel + if ( abort.is() ) + abort->select(); + } + else // nResult == RET_OK + { + // User selected OK => retry Java usage + if ( retry.is() ) + retry->select(); + } +} + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/misc/acceleratorexecute.cxx b/svtools/source/misc/acceleratorexecute.cxx new file mode 100644 index 000000000..0a36c491f --- /dev/null +++ b/svtools/source/misc/acceleratorexecute.cxx @@ -0,0 +1,494 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <memory> +#include <svtools/acceleratorexecute.hxx> + +#include <com/sun/star/frame/ModuleManager.hpp> +#include <com/sun/star/frame/Desktop.hpp> +#include <com/sun/star/ui/GlobalAcceleratorConfiguration.hpp> +#include <com/sun/star/ui/XUIConfigurationManager.hpp> +#include <com/sun/star/ui/theModuleUIConfigurationManagerSupplier.hpp> +#include <com/sun/star/ui/XUIConfigurationManagerSupplier.hpp> +#include <com/sun/star/awt/KeyModifier.hpp> +#include <com/sun/star/uno/Sequence.hxx> +#include <com/sun/star/beans/PropertyValue.hpp> +#include <com/sun/star/util/URLTransformer.hpp> +#include <cppuhelper/implbase.hxx> + +#include <vcl/evntpost.hxx> +#include <sal/log.hxx> +#include <vcl/lok.hxx> +#include <vcl/window.hxx> +#include <vcl/svapp.hxx> +#include <osl/mutex.hxx> + +namespace svt +{ + +namespace { + +class AsyncAccelExec : public cppu::WeakImplHelper<css::lang::XEventListener> +{ + private: + css::uno::Reference<css::lang::XComponent> m_xFrame; + css::uno::Reference< css::frame::XDispatch > m_xDispatch; + css::util::URL m_aURL; + vcl::EventPoster m_aAsyncCallback; + public: + + /** creates a new instance of this class, which can be used + one times only! + + This instance can be forced to execute its internal set request + asynchronous. After that it deletes itself! + */ + static AsyncAccelExec* createOneShotInstance(const css::uno::Reference<css::lang::XComponent>& xFrame, + const css::uno::Reference<css::frame::XDispatch>& xDispatch, + const css::util::URL& rURL); + + void execAsync(); + private: + + virtual void SAL_CALL disposing(const css::lang::EventObject&) override + { + m_xFrame->removeEventListener(this); + m_xFrame.clear(); + m_xDispatch.clear(); + } + + /** @short allow creation of instances of this class + by using our factory only! + */ + AsyncAccelExec(const css::uno::Reference<css::lang::XComponent>& xFrame, + const css::uno::Reference< css::frame::XDispatch >& xDispatch, + const css::util::URL& rURL); + + DECL_LINK(impl_ts_asyncCallback, LinkParamNone*, void); +}; + +} + +AcceleratorExecute::AcceleratorExecute() + : TMutexInit() +{ +} + +AcceleratorExecute::~AcceleratorExecute() +{ + // does nothing real +} + + +std::unique_ptr<AcceleratorExecute> AcceleratorExecute::createAcceleratorHelper() +{ + return std::unique_ptr<AcceleratorExecute>(new AcceleratorExecute); +} + + +void AcceleratorExecute::init(const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const css::uno::Reference< css::frame::XFrame >& xEnv ) +{ + // SAFE -> ---------------------------------- + ::osl::ResettableMutexGuard aLock(m_aLock); + + // take over the uno service manager + m_xContext = rxContext; + + // specify our internal dispatch provider + // frame or desktop?! => document or global config. + bool bDesktopIsUsed = false; + m_xDispatcher.set(xEnv, css::uno::UNO_QUERY); + if (!m_xDispatcher.is()) + { + aLock.clear(); + // <- SAFE ------------------------------ + + css::uno::Reference< css::frame::XDispatchProvider > xDispatcher(css::frame::Desktop::create(rxContext), css::uno::UNO_QUERY_THROW); + + // SAFE -> ------------------------------ + aLock.reset(); + + m_xDispatcher = xDispatcher; + bDesktopIsUsed = true; + } + + aLock.clear(); + // <- SAFE ---------------------------------- + + // open all needed configuration objects + css::uno::Reference< css::ui::XAcceleratorConfiguration > xGlobalCfg; + css::uno::Reference< css::ui::XAcceleratorConfiguration > xModuleCfg; + css::uno::Reference< css::ui::XAcceleratorConfiguration > xDocCfg ; + + // global cfg + xGlobalCfg = css::ui::GlobalAcceleratorConfiguration::create(rxContext); + if (!bDesktopIsUsed) + { + // module cfg + xModuleCfg = AcceleratorExecute::st_openModuleConfig(rxContext, xEnv); + + // doc cfg + css::uno::Reference< css::frame::XController > xController; + css::uno::Reference< css::frame::XModel > xModel; + xController = xEnv->getController(); + if (xController.is()) + xModel = xController->getModel(); + if (xModel.is()) + xDocCfg = AcceleratorExecute::st_openDocConfig(xModel); + } + + // SAFE -> ------------------------------ + aLock.reset(); + + m_xGlobalCfg = xGlobalCfg; + m_xModuleCfg = xModuleCfg; + m_xDocCfg = xDocCfg ; + + aLock.clear(); + // <- SAFE ---------------------------------- +} + + +bool AcceleratorExecute::execute(const vcl::KeyCode& aVCLKey) +{ + css::awt::KeyEvent aAWTKey = AcceleratorExecute::st_VCLKey2AWTKey(aVCLKey); + return execute(aAWTKey); +} + + +bool AcceleratorExecute::execute(const css::awt::KeyEvent& aAWTKey) +{ + OUString sCommand = impl_ts_findCommand(aAWTKey); + + // No Command found? Do nothing! User is not interested on any error handling .-) + // or for some reason m_xContext is NULL (which would crash impl_ts_getURLParser() + if (sCommand.isEmpty() || !m_xContext.is()) + { + return false; + } + + // SAFE -> ---------------------------------- + osl::ClearableMutexGuard aLock(m_aLock); + + css::uno::Reference< css::frame::XDispatchProvider > xProvider = m_xDispatcher; + + aLock.clear(); + // <- SAFE ---------------------------------- + + // convert command in URL structure + css::uno::Reference< css::util::XURLTransformer > xParser = impl_ts_getURLParser(); + css::util::URL aURL; + aURL.Complete = sCommand; + xParser->parseStrict(aURL); + + // ask for dispatch object + css::uno::Reference< css::frame::XDispatch > xDispatch = xProvider->queryDispatch(aURL, OUString(), 0); + bool bRet = xDispatch.is(); + if ( bRet ) + { + // Note: Such instance can be used one times only and destroy itself afterwards .-) + css::uno::Reference<css::lang::XComponent> xFrame(xProvider, css::uno::UNO_QUERY); + if (vcl::lok::isUnipoll()) + { // tdf#130382 - all synchronous really. + try { + xDispatch->dispatch (aURL, css::uno::Sequence< css::beans::PropertyValue >()); + } + catch(const css::uno::Exception&ev) + { + SAL_INFO("svtools", "exception on key emission: " << ev.Message); + } + } + else + { + AsyncAccelExec* pExec = AsyncAccelExec::createOneShotInstance(xFrame, xDispatch, aURL); + pExec->execAsync(); + } + } + + return bRet; +} + + +css::awt::KeyEvent AcceleratorExecute::st_VCLKey2AWTKey(const vcl::KeyCode& aVCLKey) +{ + css::awt::KeyEvent aAWTKey; + aAWTKey.Modifiers = 0; + aAWTKey.KeyCode = static_cast<sal_Int16>(aVCLKey.GetCode()); + + if (aVCLKey.IsShift()) + aAWTKey.Modifiers |= css::awt::KeyModifier::SHIFT; + if (aVCLKey.IsMod1()) + aAWTKey.Modifiers |= css::awt::KeyModifier::MOD1; + if (aVCLKey.IsMod2()) + aAWTKey.Modifiers |= css::awt::KeyModifier::MOD2; + if (aVCLKey.IsMod3()) + aAWTKey.Modifiers |= css::awt::KeyModifier::MOD3; + return aAWTKey; +} + + +vcl::KeyCode AcceleratorExecute::st_AWTKey2VCLKey(const css::awt::KeyEvent& aAWTKey) +{ + bool bShift = ((aAWTKey.Modifiers & css::awt::KeyModifier::SHIFT) == css::awt::KeyModifier::SHIFT ); + bool bMod1 = ((aAWTKey.Modifiers & css::awt::KeyModifier::MOD1 ) == css::awt::KeyModifier::MOD1 ); + bool bMod2 = ((aAWTKey.Modifiers & css::awt::KeyModifier::MOD2 ) == css::awt::KeyModifier::MOD2 ); + bool bMod3 = ((aAWTKey.Modifiers & css::awt::KeyModifier::MOD3 ) == css::awt::KeyModifier::MOD3 ); + sal_uInt16 nKey = static_cast<sal_uInt16>(aAWTKey.KeyCode); + + return vcl::KeyCode(nKey, bShift, bMod1, bMod2, bMod3); +} + +OUString AcceleratorExecute::findCommand(const css::awt::KeyEvent& aKey) +{ + return impl_ts_findCommand(aKey); +} + +OUString AcceleratorExecute::impl_ts_findCommand(const css::awt::KeyEvent& aKey) +{ + // SAFE -> ---------------------------------- + osl::ClearableMutexGuard aLock(m_aLock); + + css::uno::Reference< css::ui::XAcceleratorConfiguration > xGlobalCfg = m_xGlobalCfg; + css::uno::Reference< css::ui::XAcceleratorConfiguration > xModuleCfg = m_xModuleCfg; + css::uno::Reference< css::ui::XAcceleratorConfiguration > xDocCfg = m_xDocCfg ; + + aLock.clear(); + // <- SAFE ---------------------------------- + + OUString sCommand; + + try + { + if (xDocCfg.is()) + sCommand = xDocCfg->getCommandByKeyEvent(aKey); + if (!sCommand.isEmpty()) + return sCommand; + } + catch(const css::container::NoSuchElementException&) + {} + + try + { + if (xModuleCfg.is()) + sCommand = xModuleCfg->getCommandByKeyEvent(aKey); + if (!sCommand.isEmpty()) + return sCommand; + } + catch(const css::container::NoSuchElementException&) + {} + + try + { + if (xGlobalCfg.is()) + sCommand = xGlobalCfg->getCommandByKeyEvent(aKey); + if (!sCommand.isEmpty()) + return sCommand; + } + catch(const css::container::NoSuchElementException&) + {} + + // fall back to functional key codes + if( aKey.Modifiers == 0 ) + { + switch( aKey.KeyCode ) + { + case css::awt::Key::DELETE_TO_BEGIN_OF_LINE: + return ".uno:DelToStartOfLine"; + case css::awt::Key::DELETE_TO_END_OF_LINE: + return ".uno:DelToEndOfLine"; + case css::awt::Key::DELETE_TO_BEGIN_OF_PARAGRAPH: + return ".uno:DelToStartOfPara"; + case css::awt::Key::DELETE_TO_END_OF_PARAGRAPH: + return ".uno:DelToEndOfPara"; + case css::awt::Key::DELETE_WORD_BACKWARD: + return ".uno:DelToStartOfWord"; + case css::awt::Key::DELETE_WORD_FORWARD: + return ".uno:DelToEndOfWord"; + case css::awt::Key::INSERT_LINEBREAK: + return ".uno:InsertLinebreak"; + case css::awt::Key::INSERT_PARAGRAPH: + return ".uno:InsertPara"; + case css::awt::Key::MOVE_WORD_BACKWARD: + return ".uno:GoToPrevWord"; + case css::awt::Key::MOVE_WORD_FORWARD: + return ".uno:GoToNextWord"; + case css::awt::Key::MOVE_TO_BEGIN_OF_LINE: + return ".uno:GoToStartOfLine"; + case css::awt::Key::MOVE_TO_END_OF_LINE: + return ".uno:GoToEndOfLine"; + case css::awt::Key::MOVE_TO_BEGIN_OF_PARAGRAPH: + return ".uno:GoToStartOfPara"; + case css::awt::Key::MOVE_TO_END_OF_PARAGRAPH: + return ".uno:GoToEndOfPara"; + case css::awt::Key::MOVE_TO_BEGIN_OF_DOCUMENT: + return ".uno:GoToStartOfDoc"; + case css::awt::Key::MOVE_TO_END_OF_DOCUMENT: + return ".uno:GoToEndOfDoc"; + case css::awt::Key::SELECT_BACKWARD: + return ".uno:CharLeftSel"; + case css::awt::Key::SELECT_FORWARD: + return ".uno:CharRightSel"; + case css::awt::Key::SELECT_WORD_BACKWARD: + return ".uno:WordLeftSel"; + case css::awt::Key::SELECT_WORD_FORWARD: + return ".uno:WordRightSel"; + case css::awt::Key::SELECT_WORD: + return ".uno:SelectWord"; + case css::awt::Key::SELECT_LINE: + return OUString(); + case css::awt::Key::SELECT_PARAGRAPH: + return ".uno:SelectText"; + case css::awt::Key::SELECT_TO_BEGIN_OF_LINE: + return ".uno:StartOfLineSel"; + case css::awt::Key::SELECT_TO_END_OF_LINE: + return ".uno:EndOfLineSel"; + case css::awt::Key::SELECT_TO_BEGIN_OF_PARAGRAPH: + return ".uno:StartOfParaSel"; + case css::awt::Key::SELECT_TO_END_OF_PARAGRAPH: + return ".uno:EndOfParaSel"; + case css::awt::Key::SELECT_TO_BEGIN_OF_DOCUMENT: + return ".uno:StartOfDocumentSel"; + case css::awt::Key::SELECT_TO_END_OF_DOCUMENT: + return ".uno:EndOfDocumentSel"; + case css::awt::Key::SELECT_ALL: + return ".uno:SelectAll"; + default: + break; + } + } + + return OUString(); +} + + +css::uno::Reference< css::ui::XAcceleratorConfiguration > AcceleratorExecute::st_openModuleConfig(const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const css::uno::Reference< css::frame::XFrame >& xFrame) +{ + css::uno::Reference< css::frame::XModuleManager2 > xModuleDetection( + css::frame::ModuleManager::create(rxContext)); + + OUString sModule; + try + { + sModule = xModuleDetection->identify(xFrame); + } + catch(const css::uno::RuntimeException&) + { throw; } + catch(const css::uno::Exception&) + { return css::uno::Reference< css::ui::XAcceleratorConfiguration >(); } + + css::uno::Reference< css::ui::XModuleUIConfigurationManagerSupplier > xUISupplier( + css::ui::theModuleUIConfigurationManagerSupplier::get(rxContext) ); + + css::uno::Reference< css::ui::XAcceleratorConfiguration > xAccCfg; + try + { + css::uno::Reference< css::ui::XUIConfigurationManager > xUIManager = xUISupplier->getUIConfigurationManager(sModule); + xAccCfg = xUIManager->getShortCutManager(); + } + catch(const css::container::NoSuchElementException&) + {} + return xAccCfg; +} + + +css::uno::Reference< css::ui::XAcceleratorConfiguration > AcceleratorExecute::st_openDocConfig(const css::uno::Reference< css::frame::XModel >& xModel) +{ + css::uno::Reference< css::ui::XAcceleratorConfiguration > xAccCfg; + css::uno::Reference< css::ui::XUIConfigurationManagerSupplier > xUISupplier(xModel, css::uno::UNO_QUERY); + if (xUISupplier.is()) + { + css::uno::Reference< css::ui::XUIConfigurationManager > xUIManager = xUISupplier->getUIConfigurationManager(); + xAccCfg = xUIManager->getShortCutManager(); + } + return xAccCfg; +} + + +css::uno::Reference< css::util::XURLTransformer > AcceleratorExecute::impl_ts_getURLParser() +{ + // SAFE -> ---------------------------------- + ::osl::ResettableMutexGuard aLock(m_aLock); + + if (m_xURLParser.is()) + return m_xURLParser; + css::uno::Reference< css::uno::XComponentContext > xContext = m_xContext; + + aLock.clear(); + // <- SAFE ---------------------------------- + + css::uno::Reference< css::util::XURLTransformer > xParser = css::util::URLTransformer::create( xContext ); + + // SAFE -> ---------------------------------- + aLock.reset(); + m_xURLParser = xParser; + aLock.clear(); + // <- SAFE ---------------------------------- + + return xParser; +} + +AsyncAccelExec::AsyncAccelExec(const css::uno::Reference<css::lang::XComponent>& xFrame, + const css::uno::Reference<css::frame::XDispatch>& xDispatch, + const css::util::URL& rURL) + : m_xFrame(xFrame) + , m_xDispatch(xDispatch) + , m_aURL(rURL) + , m_aAsyncCallback(LINK(this, AsyncAccelExec, impl_ts_asyncCallback)) +{ +} + +AsyncAccelExec* AsyncAccelExec::createOneShotInstance(const css::uno::Reference<css::lang::XComponent> &xFrame, + const css::uno::Reference< css::frame::XDispatch >& xDispatch, + const css::util::URL& rURL) +{ + AsyncAccelExec* pExec = new AsyncAccelExec(xFrame, xDispatch, rURL); + return pExec; +} + + +void AsyncAccelExec::execAsync() +{ + acquire(); + if (m_xFrame.is()) + m_xFrame->addEventListener(this); + m_aAsyncCallback.Post(); +} + +IMPL_LINK_NOARG(AsyncAccelExec, impl_ts_asyncCallback, LinkParamNone*, void) +{ + if (m_xDispatch.is()) + { + try + { + if (m_xFrame.is()) + m_xFrame->removeEventListener(this); + m_xDispatch->dispatch(m_aURL, css::uno::Sequence< css::beans::PropertyValue >()); + } + catch(const css::uno::Exception&) + { + } + } + release(); +} + +} // namespace svt + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/misc/bindablecontrolhelper.cxx b/svtools/source/misc/bindablecontrolhelper.cxx new file mode 100644 index 000000000..0fe8d8503 --- /dev/null +++ b/svtools/source/misc/bindablecontrolhelper.cxx @@ -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 . + */ + +#include <svtools/bindablecontrolhelper.hxx> +#include <com/sun/star/form/binding/XBindableValue.hpp> +#include <com/sun/star/form/binding/XValueBinding.hpp> +#include <com/sun/star/form/binding/XListEntrySink.hpp> +#include <com/sun/star/form/binding/XListEntrySource.hpp> +#include <com/sun/star/frame/XModel.hpp> +#include <com/sun/star/beans/XPropertySet.hpp> +#include <com/sun/star/container/XNameAccess.hpp> +#include <com/sun/star/table/CellRangeAddress.hpp> +#include <com/sun/star/sheet/XCellRangeReferrer.hpp> +#include <com/sun/star/sheet/XCellRangeAddressable.hpp> +#include <com/sun/star/lang/XMultiServiceFactory.hpp> +#include <com/sun/star/table/CellAddress.hpp> +#include <com/sun/star/beans/NamedValue.hpp> + + +namespace svt +{ + + +using namespace ::com::sun::star; + +static bool lcl_isNamedRange( const OUString& sAddress, const uno::Reference< frame::XModel >& xModel, css::table::CellRangeAddress& aAddress ) +{ + bool bRes = false; + uno::Reference< sheet::XCellRangeReferrer > xReferrer; + try + { + uno::Reference< beans::XPropertySet > xPropSet( xModel, uno::UNO_QUERY_THROW ); + uno::Reference< container::XNameAccess > xNamed( xPropSet->getPropertyValue( "NamedRanges" ), uno::UNO_QUERY_THROW ); + xReferrer.set ( xNamed->getByName( sAddress ), uno::UNO_QUERY ); + } + catch( uno::Exception& /*e*/ ) + { + // do nothing + } + if ( xReferrer.is() ) + { + uno::Reference< sheet::XCellRangeAddressable > xRangeAddressable( xReferrer->getReferredCells(), uno::UNO_QUERY ); + if ( xRangeAddressable.is() ) + { + aAddress = xRangeAddressable->getRangeAddress(); + bRes = true; + } + } + return bRes; +} + + +void +BindableControlHelper::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 ) +{ +// XBindable etc. + uno::Reference< lang::XMultiServiceFactory > xFac; + if ( xModel.is() ) + xFac.set( xModel, uno::UNO_QUERY ); + uno::Reference< form::binding::XBindableValue > xBindable( rObj, uno::UNO_QUERY ); + if ( xFac.is() && rsCtrlSource.getLength() && xBindable.is() ) + { + + // OOo address structures + // RefCell - convert from XL + // pretend we converted the imported string address into the + // appropriate address structure + uno::Reference< beans::XPropertySet > xConvertor( xFac->createInstance( "com.sun.star.table.CellAddressConversion"), uno::UNO_QUERY ); + css::table::CellAddress aAddress; + if ( xConvertor.is() ) + { + // we need this service to properly convert XL notation also + // Should be easy to extend + xConvertor->setPropertyValue( "ReferenceSheet", uno::makeAny( nRefTab ) ); + xConvertor->setPropertyValue( "XLA1Representation", uno::makeAny( rsCtrlSource ) ); + xConvertor->getPropertyValue( "Address" ) >>= aAddress; + } + + beans::NamedValue aArg1; + aArg1.Name = "BoundCell"; + aArg1.Value <<= aAddress; + + uno::Sequence< uno::Any > aArgs(1); + aArgs[ 0 ] <<= aArg1; + + uno::Reference< form::binding::XValueBinding > xBinding( xFac->createInstanceWithArguments( "com.sun.star.table.CellValueBinding", aArgs ), uno::UNO_QUERY ); + xBindable->setValueBinding( xBinding ); + } + else if ( xBindable.is() ) // reset it + xBindable->setValueBinding( uno::Reference< form::binding::XValueBinding >() ); + uno::Reference< form::binding::XListEntrySink > xListEntrySink( rObj, uno::UNO_QUERY ); + if ( xFac.is() && rsRowSource.getLength() && xListEntrySink.is() ) + { + + // OOo address structures + // RefCell - convert from XL + // pretend we converted the imported string address into the + // appropriate address structure + uno::Reference< beans::XPropertySet > xConvertor( xFac->createInstance( "com.sun.star.table.CellRangeAddressConversion"), uno::UNO_QUERY ); + css::table::CellRangeAddress aAddress; + if ( xConvertor.is() ) + { + if ( !lcl_isNamedRange( rsRowSource, xModel, aAddress ) ) + { + // we need this service to properly convert XL notation also + // Should be easy to extend + xConvertor->setPropertyValue( "ReferenceSheet", uno::makeAny( nRefTab ) ); + xConvertor->setPropertyValue( "XLA1Representation", uno::makeAny( rsRowSource ) ); + xConvertor->getPropertyValue( "Address" ) >>= aAddress; + } + } + + beans::NamedValue aArg1; + aArg1.Name = "CellRange"; + aArg1.Value <<= aAddress; + + uno::Sequence< uno::Any > aArgs(1); + aArgs[ 0 ] <<= aArg1; + + uno::Reference< form::binding::XListEntrySource > xSource( xFac->createInstanceWithArguments( "com.sun.star.table.CellRangeListSource", aArgs ), uno::UNO_QUERY ); + xListEntrySink->setListEntrySource( xSource ); + } + else if ( xListEntrySink.is() ) // reset + xListEntrySink->setListEntrySource( uno::Reference< form::binding::XListEntrySource >() ); + +} + + +} // namespace svt + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/misc/cliplistener.cxx b/svtools/source/misc/cliplistener.cxx new file mode 100644 index 000000000..992d9efb9 --- /dev/null +++ b/svtools/source/misc/cliplistener.cxx @@ -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 . + */ + + +#include <com/sun/star/datatransfer/clipboard/XClipboardNotifier.hpp> + +#include <vcl/svapp.hxx> +#include <vcl/window.hxx> + +#include <svtools/cliplistener.hxx> +#include <vcl/transfer.hxx> + +using namespace ::com::sun::star; + + +TransferableClipboardListener::TransferableClipboardListener( const Link<TransferableDataHelper*,void>& rCallback ) : + aLink( rCallback ) +{ +} + +TransferableClipboardListener::~TransferableClipboardListener() +{ +} + +void SAL_CALL TransferableClipboardListener::disposing( const lang::EventObject& ) +{ +} + +void SAL_CALL TransferableClipboardListener::changedContents( + const datatransfer::clipboard::ClipboardEvent& rEventObject ) +{ + if ( aLink.IsSet() ) + { + const SolarMutexGuard aGuard; + + TransferableDataHelper aDataHelper( rEventObject.Contents ); + aLink.Call( &aDataHelper ); + } +} + +void TransferableClipboardListener::AddRemoveListener( vcl::Window* pWin, bool bAdd ) +{ + try + { + if ( pWin ) + { + uno::Reference<datatransfer::clipboard::XClipboard> xClipboard = pWin->GetClipboard(); + uno::Reference<datatransfer::clipboard::XClipboardNotifier> xClpbrdNtfr( xClipboard, uno::UNO_QUERY ); + if( xClpbrdNtfr.is() ) + { + uno::Reference<datatransfer::clipboard::XClipboardListener> xClipEvtLstnr( this ); + if( bAdd ) + xClpbrdNtfr->addClipboardListener( xClipEvtLstnr ); + else + xClpbrdNtfr->removeClipboardListener( xClipEvtLstnr ); + } + } + } + catch( const css::uno::Exception& ) + { + } +} + +void TransferableClipboardListener::ClearCallbackLink() +{ + aLink = Link<TransferableDataHelper*,void>(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/misc/dialogclosedlistener.cxx b/svtools/source/misc/dialogclosedlistener.cxx new file mode 100644 index 000000000..c9e4c095e --- /dev/null +++ b/svtools/source/misc/dialogclosedlistener.cxx @@ -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 . + */ + +#include <svtools/dialogclosedlistener.hxx> + + +namespace svt +{ + + + using namespace ::com::sun::star::lang; + using namespace ::com::sun::star::uno; + using namespace ::com::sun::star::ui::dialogs; + + + //= DialogClosedListener + + + DialogClosedListener::DialogClosedListener() + { + } + + // XDialogClosedListener methods + void SAL_CALL DialogClosedListener::dialogClosed( const DialogClosedEvent& aEvent ) + { + if ( m_aDialogClosedLink.IsSet() ) + { + css::ui::dialogs::DialogClosedEvent aEvt( aEvent ); + m_aDialogClosedLink.Call( &aEvt ); + } + } + + // XEventListener methods + void SAL_CALL DialogClosedListener::disposing( const EventObject& ) + { + m_aDialogClosedLink = Link<css::ui::dialogs::DialogClosedEvent*,void>(); + } + + +} // namespace svt + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/misc/ehdl.cxx b/svtools/source/misc/ehdl.cxx new file mode 100644 index 000000000..1dcfbc990 --- /dev/null +++ b/svtools/source/misc/ehdl.cxx @@ -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 . + */ + +#include <unotools/resmgr.hxx> +#include <vcl/stdtext.hxx> +#include <vcl/svapp.hxx> +#include <vcl/weld.hxx> +#include <sal/log.hxx> + +#include <svtools/ehdl.hxx> +#include <svtools/svtresid.hxx> +#include <svtools/sfxecode.hxx> +#include <memory> +#include <errtxt.hrc> + +static DialogMask aWndFunc( + weld::Window *pWin, // Parent of the dialog + DialogMask nFlags, + const OUString &rErr, // error text + const OUString &rAction) // action text + +/* [Description] + + Draw an errorbox on the screen. Depending on nFlags + Error/Info etc. boxes with the requested buttons are shown. + + Returnvalue is the button pressed + + */ + + +{ + SolarMutexGuard aGuard; + + // determine necessary WinBits from the flags + VclButtonsType eButtonsType = VclButtonsType::NONE; + bool bAddRetry = false; + if ( (nFlags & (DialogMask::ButtonsCancel | DialogMask::ButtonsRetry)) == (DialogMask::ButtonsCancel | DialogMask::ButtonsRetry)) + { + bAddRetry = true; + eButtonsType = VclButtonsType::Cancel; + } + else if ( (nFlags & DialogMask::ButtonsOk) == DialogMask::ButtonsOk ) + eButtonsType = VclButtonsType::Ok; + else if ( (nFlags & DialogMask::ButtonsYesNo) == DialogMask::ButtonsYesNo ) + eButtonsType = VclButtonsType::YesNo; + + OUString aErr("$(ACTION)$(ERROR)"); + OUString aAction(rAction); + if ( !aAction.isEmpty() ) + aAction += ":\n"; + aErr = aErr.replaceAll("$(ACTION)", aAction); + aErr = aErr.replaceAll("$(ERROR)", rErr); + + VclMessageType eMessageType; + switch (nFlags & DialogMask(0xf000)) + { + case DialogMask::MessageError: + eMessageType = VclMessageType::Error; + break; + + case DialogMask::MessageWarning: + eMessageType = VclMessageType::Warning; + break; + + case DialogMask::MessageInfo: + eMessageType = VclMessageType::Info; + break; + + default: + { + SAL_WARN( "svtools.misc", "no MessBox type"); + return DialogMask::ButtonsOk; + } + } + + std::unique_ptr<weld::MessageDialog> xBox(Application::CreateMessageDialog(pWin, + eMessageType, eButtonsType, aErr)); + + if (bAddRetry) + xBox->add_button(GetStandardText(StandardButtonType::Retry), RET_RETRY); + + switch(nFlags & DialogMask(0x0f00)) + { + case DialogMask::ButtonDefaultsOk: + xBox->set_default_response(RET_OK); + break; + case DialogMask::ButtonDefaultsCancel: + xBox->set_default_response(RET_CANCEL); + break; + case DialogMask::ButtonDefaultsYes: + xBox->set_default_response(RET_YES); + break; + case DialogMask::ButtonDefaultsNo: + xBox->set_default_response(RET_NO); + break; + default: + break; + } + + DialogMask nRet = DialogMask::NONE; + switch (xBox->run()) + { + case RET_OK: + nRet = DialogMask::ButtonsOk; + break; + case RET_CANCEL: + nRet = DialogMask::ButtonsCancel; + break; + case RET_RETRY: + nRet = DialogMask::ButtonsRetry; + break; + case RET_YES: + nRet = DialogMask::ButtonsYes; + break; + case RET_NO: + nRet = DialogMask::ButtonsNo; + break; + default: + SAL_WARN( "svtools.misc", "Unknown MessBox return value" ); + break; + } + + return nRet; +} + +SfxErrorHandler::SfxErrorHandler(const ErrMsgCode* pIdPs, ErrCodeArea lStartP, ErrCodeArea lEndP, const std::locale& rLocale) + : lStart(lStartP), lEnd(lEndP), pIds(pIdPs), aResLocale(rLocale) +{ + ErrorRegistry::RegisterDisplay(&aWndFunc); +} + +SfxErrorHandler::~SfxErrorHandler() +{ +} + +bool SfxErrorHandler::CreateString(const ErrorInfo *pErr, OUString &rStr) const + +/* [Description] + + Assemble error string for the ErrorInfo pErr. + + */ + +{ + ErrCode nErrCode(sal_uInt32(pErr->GetErrorCode()) & ERRCODE_ERROR_MASK); + if (pErr->GetErrorCode().GetArea() < lStart || lEnd < pErr->GetErrorCode().GetArea()) + return false; + if(GetErrorString(nErrCode, rStr)) + { + const StringErrorInfo *pStringInfo = dynamic_cast<const StringErrorInfo *>(pErr); + if(pStringInfo) + { + rStr = rStr.replaceAll("$(ARG1)", pStringInfo->GetErrorString()); + } + else + { + const TwoStringErrorInfo * pTwoStringInfo = dynamic_cast<const TwoStringErrorInfo* >(pErr); + if (pTwoStringInfo) + { + rStr = rStr.replaceAll("$(ARG1)", pTwoStringInfo->GetArg1()); + rStr = rStr.replaceAll("$(ARG2)", pTwoStringInfo->GetArg2()); + } + } + return true; + } + return false; +} + +void SfxErrorHandler::GetClassString(ErrCodeClass lClassId, OUString &rStr) + +/* [Description] + + Creates the string for the class of the error. Will always + be read from the resource of the Sfx. + + */ + +{ + for (const std::pair<const char*, ErrCodeClass>* pItem = RID_ERRHDL_CLASS; pItem->first; ++pItem) + { + if (pItem->second == lClassId) + { + rStr = SvtResId(pItem->first); + break; + } + } +} + +bool SfxErrorHandler::GetErrorString(ErrCode lErrId, OUString &rStr) const + +/* [Description] + + Creates the error string for the actual error + without its class + + */ + +{ + bool bRet = false; + rStr = "$(CLASS)$(ERROR)"; + + for (const ErrMsgCode* pItem = pIds; pItem->second; ++pItem) + { + if (pItem->second.StripWarningAndDynamic() == lErrId.StripWarningAndDynamic()) + { + rStr = rStr.replaceAll("$(ERROR)", Translate::get(pItem->first, aResLocale)); + bRet = true; + break; + } + } + + if( bRet ) + { + OUString aErrStr; + GetClassString(lErrId.GetClass(), aErrStr); + if(!aErrStr.isEmpty()) + aErrStr += ".\n"; + rStr = rStr.replaceAll("$(CLASS)",aErrStr); + } + + return bRet; +} + +SfxErrorContext::SfxErrorContext( + sal_uInt16 nCtxIdP, weld::Window *pWindow, const ErrMsgCode* pIdsP, const std::locale& rResLocaleP) +: ErrorContext(pWindow), nCtxId(nCtxIdP), pIds(pIdsP), aResLocale(rResLocaleP) +{ + if (!pIds) + pIds = RID_ERRCTX; +} + + +SfxErrorContext::SfxErrorContext( + sal_uInt16 nCtxIdP, const OUString &aArg1P, weld::Window *pWindow, + const ErrMsgCode* pIdsP, const std::locale& rResLocaleP) +: ErrorContext(pWindow), nCtxId(nCtxIdP), pIds(pIdsP), aResLocale(rResLocaleP), + aArg1(aArg1P) +{ + if (!pIds) + pIds = RID_ERRCTX; +} + +bool SfxErrorContext::GetString(ErrCode nErrId, OUString &rStr) + +/* [Description] + + Constructs the description of an error context + */ + +{ + bool bRet = false; + for (const ErrMsgCode* pItem = pIds; pItem->second; ++pItem) + { + if (sal_uInt32(pItem->second) == nCtxId) + { + rStr = Translate::get(pItem->first, aResLocale); + rStr = rStr.replaceAll("$(ARG1)", aArg1); + bRet = true; + break; + } + } + + SAL_WARN_IF(!bRet, "svtools.misc", "ErrorContext cannot find the resource"); + + if ( bRet ) + { + sal_uInt16 nId = nErrId.IsWarning() ? ERRCTX_WARNING : ERRCTX_ERROR; + for (const ErrMsgCode* pItem = RID_ERRCTX; pItem->second; ++pItem) + { + if (sal_uInt32(pItem->second) == nId) + { + rStr = rStr.replaceAll("$(ERR)", Translate::get(pItem->first, aResLocale)); + break; + } + } + } + + return bRet; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/misc/embedhlp.cxx b/svtools/source/misc/embedhlp.cxx new file mode 100644 index 000000000..2319485a6 --- /dev/null +++ b/svtools/source/misc/embedhlp.cxx @@ -0,0 +1,958 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <svtools/embedhlp.hxx> +#include <vcl/graphicfilter.hxx> +#include <vcl/gdimtf.hxx> +#include <vcl/outdev.hxx> +#include <bitmaps.hlst> + +#include <sal/log.hxx> +#include <comphelper/fileformat.h> +#include <comphelper/embeddedobjectcontainer.hxx> +#include <toolkit/helper/vclunohelper.hxx> +#include <unotools/ucbstreamhelper.hxx> +#include <unotools/streamwrap.hxx> +#include <com/sun/star/chart2/XChartDocument.hpp> +#include <com/sun/star/chart2/XCoordinateSystem.hpp> +#include <com/sun/star/chart2/XCoordinateSystemContainer.hpp> +#include <com/sun/star/chart2/XDiagram.hpp> +#include <com/sun/star/chart2/XChartTypeContainer.hpp> +#include <com/sun/star/chart2/XChartType.hpp> +#include <tools/globname.hxx> +#include <comphelper/classids.hxx> +#include <com/sun/star/util/CloseVetoException.hpp> +#include <com/sun/star/util/XModifyListener.hpp> +#include <com/sun/star/util/XModifiable.hpp> +#include <com/sun/star/embed/Aspects.hpp> +#include <com/sun/star/embed/EmbedStates.hpp> +#include <com/sun/star/embed/NoVisualAreaSizeException.hpp> +#include <com/sun/star/embed/XEmbeddedObject.hpp> +#include <com/sun/star/embed/XStateChangeListener.hpp> +#include <com/sun/star/embed/XLinkageSupport.hpp> +#include <com/sun/star/chart2/XDefaultSizeTransmitter.hpp> +#include <cppuhelper/implbase.hxx> +#include <vcl/svapp.hxx> +#include <tools/diagnose_ex.h> +#include <tools/debug.hxx> +#include <memory> + +using namespace com::sun::star; + +namespace svt { + +namespace { + +class EmbedEventListener_Impl : public ::cppu::WeakImplHelper < embed::XStateChangeListener, + document::XEventListener, + util::XModifyListener, + util::XCloseListener > +{ +public: + EmbeddedObjectRef* pObject; + sal_Int32 nState; + + explicit EmbedEventListener_Impl( EmbeddedObjectRef* p ) : + pObject(p) + , nState(-1) + {} + + static rtl::Reference<EmbedEventListener_Impl> Create( EmbeddedObjectRef* ); + + virtual void SAL_CALL changingState( const lang::EventObject& aEvent, ::sal_Int32 nOldState, ::sal_Int32 nNewState ) override; + virtual void SAL_CALL stateChanged( const lang::EventObject& aEvent, ::sal_Int32 nOldState, ::sal_Int32 nNewState ) override; + virtual void SAL_CALL queryClosing( const lang::EventObject& Source, sal_Bool GetsOwnership ) override; + virtual void SAL_CALL notifyClosing( const lang::EventObject& Source ) override; + virtual void SAL_CALL notifyEvent( const document::EventObject& aEvent ) override; + virtual void SAL_CALL disposing( const lang::EventObject& aEvent ) override; + virtual void SAL_CALL modified( const css::lang::EventObject& aEvent ) override; +}; + +} + +rtl::Reference<EmbedEventListener_Impl> EmbedEventListener_Impl::Create( EmbeddedObjectRef* p ) +{ + rtl::Reference<EmbedEventListener_Impl> pRet(new EmbedEventListener_Impl( p )); + + if ( p->GetObject().is() ) + { + p->GetObject()->addStateChangeListener( pRet.get() ); + + uno::Reference < util::XCloseable > xClose = p->GetObject(); + DBG_ASSERT( xClose.is(), "Object does not support XCloseable!" ); + if ( xClose.is() ) + xClose->addCloseListener( pRet.get() ); + + uno::Reference < document::XEventBroadcaster > xBrd = p->GetObject(); + if ( xBrd.is() ) + xBrd->addEventListener( pRet.get() ); + + pRet->nState = p->GetObject()->getCurrentState(); + if ( pRet->nState == embed::EmbedStates::RUNNING ) + { + uno::Reference < util::XModifiable > xMod( p->GetObject()->getComponent(), uno::UNO_QUERY ); + if ( xMod.is() ) + // listen for changes in running state (update replacements in case of changes) + xMod->addModifyListener( pRet.get() ); + } + } + + return pRet; +} + +void SAL_CALL EmbedEventListener_Impl::changingState( const lang::EventObject&, + ::sal_Int32, + ::sal_Int32 ) +{ +} + +void SAL_CALL EmbedEventListener_Impl::stateChanged( const lang::EventObject&, + ::sal_Int32 nOldState, + ::sal_Int32 nNewState ) +{ + SolarMutexGuard aGuard; + nState = nNewState; + if ( !pObject ) + return; + + uno::Reference < util::XModifiable > xMod( pObject->GetObject()->getComponent(), uno::UNO_QUERY ); + if ( nNewState == embed::EmbedStates::RUNNING ) + { + // TODO/LATER: container must be set before! + // When is this event created? Who sets the new container when it changed? + if( ( pObject->GetViewAspect() != embed::Aspects::MSOLE_ICON ) && nOldState != embed::EmbedStates::LOADED && !pObject->IsChart() ) + // get new replacement after deactivation + pObject->UpdateReplacement(); + + if( pObject->IsChart() && nOldState == embed::EmbedStates::UI_ACTIVE ) + { + //create a new metafile replacement when leaving the edit mode + //for buggy documents where the old image looks different from the correct one + if( xMod.is() && !xMod->isModified() )//in case of modification a new replacement will be requested anyhow + pObject->UpdateReplacementOnDemand(); + } + + if ( xMod.is() && nOldState == embed::EmbedStates::LOADED ) + // listen for changes (update replacements in case of changes) + xMod->addModifyListener( this ); + } + else if ( nNewState == embed::EmbedStates::LOADED ) + { + // in loaded state we can't listen + if ( xMod.is() ) + xMod->removeModifyListener( this ); + } +} + +void SAL_CALL EmbedEventListener_Impl::modified( const lang::EventObject& ) +{ + SolarMutexGuard aGuard; + if ( !(pObject && pObject->GetViewAspect() != embed::Aspects::MSOLE_ICON) ) + return; + + if ( nState == embed::EmbedStates::RUNNING ) + { + // updates only necessary in non-active states + if( pObject->IsChart() ) + pObject->UpdateReplacementOnDemand(); + else + pObject->UpdateReplacement(); + } + else if ( nState == embed::EmbedStates::ACTIVE || + nState == embed::EmbedStates::UI_ACTIVE || + nState == embed::EmbedStates::INPLACE_ACTIVE ) + { + // in case the object is inplace or UI active the replacement image should be updated on demand + pObject->UpdateReplacementOnDemand(); + } +} + +void SAL_CALL EmbedEventListener_Impl::notifyEvent( const document::EventObject& aEvent ) +{ + SolarMutexGuard aGuard; + + if ( pObject && aEvent.EventName == "OnVisAreaChanged" && pObject->GetViewAspect() != embed::Aspects::MSOLE_ICON && !pObject->IsChart() ) + { + pObject->UpdateReplacement(); + } +} + +void SAL_CALL EmbedEventListener_Impl::queryClosing( const lang::EventObject& Source, sal_Bool ) +{ + // An embedded object can be shared between several objects (f.e. for undo purposes) + // the object will not be closed before the last "customer" is destroyed + // Now the EmbeddedObjectRef helper class works like a "lock" on the object + if ( pObject && pObject->IsLocked() && Source.Source == pObject->GetObject() ) + throw util::CloseVetoException(); +} + +void SAL_CALL EmbedEventListener_Impl::notifyClosing( const lang::EventObject& Source ) +{ + if ( pObject && Source.Source == pObject->GetObject() ) + { + pObject->Clear(); + pObject = nullptr; + } +} + +void SAL_CALL EmbedEventListener_Impl::disposing( const lang::EventObject& aEvent ) +{ + if ( pObject && aEvent.Source == pObject->GetObject() ) + { + pObject->Clear(); + pObject = nullptr; + } +} + +struct EmbeddedObjectRef_Impl +{ + uno::Reference <embed::XEmbeddedObject> mxObj; + + rtl::Reference<EmbedEventListener_Impl> mxListener; + OUString aPersistName; + OUString aMediaType; + comphelper::EmbeddedObjectContainer* pContainer; + std::unique_ptr<Graphic> pGraphic; + sal_Int64 nViewAspect; + bool bIsLocked:1; + bool bNeedUpdate:1; + bool bUpdating:1; + + // #i104867# + sal_uInt32 mnGraphicVersion; + awt::Size aDefaultSizeForChart_In_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 member + + EmbeddedObjectRef_Impl() : + pContainer(nullptr), + nViewAspect(embed::Aspects::MSOLE_CONTENT), + bIsLocked(false), + bNeedUpdate(false), + bUpdating(false), + mnGraphicVersion(0), + aDefaultSizeForChart_In_100TH_MM(awt::Size(8000,7000)) + {} + + EmbeddedObjectRef_Impl( const EmbeddedObjectRef_Impl& r ) : + mxObj(r.mxObj), + aPersistName(r.aPersistName), + aMediaType(r.aMediaType), + pContainer(r.pContainer), + nViewAspect(r.nViewAspect), + bIsLocked(r.bIsLocked), + bNeedUpdate(r.bNeedUpdate), + bUpdating(r.bUpdating), + mnGraphicVersion(0), + aDefaultSizeForChart_In_100TH_MM(r.aDefaultSizeForChart_In_100TH_MM) + { + if (r.pGraphic && !r.bNeedUpdate) + pGraphic.reset( new Graphic(*r.pGraphic) ); + } +}; + +const uno::Reference <embed::XEmbeddedObject>& EmbeddedObjectRef::operator->() const +{ + return mpImpl->mxObj; +} + +const uno::Reference <embed::XEmbeddedObject>& EmbeddedObjectRef::GetObject() const +{ + return mpImpl->mxObj; +} + +EmbeddedObjectRef::EmbeddedObjectRef() : mpImpl(new EmbeddedObjectRef_Impl) {} + +EmbeddedObjectRef::EmbeddedObjectRef( const uno::Reference < embed::XEmbeddedObject >& xObj, sal_Int64 nAspect ) : + mpImpl(new EmbeddedObjectRef_Impl) +{ + mpImpl->nViewAspect = nAspect; + mpImpl->mxObj = xObj; + mpImpl->mxListener = EmbedEventListener_Impl::Create( this ); +} + +EmbeddedObjectRef::EmbeddedObjectRef( const EmbeddedObjectRef& rObj ) : + mpImpl(new EmbeddedObjectRef_Impl(*rObj.mpImpl)) +{ + mpImpl->mxListener = EmbedEventListener_Impl::Create( this ); +} + +EmbeddedObjectRef::~EmbeddedObjectRef() +{ + Clear(); +} + +void EmbeddedObjectRef::Assign( const uno::Reference < embed::XEmbeddedObject >& xObj, sal_Int64 nAspect ) +{ + DBG_ASSERT(!mpImpl->mxObj.is(), "Never assign an already assigned object!"); + + Clear(); + mpImpl->nViewAspect = nAspect; + mpImpl->mxObj = xObj; + mpImpl->mxListener = EmbedEventListener_Impl::Create( this ); + + //#i103460# + if ( IsChart() ) + { + uno::Reference < chart2::XDefaultSizeTransmitter > xSizeTransmitter( xObj, uno::UNO_QUERY ); + DBG_ASSERT( xSizeTransmitter.is(), "Object does not support XDefaultSizeTransmitter -> will cause #i103460#!" ); + if( xSizeTransmitter.is() ) + xSizeTransmitter->setDefaultSize( mpImpl->aDefaultSizeForChart_In_100TH_MM ); + } +} + +void EmbeddedObjectRef::Clear() +{ + if (mpImpl->mxObj.is() && mpImpl->mxListener.is()) + { + mpImpl->mxObj->removeStateChangeListener(mpImpl->mxListener.get()); + + mpImpl->mxObj->removeCloseListener( mpImpl->mxListener.get() ); + mpImpl->mxObj->removeEventListener( mpImpl->mxListener.get() ); + + if ( mpImpl->bIsLocked ) + { + try + { + mpImpl->mxObj->changeState(embed::EmbedStates::LOADED); + mpImpl->mxObj->close( true ); + } + catch (const util::CloseVetoException&) + { + // there's still someone who needs the object! + } + catch (const uno::Exception&) + { + TOOLS_WARN_EXCEPTION("svtools.misc", "Error on switching of the object to loaded state and closing"); + } + } + } + + if (mpImpl->mxListener.is()) + { + mpImpl->mxListener->pObject = nullptr; + mpImpl->mxListener.clear(); + } + + mpImpl->mxObj = nullptr; + mpImpl->pContainer = nullptr; + mpImpl->bIsLocked = false; + mpImpl->bNeedUpdate = false; +} + +bool EmbeddedObjectRef::is() const +{ + return mpImpl->mxObj.is(); +} + +void EmbeddedObjectRef::AssignToContainer( comphelper::EmbeddedObjectContainer* pContainer, const OUString& rPersistName ) +{ + mpImpl->pContainer = pContainer; + mpImpl->aPersistName = rPersistName; + + if ( mpImpl->pGraphic && !mpImpl->bNeedUpdate && pContainer ) + SetGraphicToContainer( *mpImpl->pGraphic, *pContainer, mpImpl->aPersistName, OUString() ); +} + +comphelper::EmbeddedObjectContainer* EmbeddedObjectRef::GetContainer() const +{ + return mpImpl->pContainer; +} + +sal_Int64 EmbeddedObjectRef::GetViewAspect() const +{ + return mpImpl->nViewAspect; +} + +void EmbeddedObjectRef::SetViewAspect( sal_Int64 nAspect ) +{ + mpImpl->nViewAspect = nAspect; +} + +void EmbeddedObjectRef::Lock( bool bLock ) +{ + mpImpl->bIsLocked = bLock; +} + +bool EmbeddedObjectRef::IsLocked() const +{ + return mpImpl->bIsLocked; +} + +void EmbeddedObjectRef::GetReplacement( bool bUpdate ) +{ + Graphic aOldGraphic; + + if ( bUpdate ) + { + if (mpImpl->pGraphic) + aOldGraphic = *mpImpl->pGraphic; + + mpImpl->pGraphic.reset(); + mpImpl->aMediaType.clear(); + mpImpl->pGraphic.reset( new Graphic ); + mpImpl->mnGraphicVersion++; + } + else if ( !mpImpl->pGraphic ) + { + mpImpl->pGraphic.reset( new Graphic ); + mpImpl->mnGraphicVersion++; + } + else + { + OSL_FAIL("No update, but replacement exists already!"); + return; + } + + std::unique_ptr<SvStream> pGraphicStream(GetGraphicStream( bUpdate )); + if ( pGraphicStream ) + { + GraphicFilter& rGF = GraphicFilter::GetGraphicFilter(); + if( mpImpl->pGraphic ) + rGF.ImportGraphic( *mpImpl->pGraphic, OUString(), *pGraphicStream ); + mpImpl->mnGraphicVersion++; + } + + // note that UpdateReplacementOnDemand which resets mpImpl->pGraphic to null may have been called + // e.g. when exporting ooo58458-1.odt to doc + if (bUpdate && (!mpImpl->pGraphic || mpImpl->pGraphic->IsNone()) && !aOldGraphic.IsNone()) + { + // We used to have an old graphic, tried to update and the update + // failed. Go back to the old graphic instead of having no graphic at + // all. + mpImpl->pGraphic.reset(new Graphic(aOldGraphic)); + SAL_WARN("svtools.misc", "EmbeddedObjectRef::GetReplacement: update failed"); + } +} + +const Graphic* EmbeddedObjectRef::GetGraphic() const +{ + try + { + if ( mpImpl->bNeedUpdate ) + // bNeedUpdate will be set to false while retrieving new replacement + const_cast < EmbeddedObjectRef* >(this)->GetReplacement(true); + else if ( !mpImpl->pGraphic ) + const_cast < EmbeddedObjectRef* >(this)->GetReplacement(false); + } + catch( const uno::Exception& ) + { + DBG_UNHANDLED_EXCEPTION("svtools.misc", "Something went wrong on getting the graphic"); + } + + return mpImpl->pGraphic.get(); +} + +Size EmbeddedObjectRef::GetSize( MapMode const * pTargetMapMode ) const +{ + MapMode aSourceMapMode( MapUnit::Map100thMM ); + Size aResult; + + if ( mpImpl->nViewAspect == embed::Aspects::MSOLE_ICON ) + { + const Graphic* pGraphic = GetGraphic(); + if ( pGraphic ) + { + aSourceMapMode = pGraphic->GetPrefMapMode(); + aResult = pGraphic->GetPrefSize(); + } + else + aResult = Size( 2500, 2500 ); + } + else + { + awt::Size aSize; + + if (mpImpl->mxObj.is()) + { + try + { + aSize = mpImpl->mxObj->getVisualAreaSize(mpImpl->nViewAspect); + } + catch(const embed::NoVisualAreaSizeException&) + { + } + catch (const uno::Exception&) + { + TOOLS_WARN_EXCEPTION("svtools.misc", "Something went wrong on getting of the size of the object"); + } + + try + { + aSourceMapMode = MapMode(VCLUnoHelper::UnoEmbed2VCLMapUnit(mpImpl->mxObj->getMapUnit(mpImpl->nViewAspect))); + } + catch (const uno::Exception&) + { + TOOLS_WARN_EXCEPTION("svtools.misc", "Can not get the map mode"); + } + } + + if ( !aSize.Height && !aSize.Width ) + { + aSize.Width = 5000; + aSize.Height = 5000; + } + + aResult = Size( aSize.Width, aSize.Height ); + } + + if ( pTargetMapMode ) + aResult = OutputDevice::LogicToLogic( aResult, aSourceMapMode, *pTargetMapMode ); + + return aResult; +} + +void EmbeddedObjectRef::SetGraphicStream( const uno::Reference< io::XInputStream >& xInGrStream, + const OUString& rMediaType ) +{ + mpImpl->pGraphic.reset( new Graphic ); + mpImpl->aMediaType = rMediaType; + mpImpl->mnGraphicVersion++; + + std::unique_ptr<SvStream> pGraphicStream(::utl::UcbStreamHelper::CreateStream( xInGrStream )); + + if ( pGraphicStream ) + { + GraphicFilter& rGF = GraphicFilter::GetGraphicFilter(); + rGF.ImportGraphic( *mpImpl->pGraphic, "", *pGraphicStream ); + mpImpl->mnGraphicVersion++; + + if ( mpImpl->pContainer ) + { + pGraphicStream->Seek( 0 ); + uno::Reference< io::XInputStream > xInSeekGrStream = new ::utl::OSeekableInputStreamWrapper( pGraphicStream.get() ); + + mpImpl->pContainer->InsertGraphicStream( xInSeekGrStream, mpImpl->aPersistName, rMediaType ); + } + } + + mpImpl->bNeedUpdate = false; + +} + +void EmbeddedObjectRef::SetGraphic( const Graphic& rGraphic, const OUString& rMediaType ) +{ + mpImpl->pGraphic.reset( new Graphic( rGraphic ) ); + mpImpl->aMediaType = rMediaType; + mpImpl->mnGraphicVersion++; + + if ( mpImpl->pContainer ) + SetGraphicToContainer( rGraphic, *mpImpl->pContainer, mpImpl->aPersistName, rMediaType ); + + mpImpl->bNeedUpdate = false; +} + +std::unique_ptr<SvStream> EmbeddedObjectRef::GetGraphicStream( bool bUpdate ) const +{ + DBG_ASSERT( bUpdate || mpImpl->pContainer, "Can't retrieve current graphic!" ); + uno::Reference < io::XInputStream > xStream; + if ( mpImpl->pContainer && !bUpdate ) + { + SAL_INFO( "svtools.misc", "getting stream from container" ); + // try to get graphic stream from container storage + xStream = mpImpl->pContainer->GetGraphicStream(mpImpl->mxObj, &mpImpl->aMediaType); + if ( xStream.is() ) + { + const sal_Int32 nConstBufferSize = 32000; + std::unique_ptr<SvStream> pStream(new SvMemoryStream( 32000, 32000 )); + try + { + sal_Int32 nRead=0; + uno::Sequence < sal_Int8 > aSequence ( nConstBufferSize ); + do + { + nRead = xStream->readBytes ( aSequence, nConstBufferSize ); + pStream->WriteBytes(aSequence.getConstArray(), nRead); + } + while ( nRead == nConstBufferSize ); + pStream->Seek(0); + return pStream; + } + catch (const uno::Exception&) + { + DBG_UNHANDLED_EXCEPTION("svtools.misc", "discarding broken embedded object preview"); + xStream.clear(); + } + } + } + + if ( !xStream.is() ) + { + SAL_INFO( "svtools.misc", "getting stream from object" ); + bool bUpdateAllowed(true); + const comphelper::EmbeddedObjectContainer* pContainer = GetContainer(); + + if(pContainer) + { + uno::Reference<embed::XLinkageSupport> const xLinkage( + mpImpl->mxObj, uno::UNO_QUERY); + if (xLinkage.is() && xLinkage->isLink()) + { + bUpdateAllowed = pContainer->getUserAllowsLinkUpdate(); + + } + } + + if (bUpdateAllowed) + { + // update wanted or no stream in container storage available + xStream = GetGraphicReplacementStream(mpImpl->nViewAspect, mpImpl->mxObj, &mpImpl->aMediaType); + + if(xStream.is()) + { + if (mpImpl->pContainer) + mpImpl->pContainer->InsertGraphicStream(xStream,mpImpl->aPersistName,mpImpl->aMediaType); + + std::unique_ptr<SvStream> pResult = ::utl::UcbStreamHelper::CreateStream( xStream ); + if (pResult && bUpdate) + mpImpl->bNeedUpdate = false; + + return pResult; + } + } + } + + return nullptr; +} + +void EmbeddedObjectRef::DrawPaintReplacement( const tools::Rectangle &rRect, const OUString &rText, OutputDevice *pOut ) +{ + MapMode aMM( MapUnit::MapAppFont ); + Size aAppFontSz = pOut->LogicToLogic( Size( 0, 8 ), &aMM, nullptr ); + vcl::Font aFnt( "Helvetica", aAppFontSz ); + aFnt.SetTransparent( true ); + aFnt.SetColor( COL_LIGHTRED ); + aFnt.SetWeight( WEIGHT_BOLD ); + aFnt.SetFamily( FAMILY_SWISS ); + + pOut->Push(); + pOut->SetBackground(); + pOut->SetFont( aFnt ); + + Point aPt; + + // Now scale text such that it fits in the rectangle + // We start with the default size and decrease 1-AppFont + for( sal_uInt16 i = 8; i > 2; i-- ) + { + aPt.setX( (rRect.GetWidth() - pOut->GetTextWidth( rText )) / 2 ); + aPt.setY( (rRect.GetHeight() - pOut->GetTextHeight()) / 2 ); + + bool bTiny = false; + if( aPt.X() < 0 ) + { + bTiny = true; + aPt.setX( 0 ); + } + if( aPt.Y() < 0 ) + { + bTiny = true; + aPt.setY( 0 ); + } + if( bTiny ) + { + // decrease for small images + aFnt.SetFontSize( Size( 0, aAppFontSz.Height() * i / 8 ) ); + pOut->SetFont( aFnt ); + } + else + break; + } + + BitmapEx aBmp(BMP_PLUGIN); + long nHeight = rRect.GetHeight() - pOut->GetTextHeight(); + long nWidth = rRect.GetWidth(); + if(nHeight > 0 && nWidth > 0 && aBmp.GetSizePixel().Width() > 0) + { + aPt.setY( nHeight ); + Point aP = rRect.TopLeft(); + Size aBmpSize = aBmp.GetSizePixel(); + // fit bitmap in + if( nHeight * 10 / nWidth + > aBmpSize.Height() * 10 / aBmpSize.Width() ) + { + // adjust to the width + // keep proportions + long nH = nWidth * aBmpSize.Height() / aBmpSize.Width(); + // center + aP.AdjustY((nHeight - nH) / 2 ); + nHeight = nH; + } + else + { + // adjust to the height + // keep proportions + long nW = nHeight * aBmpSize.Width() / aBmpSize.Height(); + // center + aP.AdjustX((nWidth - nW) / 2 ); + nWidth = nW; + } + + pOut->DrawBitmapEx(aP, Size( nWidth, nHeight ), aBmp); + } + + pOut->IntersectClipRegion( rRect ); + aPt += rRect.TopLeft(); + pOut->DrawText( aPt, rText ); + pOut->Pop(); +} + +void EmbeddedObjectRef::DrawShading( const tools::Rectangle &rRect, OutputDevice *pOut ) +{ + GDIMetaFile * pMtf = pOut->GetConnectMetaFile(); + if( pMtf && pMtf->IsRecord() ) + return; + + pOut->Push(); + pOut->SetLineColor( COL_BLACK ); + + Size aPixSize = pOut->LogicToPixel( rRect.GetSize() ); + aPixSize.AdjustWidth( -1 ); + aPixSize.AdjustHeight( -1 ); + Point aPixViewPos = pOut->LogicToPixel( rRect.TopLeft() ); + sal_Int32 nMax = aPixSize.Width() + aPixSize.Height(); + for( sal_Int32 i = 5; i < nMax; i += 5 ) + { + Point a1( aPixViewPos ), a2( aPixViewPos ); + if( i > aPixSize.Width() ) + a1 += Point( aPixSize.Width(), i - aPixSize.Width() ); + else + a1 += Point( i, 0 ); + if( i > aPixSize.Height() ) + a2 += Point( i - aPixSize.Height(), aPixSize.Height() ); + else + a2 += Point( 0, i ); + + pOut->DrawLine( pOut->PixelToLogic( a1 ), pOut->PixelToLogic( a2 ) ); + } + + pOut->Pop(); + +} + +bool EmbeddedObjectRef::TryRunningState( const uno::Reference < embed::XEmbeddedObject >& xEmbObj ) +{ + if ( !xEmbObj.is() ) + return false; + + try + { + if ( xEmbObj->getCurrentState() == embed::EmbedStates::LOADED ) + xEmbObj->changeState( embed::EmbedStates::RUNNING ); + } + catch (const uno::Exception&) + { + return false; + } + + return true; +} + +void EmbeddedObjectRef::SetGraphicToContainer( const Graphic& rGraphic, + comphelper::EmbeddedObjectContainer& aContainer, + const OUString& aName, + const OUString& aMediaType ) +{ + SvMemoryStream aStream; + aStream.SetVersion( SOFFICE_FILEFORMAT_CURRENT ); + if ( rGraphic.ExportNative( aStream ) ) + { + aStream.Seek( 0 ); + + uno::Reference < io::XInputStream > xStream = new ::utl::OSeekableInputStreamWrapper( aStream ); + aContainer.InsertGraphicStream( xStream, aName, aMediaType ); + } + else + OSL_FAIL( "Export of graphic is failed!" ); +} + +uno::Reference< io::XInputStream > EmbeddedObjectRef::GetGraphicReplacementStream( + sal_Int64 nViewAspect, + const uno::Reference< embed::XEmbeddedObject >& xObj, + OUString* pMediaType ) + throw() +{ + return ::comphelper::EmbeddedObjectContainer::GetGraphicReplacementStream(nViewAspect,xObj,pMediaType); +} + +bool EmbeddedObjectRef::IsChart(const css::uno::Reference < css::embed::XEmbeddedObject >& xObj) +{ + SvGlobalName aObjClsId(xObj->getClassID()); + return SvGlobalName(SO3_SCH_CLASSID_30) == aObjClsId + || SvGlobalName(SO3_SCH_CLASSID_40) == aObjClsId + || SvGlobalName(SO3_SCH_CLASSID_50) == aObjClsId + || SvGlobalName(SO3_SCH_CLASSID_60) == aObjClsId; +} + +void EmbeddedObjectRef::UpdateReplacement() +{ + if (mpImpl->bUpdating) + { + SAL_WARN("svtools.misc", "UpdateReplacement called while UpdateReplacement already underway"); + return; + } + mpImpl->bUpdating = true; + GetReplacement(true); + mpImpl->bUpdating = false; +} + +void EmbeddedObjectRef::UpdateReplacementOnDemand() +{ + mpImpl->pGraphic.reset(); + mpImpl->bNeedUpdate = true; + mpImpl->mnGraphicVersion++; + + if( mpImpl->pContainer ) + { + //remove graphic from container thus a new up to date one is requested on save + mpImpl->pContainer->RemoveGraphicStream( mpImpl->aPersistName ); + } +} + +bool EmbeddedObjectRef::IsChart() const +{ + //todo maybe for 3.0: + //if the changes work good for chart + //we should apply them for all own ole objects + + //#i83708# #i81857# #i79578# request an ole replacement image only if really necessary + //as this call can be very expensive and does block the user interface as long at it takes + + if (!mpImpl->mxObj.is()) + return false; + + return EmbeddedObjectRef::IsChart(mpImpl->mxObj); +} + +// MT: Only used for getting accessible attributes, which are not localized +OUString EmbeddedObjectRef::GetChartType() +{ + OUString Style; + if ( mpImpl->mxObj.is() ) + { + if ( IsChart() ) + { + if ( svt::EmbeddedObjectRef::TryRunningState( mpImpl->mxObj ) ) + { + uno::Reference< chart2::XChartDocument > xChart( mpImpl->mxObj->getComponent(), uno::UNO_QUERY ); + if (xChart.is()) + { + uno::Reference< chart2::XDiagram > xDiagram( xChart->getFirstDiagram()); + if( ! xDiagram.is()) + return OUString(); + uno::Reference< chart2::XCoordinateSystemContainer > xCooSysCnt( xDiagram, uno::UNO_QUERY_THROW ); + const uno::Sequence< uno::Reference< chart2::XCoordinateSystem > > aCooSysSeq( xCooSysCnt->getCoordinateSystems()); + // IA2 CWS. Unused: int nCoordinateCount = aCooSysSeq.getLength(); + bool bGetChartType = false; + for( const auto& rCooSys : aCooSysSeq ) + { + uno::Reference< chart2::XChartTypeContainer > xCTCnt( rCooSys, uno::UNO_QUERY_THROW ); + const uno::Sequence< uno::Reference< chart2::XChartType > > aChartTypes( xCTCnt->getChartTypes()); + int nDimesionCount = rCooSys->getDimension(); + if( nDimesionCount == 3 ) + Style += "3D "; + else + Style += "2D "; + for( const auto& rChartType : aChartTypes ) + { + OUString strChartType = rChartType->getChartType(); + if (strChartType == "com.sun.star.chart2.AreaChartType") + { + Style += "Areas"; + bGetChartType = true; + } + else if (strChartType == "com.sun.star.chart2.BarChartType") + { + Style += "Bars"; + bGetChartType = true; + } + else if (strChartType == "com.sun.star.chart2.ColumnChartType") + { + uno::Reference< beans::XPropertySet > xProp( rCooSys, uno::UNO_QUERY ); + if( xProp.is()) + { + bool bCurrent = false; + if( xProp->getPropertyValue( "SwapXAndYAxis" ) >>= bCurrent ) + { + if (bCurrent) + Style += "Bars"; + else + Style += "Columns"; + bGetChartType = true; + } + } + } + else if (strChartType == "com.sun.star.chart2.LineChartType") + { + Style += "Lines"; + bGetChartType = true; + } + else if (strChartType == "com.sun.star.chart2.ScatterChartType") + { + Style += "XY Chart"; + bGetChartType = true; + } + else if (strChartType == "com.sun.star.chart2.PieChartType") + { + Style += "Pies"; + bGetChartType = true; + } + else if (strChartType == "com.sun.star.chart2.NetChartType") + { + Style += "Radar"; + bGetChartType = true; + } + else if (strChartType == "com.sun.star.chart2.CandleStickChartType") + { + Style += "Candle Stick Chart"; + bGetChartType = true; + } + if (bGetChartType) + return Style; + } + } + } + } + } + } + return Style; +} + +// #i104867# +sal_uInt32 EmbeddedObjectRef::getGraphicVersion() const +{ + return mpImpl->mnGraphicVersion; +} + +void EmbeddedObjectRef::SetDefaultSizeForChart( const Size& rSizeIn_100TH_MM ) +{ + //#i103460# charts do not necessarily have an own size within ODF files, + //for this case they need to use the size settings from the surrounding frame, + //which is made available with this method + + mpImpl->aDefaultSizeForChart_In_100TH_MM = awt::Size( rSizeIn_100TH_MM.getWidth(), rSizeIn_100TH_MM.getHeight() ); + + uno::Reference<chart2::XDefaultSizeTransmitter> xSizeTransmitter(mpImpl->mxObj, uno::UNO_QUERY); + DBG_ASSERT( xSizeTransmitter.is(), "Object does not support XDefaultSizeTransmitter -> will cause #i103460#!" ); + if( xSizeTransmitter.is() ) + xSizeTransmitter->setDefaultSize( mpImpl->aDefaultSizeForChart_In_100TH_MM ); +} + +} // namespace svt + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/misc/embedtransfer.cxx b/svtools/source/misc/embedtransfer.cxx new file mode 100644 index 000000000..ac18b8cde --- /dev/null +++ b/svtools/source/misc/embedtransfer.cxx @@ -0,0 +1,248 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <com/sun/star/embed/XEmbeddedObject.hpp> +#include <com/sun/star/embed/XEmbedPersist.hpp> +#include <com/sun/star/embed/NoVisualAreaSizeException.hpp> +#include <com/sun/star/datatransfer/XTransferable.hpp> +#include <com/sun/star/embed/Aspects.hpp> +#include <osl/diagnose.h> +#include <sot/exchange.hxx> +#include <svtools/embedtransfer.hxx> +#include <tools/mapunit.hxx> +#include <vcl/outdev.hxx> +#include <vcl/gdimtf.hxx> +#include <comphelper/fileformat.h> +#include <comphelper/propertysequence.hxx> +#include <comphelper/storagehelper.hxx> +#include <unotools/ucbstreamhelper.hxx> +#include <unotools/streamwrap.hxx> +#include <unotools/tempfile.hxx> +#include <toolkit/helper/vclunohelper.hxx> + +#include <svtools/embedhlp.hxx> + +using namespace ::com::sun::star; + +SvEmbedTransferHelper::SvEmbedTransferHelper( const uno::Reference< embed::XEmbeddedObject >& xObj, + const Graphic* pGraphic, + sal_Int64 nAspect ) +: m_xObj( xObj ) +, m_pGraphic( pGraphic ? new Graphic( *pGraphic ) : nullptr ) +, m_nAspect( nAspect ) +{ + if( xObj.is() ) + { + TransferableObjectDescriptor aObjDesc; + + FillTransferableObjectDescriptor( aObjDesc, m_xObj, nullptr, m_nAspect ); + PrepareOLE( aObjDesc ); + } +} + + +SvEmbedTransferHelper::~SvEmbedTransferHelper() +{ +} + +void SvEmbedTransferHelper::SetParentShellID( const OUString& rShellID ) +{ + maParentShellID = rShellID; +} + + +void SvEmbedTransferHelper::AddSupportedFormats() +{ + AddFormat( SotClipboardFormatId::EMBED_SOURCE ); + AddFormat( SotClipboardFormatId::OBJECTDESCRIPTOR ); + AddFormat( SotClipboardFormatId::GDIMETAFILE ); + AddFormat( SotClipboardFormatId::BITMAP ); +} + + +bool SvEmbedTransferHelper::GetData( const css::datatransfer::DataFlavor& rFlavor, const OUString& rDestDoc ) +{ + bool bRet = false; + + if( m_xObj.is() ) + { + try + { + SotClipboardFormatId nFormat = SotExchange::GetFormat( rFlavor ); + if( HasFormat( nFormat ) ) + { + if( nFormat == SotClipboardFormatId::OBJECTDESCRIPTOR ) + { + TransferableObjectDescriptor aDesc; + FillTransferableObjectDescriptor( aDesc, m_xObj, m_pGraphic.get(), m_nAspect ); + bRet = SetTransferableObjectDescriptor( aDesc ); + } + else if( nFormat == SotClipboardFormatId::EMBED_SOURCE ) + { + try + { + // TODO/LATER: Probably the graphic should be copied here as well + // currently it is handled by the applications + utl::TempFile aTmp; + aTmp.EnableKillingFile(); + uno::Reference < embed::XEmbedPersist > xPers( m_xObj, uno::UNO_QUERY ); + if ( xPers.is() ) + { + uno::Reference < embed::XStorage > xStg = comphelper::OStorageHelper::GetTemporaryStorage(); + OUString aName( "Dummy" ); + SvStream* pStream = nullptr; + bool bDeleteStream = false; + uno::Sequence < beans::PropertyValue > aEmpty; + uno::Sequence<beans::PropertyValue> aObjArgs( comphelper::InitPropertySequence({ + { "SourceShellID", uno::Any(maParentShellID) }, + { "DestinationShellID", uno::Any(rDestDoc) } + })); + xPers->storeToEntry(xStg, aName, aEmpty, aObjArgs); + if ( xStg->isStreamElement( aName ) ) + { + uno::Reference < io::XStream > xStm = xStg->cloneStreamElement( aName ); + pStream = utl::UcbStreamHelper::CreateStream( xStm ).release(); + bDeleteStream = true; + } + else + { + pStream = aTmp.GetStream( StreamMode::STD_READWRITE ); + uno::Reference < embed::XStorage > xStor = comphelper::OStorageHelper::GetStorageFromStream( new utl::OStreamWrapper( *pStream ) ); + xStg->openStorageElement( aName, embed::ElementModes::READ )->copyToStorage( xStor ); + } + + const sal_uInt32 nLen = pStream->TellEnd(); + css::uno::Sequence< sal_Int8 > aSeq( nLen ); + + pStream->Seek( STREAM_SEEK_TO_BEGIN ); + pStream->ReadBytes(aSeq.getArray(), nLen); + if ( bDeleteStream ) + delete pStream; + + bRet = aSeq.hasElements(); + if( bRet ) + { + SetAny( uno::Any(aSeq) ); + } + } + else + { + //TODO/LATER: how to handle objects without persistence?! + } + } + catch ( uno::Exception& ) + { + } + } + else if ( nFormat == SotClipboardFormatId::GDIMETAFILE && m_pGraphic ) + { + SvMemoryStream aMemStm( 65535, 65535 ); + aMemStm.SetVersion( SOFFICE_FILEFORMAT_CURRENT ); + + const GDIMetaFile& aMetaFile = m_pGraphic->GetGDIMetaFile(); + const_cast<GDIMetaFile*>(&aMetaFile)->Write( aMemStm ); + uno::Any aAny; + aAny <<= uno::Sequence< sal_Int8 >( static_cast< const sal_Int8* >( aMemStm.GetData() ), + aMemStm.TellEnd() ); + SetAny( aAny ); + bRet = true; + } + else if ( ( nFormat == SotClipboardFormatId::BITMAP || nFormat == SotClipboardFormatId::PNG ) && m_pGraphic ) + { + bRet = SetBitmapEx( m_pGraphic->GetBitmapEx(), rFlavor ); + } + else if ( m_xObj.is() && ::svt::EmbeddedObjectRef::TryRunningState( m_xObj ) ) + { + uno::Reference< datatransfer::XTransferable > xTransferable( m_xObj->getComponent(), uno::UNO_QUERY ); + if ( xTransferable.is() ) + { + uno::Any aAny = xTransferable->getTransferData( rFlavor ); + SetAny( aAny ); + bRet = true; + } + } + } + } + catch( uno::Exception& ) + { + // Error handling? + } + } + + return bRet; +} + + +void SvEmbedTransferHelper::ObjectReleased() +{ + m_xObj.clear(); +} + +void SvEmbedTransferHelper::FillTransferableObjectDescriptor( TransferableObjectDescriptor& rDesc, + const css::uno::Reference< css::embed::XEmbeddedObject >& xObj, + const Graphic* pGraphic, + sal_Int64 nAspect ) +{ + //TODO/LATER: need TypeName to fill it into the Descriptor (will be shown in listbox) + css::datatransfer::DataFlavor aFlavor; + SotExchange::GetFormatDataFlavor( SotClipboardFormatId::OBJECTDESCRIPTOR, aFlavor ); + + rDesc.maClassName = SvGlobalName( xObj->getClassID() ); + rDesc.maTypeName = aFlavor.HumanPresentableName; + + //TODO/LATER: the aspect size in the descriptor is wrong, unfortunately the stream + // representation of the descriptor allows only 4 bytes for the aspect + // so for internal transport something different should be found + rDesc.mnViewAspect = sal::static_int_cast<sal_uInt16>( nAspect ); + + Size aSize; + MapMode aMapMode( MapUnit::Map100thMM ); + if ( nAspect == embed::Aspects::MSOLE_ICON ) + { + if ( pGraphic ) + { + aMapMode = pGraphic->GetPrefMapMode(); + aSize = pGraphic->GetPrefSize(); + } + else + aSize = Size( 2500, 2500 ); + } + else + { + try + { + awt::Size aSz = xObj->getVisualAreaSize( rDesc.mnViewAspect ); + aSize = Size( aSz.Width, aSz.Height ); + } + catch( embed::NoVisualAreaSizeException& ) + { + OSL_FAIL( "Can not get visual area size!" ); + aSize = Size( 5000, 5000 ); + } + + // TODO/LEAN: getMapUnit can switch object to running state + aMapMode = MapMode( VCLUnoHelper::UnoEmbed2VCLMapUnit( xObj->getMapUnit( rDesc.mnViewAspect ) ) ); + } + + rDesc.maSize = OutputDevice::LogicToLogic( aSize, aMapMode, MapMode( MapUnit::Map100thMM ) ); + rDesc.maDragStartPos = Point(); + rDesc.maDisplayName.clear(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/misc/filechangedchecker.cxx b/svtools/source/misc/filechangedchecker.cxx new file mode 100644 index 000000000..8536eb0bd --- /dev/null +++ b/svtools/source/misc/filechangedchecker.cxx @@ -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/. + */ + +#include <sal/config.h> +#include <sal/log.hxx> +#include <osl/file.hxx> + +#include <svtools/filechangedchecker.hxx> +#include <vcl/timer.hxx> + +FileChangedChecker::FileChangedChecker(const OUString& rFilename, + const ::std::function<void ()>& rCallback) + : mTimer("SVTools FileChangedChecker Timer") + , mFileName(rFilename) + , mLastModTime() + , mpCallback(rCallback) +{ + // Get the curren last file modified Status + getCurrentModTime(mLastModTime); + + // associate the callback function for the Timer + mTimer.SetInvokeHandler(LINK(this, FileChangedChecker, TimerHandler)); + + // set timer interval + mTimer.SetTimeout(100); + + // start the timer + resetTimer(); +} + +void FileChangedChecker::resetTimer() +{ + // Start the Idle if it's not active + if(!mTimer.IsActive()) + mTimer.Start(); + + // Set lowest Priority + mTimer.SetPriority(TaskPriority::LOWEST); +} + +bool FileChangedChecker::getCurrentModTime(TimeValue& o_rValue) const +{ + // Need a Directory item to fetch file status + osl::DirectoryItem aItem; + if (osl::FileBase::E_None != osl::DirectoryItem::get(mFileName, aItem)) + return false; + + // Retrieve the status - we are only interested in last File + // Modified time + osl::FileStatus aStatus( osl_FileStatus_Mask_ModifyTime ); + if (osl::FileBase::E_None != aItem.getFileStatus(aStatus)) + return false; + + o_rValue = aStatus.getModifyTime(); + return true; +} + +bool FileChangedChecker::hasFileChanged() +{ + // Get the current file Status + TimeValue newTime={0,0}; + if( !getCurrentModTime(newTime) ) + return true; // well. hard to answer correctly here ... + + // Check if the seconds time stamp has any difference + // If so, then our file has changed meanwhile + if( newTime.Seconds != mLastModTime.Seconds || + newTime.Nanosec != mLastModTime.Nanosec ) + { + // Since the file has changed, set the new status as the file status and + // return True + mLastModTime = newTime ; + + return true; + } + else + return false; +} + +IMPL_LINK_NOARG(FileChangedChecker, TimerHandler, Timer *, void) +{ + // If the file has changed, then update the graphic in the doc + SAL_INFO("svtools", "Timeout Called"); + if(hasFileChanged()) + { + SAL_INFO("svtools", "File modified"); + mpCallback(); + } + + // Reset the Timer in any case + resetTimer(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/misc/imagemgr.cxx b/svtools/source/misc/imagemgr.cxx new file mode 100644 index 000000000..2964dec1c --- /dev/null +++ b/svtools/source/misc/imagemgr.cxx @@ -0,0 +1,858 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <svtools/imagemgr.hxx> +#include <tools/diagnose_ex.h> +#include <tools/urlobj.hxx> +#include <tools/debug.hxx> +#include <vcl/image.hxx> +#include <sot/storage.hxx> +#include <comphelper/classids.hxx> +#include <unotools/ucbhelper.hxx> +#include <comphelper/processfactory.hxx> +#include <com/sun/star/beans/PropertyValue.hpp> +#include <com/sun/star/container/XNameAccess.hpp> +#include <com/sun/star/document/XTypeDetection.hpp> +#include <com/sun/star/ucb/ContentCreationException.hpp> +#include <com/sun/star/ucb/XCommandEnvironment.hpp> +#include <com/sun/star/uno/XComponentContext.hpp> +#include <ucbhelper/content.hxx> +#include <svtools/strings.hrc> +#include <svtools/svtresid.hxx> +#include <bitmaps.hlst> +#include <strings.hxx> + +// globals ******************************************************************* + +#define NO_INDEX (-1) +#define CONTENT_HELPER ::utl::UCBContentHelper + +namespace { + +struct SvtExtensionResIdMapping_Impl +{ + const char* _pExt; + bool _bExt; + const char* pStrId; + SvImageId _nImgId; +}; + +} + +static SvtExtensionResIdMapping_Impl const ExtensionMap_Impl[] = +{ + { "awk", true, STR_DESCRIPTION_SOURCEFILE, SvImageId::NONE }, + { "bas", true, STR_DESCRIPTION_SOURCEFILE, SvImageId::NONE }, + { "bat", true, STR_DESCRIPTION_BATCHFILE, SvImageId::NONE }, + { "bmk", false, STR_DESCRIPTION_BOOKMARKFILE, SvImageId::NONE }, + { "bmp", true, STR_DESCRIPTION_GRAPHIC_DOC, SvImageId::Bitmap }, + { "c", true, STR_DESCRIPTION_SOURCEFILE, SvImageId::NONE }, + { "cfg", false, STR_DESCRIPTION_CFGFILE, SvImageId::NONE }, + { "cmd", true, STR_DESCRIPTION_BATCHFILE, SvImageId::NONE }, + { "cob", true, STR_DESCRIPTION_SOURCEFILE, SvImageId::NONE }, + { "com", true, STR_DESCRIPTION_APPLICATION, SvImageId::NONE }, + { "cxx", true, STR_DESCRIPTION_SOURCEFILE, SvImageId::NONE }, + { "dbf", true, STR_DESCRIPTION_DATABASE_TABLE, SvImageId::Table }, + { "def", true, STR_DESCRIPTION_SOURCEFILE, SvImageId::NONE }, + { "dll", true, STR_DESCRIPTION_SYSFILE, SvImageId::NONE }, + { "doc", false, STR_DESCRIPTION_WORD_DOC, SvImageId::Writer }, + { "dot", false, STR_DESCRIPTION_WORD_DOC, SvImageId::WriterTemplate }, + { "docx", false, STR_DESCRIPTION_WORD_DOC, SvImageId::Writer }, + { "dxf", true, STR_DESCRIPTION_GRAPHIC_DOC, SvImageId::DXF }, + { "exe", true, STR_DESCRIPTION_APPLICATION, SvImageId::NONE }, + { "gif", true, STR_DESCRIPTION_GRAPHIC_DOC, SvImageId::GIF }, + { "h", true, STR_DESCRIPTION_SOURCEFILE, SvImageId::NONE }, + { "hlp", false, STR_DESCRIPTION_HELP_DOC, SvImageId::NONE }, + { "hrc", true, STR_DESCRIPTION_SOURCEFILE, SvImageId::NONE }, + { "htm", false, STR_DESCRIPTION_HTMLFILE, SvImageId::HTML }, + { "html", false, STR_DESCRIPTION_HTMLFILE, SvImageId::HTML }, + { "asp", false, STR_DESCRIPTION_HTMLFILE, SvImageId::HTML }, + { "hxx", true, STR_DESCRIPTION_SOURCEFILE, SvImageId::NONE }, + { "ini", false, STR_DESCRIPTION_CFGFILE, SvImageId::NONE }, + { "java", true, STR_DESCRIPTION_SOURCEFILE, SvImageId::NONE }, + { "jpeg", true, STR_DESCRIPTION_GRAPHIC_DOC, SvImageId::JPG }, + { "jpg", true, STR_DESCRIPTION_GRAPHIC_DOC, SvImageId::JPG }, + { "lha", true, STR_DESCRIPTION_ARCHIVFILE, SvImageId::NONE }, +#ifdef _WIN32 + { "lnk", false, nullptr, SvImageId::NONE }, +#endif + { "log", true, STR_DESCRIPTION_LOGFILE, SvImageId::NONE }, + { "lst", true, STR_DESCRIPTION_LOGFILE, SvImageId::NONE }, + { "met", true, STR_DESCRIPTION_GRAPHIC_DOC, SvImageId::MET }, + { "mml", false, STR_DESCRIPTION_MATHML_DOC, SvImageId::Math }, + { "mod", true, STR_DESCRIPTION_SOURCEFILE, SvImageId::NONE }, + { "odb", false, STR_DESCRIPTION_OO_DATABASE_DOC, SvImageId::OO_DatabaseDoc }, + { "odg", false, STR_DESCRIPTION_OO_DRAW_DOC, SvImageId::OO_DrawDoc }, + { "odf", false, STR_DESCRIPTION_OO_MATH_DOC, SvImageId::OO_MathDoc }, + { "odm", false, STR_DESCRIPTION_OO_GLOBAL_DOC, SvImageId::OO_GlobalDoc }, + { "odp", false, STR_DESCRIPTION_OO_IMPRESS_DOC, SvImageId::OO_ImpressDoc }, + { "ods", false, STR_DESCRIPTION_OO_CALC_DOC, SvImageId::OO_CalcDoc }, + { "odt", false, STR_DESCRIPTION_OO_WRITER_DOC, SvImageId::OO_WriterDoc }, + { "otg", false, STR_DESCRIPTION_OO_DRAW_TEMPLATE, SvImageId::OO_DrawTemplate }, + { "otp", false, STR_DESCRIPTION_OO_IMPRESS_TEMPLATE, SvImageId::OO_ImpressTemplate }, + { "ots", false, STR_DESCRIPTION_OO_CALC_TEMPLATE, SvImageId::OO_CalcTemplate }, + { "ott", false, STR_DESCRIPTION_OO_WRITER_TEMPLATE, SvImageId::OO_WriterTemplate }, + { "pas", true, STR_DESCRIPTION_SOURCEFILE, SvImageId::NONE }, + { "pcd", true, STR_DESCRIPTION_GRAPHIC_DOC, SvImageId::PCD }, + { "pct", true, STR_DESCRIPTION_GRAPHIC_DOC, SvImageId::PCT }, + { "pict", true, STR_DESCRIPTION_GRAPHIC_DOC, SvImageId::PCT }, + { "pcx", true, STR_DESCRIPTION_GRAPHIC_DOC, SvImageId::PCX }, + { "pl", true, STR_DESCRIPTION_SOURCEFILE, SvImageId::NONE }, + { "png", true, STR_DESCRIPTION_GRAPHIC_DOC, SvImageId::PNG }, + { "rar", true, STR_DESCRIPTION_ARCHIVFILE, SvImageId::NONE }, + { "rtf", false, STR_DESCRIPTION_WORD_DOC, SvImageId::Writer }, + { "sbl", false, nullptr, SvImageId::NONE }, + { "sch", false, nullptr, SvImageId::NONE }, + { "sda", false, STR_DESCRIPTION_SDRAW_DOC, SvImageId::Draw }, + { "sdb", false, STR_DESCRIPTION_SDATABASE_DOC, SvImageId::Database }, + { "sdc", false, STR_DESCRIPTION_SCALC_DOC, SvImageId::Calc }, + { "sdd", false, STR_DESCRIPTION_SIMPRESS_DOC, SvImageId::Impress }, + { "sdp", false, STR_DESCRIPTION_SIMPRESS_DOC, SvImageId::NONE }, + { "sds", false, STR_DESCRIPTION_SCHART_DOC, SvImageId::NONE }, + { "sdw", false, STR_DESCRIPTION_SWRITER_DOC, SvImageId::Writer }, + { "sga", false, nullptr, SvImageId::NONE }, + { "sgl", false, STR_DESCRIPTION_GLOBALDOC, SvImageId::GlobalDoc }, + { "shtml", false, STR_DESCRIPTION_HTMLFILE, SvImageId::HTML }, + { "sim", false, STR_DESCRIPTION_SIMAGE_DOC, SvImageId::SIM }, + { "smf", false, STR_DESCRIPTION_SMATH_DOC, SvImageId::Math }, + { "src", true, STR_DESCRIPTION_SOURCEFILE, SvImageId::NONE }, + { "svh", false, STR_DESCRIPTION_HELP_DOC, SvImageId::NONE }, + { "svm", true, STR_DESCRIPTION_GRAPHIC_DOC, SvImageId::SVM }, + { "stc", false, STR_DESCRIPTION_CALC_TEMPLATE, SvImageId::CalcTemplate }, + { "std", false, STR_DESCRIPTION_DRAW_TEMPLATE, SvImageId::DrawTemplate }, + { "sti", false, STR_DESCRIPTION_IMPRESS_TEMPLATE, SvImageId::ImpressTemplate }, + { "stw", false, STR_DESCRIPTION_WRITER_TEMPLATE, SvImageId::WriterTemplate }, + { "sxc", false, STR_DESCRIPTION_SXCALC_DOC, SvImageId::Calc }, + { "sxd", false, STR_DESCRIPTION_SXDRAW_DOC, SvImageId::Draw }, + { "sxg", false, STR_DESCRIPTION_SXGLOBAL_DOC, SvImageId::GlobalDoc }, + { "sxi", false, STR_DESCRIPTION_SXIMPRESS_DOC, SvImageId::Impress }, + { "sxm", false, STR_DESCRIPTION_SXMATH_DOC, SvImageId::Math }, + { "sxs", false, STR_DESCRIPTION_SXCHART_DOC, SvImageId::NONE }, + { "sxw", false, STR_DESCRIPTION_SXWRITER_DOC, SvImageId::Writer }, + { "sys", true, STR_DESCRIPTION_SYSFILE, SvImageId::NONE }, + { "tif", true, STR_DESCRIPTION_GRAPHIC_DOC, SvImageId::TIFF }, + { "tiff", true, STR_DESCRIPTION_GRAPHIC_DOC, SvImageId::TIFF }, + { "txt", false, STR_DESCRIPTION_TEXTFILE, SvImageId::TextFile }, + { "url", false, STR_DESCRIPTION_LINK, SvImageId::NONE }, + { "vor", false, STR_DESCRIPTION_SOFFICE_TEMPLATE_DOC, SvImageId::WriterTemplate }, + { "vxd", true, STR_DESCRIPTION_SYSFILE, SvImageId::NONE }, + { "wmf", true, STR_DESCRIPTION_GRAPHIC_DOC, SvImageId::WMF }, + { "xls", false, STR_DESCRIPTION_EXCEL_DOC, SvImageId::Calc }, + { "xlt", false, STR_DESCRIPTION_EXCEL_TEMPLATE_DOC, SvImageId::CalcTemplate }, + { "xlsx", false, STR_DESCRIPTION_EXCEL_DOC, SvImageId::Calc }, + { "uu", true, STR_DESCRIPTION_ARCHIVFILE, SvImageId::NONE }, + { "uue", true, STR_DESCRIPTION_ARCHIVFILE, SvImageId::NONE }, + { "z", true, STR_DESCRIPTION_ARCHIVFILE, SvImageId::NONE }, + { "zip", true, STR_DESCRIPTION_ARCHIVFILE, SvImageId::NONE }, + { "zoo", true, STR_DESCRIPTION_ARCHIVFILE, SvImageId::NONE }, + { "gz", true, STR_DESCRIPTION_ARCHIVFILE, SvImageId::NONE }, + { "ppt", false, STR_DESCRIPTION_POWERPOINT, SvImageId::Impress }, + { "pot", false, STR_DESCRIPTION_POWERPOINT_TEMPLATE, SvImageId::ImpressTemplate }, + { "pps", false, STR_DESCRIPTION_POWERPOINT_SHOW, SvImageId::Impress }, + { "pptx", false, STR_DESCRIPTION_POWERPOINT, SvImageId::Impress }, + { "oxt", false, STR_DESCRIPTION_EXTENSION, SvImageId::Extension }, + { nullptr, false, nullptr, SvImageId::NONE } +}; + +namespace { + +struct SvtFactory2ExtensionMapping_Impl +{ + const char* _pFactory; + const char* _pExtension; +}; + +} + +// mapping from "private:factory" url to extension + +static SvtFactory2ExtensionMapping_Impl const Fac2ExtMap_Impl[] = +{ + { "swriter", "odt" }, + { "swriter/web", "html" }, + { "swriter/GlobalDocument", "odm" }, + { "scalc", "ods" }, + { "simpress", "odp" }, + { "sdraw", "odg" }, + { "smath", "odf" }, + { "sdatabase", "odb" }, + { nullptr, nullptr } +}; + + +static OUString GetImageExtensionByFactory_Impl( const OUString& rURL ) +{ + INetURLObject aObj( rURL ); + OUString aPath = aObj.GetURLPath( INetURLObject::DecodeMechanism::NONE ); + OUString aExtension; + + if ( !aPath.isEmpty() ) + { + sal_uInt16 nIndex = 0; + while ( Fac2ExtMap_Impl[ nIndex ]._pFactory ) + { + if ( aPath.equalsAscii( Fac2ExtMap_Impl[ nIndex ]._pFactory ) ) + { + // extension found + aExtension = OUString::createFromAscii(Fac2ExtMap_Impl[ nIndex ]._pExtension); + // and return it + return aExtension; + } + ++nIndex; + } + } + + // no extension found, so use the type detection (performance brake) + + try + { + // get the TypeDetection service to access all registered types + css::uno::Reference < css::uno::XComponentContext > xContext = ::comphelper::getProcessComponentContext(); + css::uno::Reference < css::document::XTypeDetection > xTypeDetector( + xContext->getServiceManager()->createInstanceWithContext("com.sun.star.document.TypeDetection", xContext), + css::uno::UNO_QUERY ); + + OUString aInternalType = xTypeDetector->queryTypeByURL( rURL ); + css::uno::Reference < css::container::XNameAccess > xAccess( xTypeDetector, css::uno::UNO_QUERY ); + css::uno::Sequence < css::beans::PropertyValue > aTypeProps; + if ( !aInternalType.isEmpty() && xAccess->hasByName( aInternalType ) ) + { + xAccess->getByName( aInternalType ) >>= aTypeProps; + for ( const css::beans::PropertyValue& rProp : std::as_const(aTypeProps) ) + { + if (rProp.Name == "Extensions") + { + css::uno::Sequence < OUString > aExtensions; + if ( ( rProp.Value >>= aExtensions ) && aExtensions.hasElements() ) + { + const OUString* pExtensions = aExtensions.getConstArray(); + aExtension = pExtensions[0]; + break; + } + } + } + } + } + catch( const css::uno::RuntimeException& ) + { + throw; // don't hide it! + } + catch( const css::uno::Exception& ) + { + // type detection failed -> no extension + } + + return aExtension; +} + +static sal_Int32 GetIndexOfExtension_Impl( const OUString& rExtension ) +{ + sal_Int32 nRet = NO_INDEX; + if ( !rExtension.isEmpty() ) + { + sal_Int32 nIndex = 0; + OUString aExt = rExtension.toAsciiLowerCase(); + while ( ExtensionMap_Impl[ nIndex ]._pExt ) + { + if ( aExt.equalsAscii( ExtensionMap_Impl[ nIndex ]._pExt ) ) + { + nRet = nIndex; + break; + } + ++nIndex; + } + } + + return nRet; +} + +static SvImageId GetImageId_Impl( const OUString& rExtension ) +{ + SvImageId nImage = SvImageId::File; + sal_Int32 nIndex = GetIndexOfExtension_Impl( rExtension ); + if ( nIndex != NO_INDEX ) + { + nImage = ExtensionMap_Impl[ nIndex ]._nImgId; + if ( nImage == SvImageId::NONE ) + nImage = SvImageId::File; + } + + return nImage; +} + +static bool GetVolumeProperties_Impl( ::ucbhelper::Content& rContent, svtools::VolumeInfo& rVolumeInfo ) +{ + bool bRet = false; + + try + { + bRet = ( ( rContent.getPropertyValue( "IsVolume" ) >>= rVolumeInfo.m_bIsVolume ) && + ( rContent.getPropertyValue( "IsRemote" ) >>= rVolumeInfo.m_bIsRemote ) && + ( rContent.getPropertyValue( "IsRemoveable" ) >>= rVolumeInfo.m_bIsRemoveable ) && + ( rContent.getPropertyValue( "IsFloppy" ) >>= rVolumeInfo.m_bIsFloppy ) && + ( rContent.getPropertyValue( "IsCompactDisc" ) >>= rVolumeInfo.m_bIsCompactDisc ) ); + } + catch( const css::uno::RuntimeException& ) + { + throw; // don't hide it! + } + catch( const css::uno::Exception& ) + { + // type detection failed -> no extension + } + + return bRet; +} + +static SvImageId GetFolderImageId_Impl( const OUString& rURL ) +{ + SvImageId nRet = SvImageId::Folder; + ::svtools::VolumeInfo aVolumeInfo; + try + { + ::ucbhelper::Content aCnt( rURL, css::uno::Reference< css::ucb::XCommandEnvironment >(), comphelper::getProcessComponentContext() ); + if ( GetVolumeProperties_Impl( aCnt, aVolumeInfo ) ) + { + if ( aVolumeInfo.m_bIsRemote ) + nRet = SvImageId::NetworkDevice; + else if ( aVolumeInfo.m_bIsCompactDisc ) + nRet = SvImageId::CDRomDevice; + else if ( aVolumeInfo.m_bIsRemoveable ) + nRet = SvImageId::RemoveableDevice; + else if ( aVolumeInfo.m_bIsVolume ) + nRet = SvImageId::FixedDevice; + } + } + catch( const css::uno::RuntimeException& ) + { + throw; // don't hide it! + } + catch( const css::uno::Exception& ) + { + + } + return nRet; +} + +static SvImageId GetImageId_Impl( const INetURLObject& rObject, bool bDetectFolder ) +{ + OUString aExt, sURL = rObject.GetMainURL( INetURLObject::DecodeMechanism::NONE ); + SvImageId nImage = SvImageId::File; + + if ( rObject.GetProtocol() == INetProtocol::PrivSoffice ) + { + OUString aURLPath = sURL.copy( strlen(URL_PREFIX_PRIV_SOFFICE) ); + OUString aType = aURLPath.getToken( 0, '/' ); + if ( aType == "factory" ) + { + // detect an image id for our "private:factory" urls + aExt = GetImageExtensionByFactory_Impl( sURL ); + if ( !aExt.isEmpty() ) + nImage = GetImageId_Impl( aExt ); + return nImage; + } + else if ( aType == "image" ) + nImage = static_cast<SvImageId>(aURLPath.getToken( 1, '/' ).toInt32()); + } + else + { + aExt = rObject.getExtension(); + if ( aExt == "vor" ) + { + SvImageId nId = SvImageId::WriterTemplate; + try + { + tools::SvRef<SotStorage> aStorage = new SotStorage( sURL, StreamMode::STD_READ ); + if ( !aStorage->GetError() ) + { + SvGlobalName aGlobalName = aStorage->GetClassName(); + if ( aGlobalName == SvGlobalName(SO3_SC_CLASSID_50) || aGlobalName == SvGlobalName(SO3_SC_CLASSID_40) || aGlobalName == SvGlobalName(SO3_SC_CLASSID_30) ) + nId = SvImageId::CalcTemplate; + else if ( aGlobalName == SvGlobalName(SO3_SDRAW_CLASSID_50) ) + nId = SvImageId::DrawTemplate; + else if ( aGlobalName == SvGlobalName(SO3_SIMPRESS_CLASSID_50) || + aGlobalName == SvGlobalName(SO3_SIMPRESS_CLASSID_40) || aGlobalName == SvGlobalName(SO3_SIMPRESS_CLASSID_30) ) + nId = SvImageId::ImpressTemplate; + else if ( aGlobalName == SvGlobalName(SO3_SM_CLASSID_50) || aGlobalName == SvGlobalName(SO3_SM_CLASSID_40) || aGlobalName == SvGlobalName(SO3_SM_CLASSID_30) ) + nId = SvImageId::MathTemplate; + } + } + catch (const css::ucb::ContentCreationException&) + { + TOOLS_WARN_EXCEPTION("svtools.misc", "GetImageId_Impl"); + } + + return nId; + } + } + + if ( nImage == SvImageId::File && !sURL.isEmpty() ) + { + if ( bDetectFolder && CONTENT_HELPER::IsFolder( sURL ) ) + nImage = GetFolderImageId_Impl( sURL ); + else if ( !aExt.isEmpty() ) + nImage = GetImageId_Impl( aExt ); + } + return nImage; +} + +static const char* GetDescriptionId_Impl( const OUString& rExtension, bool& rbShowExt ) +{ + const char* pId = nullptr; + sal_Int32 nIndex = GetIndexOfExtension_Impl( rExtension ); + if ( nIndex != NO_INDEX ) + { + pId = ExtensionMap_Impl[ nIndex ].pStrId; + rbShowExt = ExtensionMap_Impl[ nIndex ]._bExt; + } + + return pId; +} + +static OUString GetDescriptionByFactory_Impl( const OUString& rFactory ) +{ + const char* pResId = nullptr; + if ( rFactory.startsWithIgnoreAsciiCase( "swriter" ) ) + pResId = STR_DESCRIPTION_FACTORY_WRITER; + else if ( rFactory.startsWithIgnoreAsciiCase( "scalc" ) ) + pResId = STR_DESCRIPTION_FACTORY_CALC; + else if ( rFactory.startsWithIgnoreAsciiCase( "simpress" ) ) + pResId = STR_DESCRIPTION_FACTORY_IMPRESS; + else if ( rFactory.startsWithIgnoreAsciiCase( "sdraw" ) ) + pResId = STR_DESCRIPTION_FACTORY_DRAW; + else if ( rFactory.startsWithIgnoreAsciiCase( "swriter/web" ) ) + pResId = STR_DESCRIPTION_FACTORY_WRITERWEB; + else if ( rFactory.startsWithIgnoreAsciiCase( "swriter/globaldocument" ) ) + pResId = STR_DESCRIPTION_FACTORY_GLOBALDOC; + else if ( rFactory.startsWithIgnoreAsciiCase( "smath" ) ) + pResId = STR_DESCRIPTION_FACTORY_MATH; + else if ( rFactory.startsWithIgnoreAsciiCase( "sdatabase" ) ) + pResId = STR_DESCRIPTION_FACTORY_DATABASE; + + if (pResId) + { + return SvtResId(pResId); + } + return OUString(); +} + +static const char* GetFolderDescriptionId_Impl( const OUString& rURL ) +{ + const char* pRet = STR_DESCRIPTION_FOLDER; + svtools::VolumeInfo aVolumeInfo; + try + { + ::ucbhelper::Content aCnt( rURL, css::uno::Reference< css::ucb::XCommandEnvironment >(), comphelper::getProcessComponentContext() ); + if ( GetVolumeProperties_Impl( aCnt, aVolumeInfo ) ) + { + if ( aVolumeInfo.m_bIsRemote ) + pRet = STR_DESCRIPTION_REMOTE_VOLUME; + else if ( aVolumeInfo.m_bIsFloppy ) + pRet = STR_DESCRIPTION_FLOPPY_VOLUME; + else if ( aVolumeInfo.m_bIsCompactDisc ) + pRet = STR_DESCRIPTION_CDROM_VOLUME; + else if ( aVolumeInfo.m_bIsRemoveable || aVolumeInfo.m_bIsVolume ) + pRet = STR_DESCRIPTION_LOCALE_VOLUME; + } + } + catch( const css::uno::RuntimeException& ) + { + throw; // don't hide it! + } + catch( const css::uno::Exception& ) + { + + } + return pRet; +} + +static OUString GetImageNameFromList_Impl( SvImageId nImageId, vcl::ImageType eImageType ) +{ + if (eImageType == vcl::ImageType::Size32) + { + switch (nImageId) + { + case SvImageId::HTML: + return BMP_HTML_32; + case SvImageId::OO_DatabaseDoc: + return BMP_OO_DATABASE_DOC_32; + case SvImageId::OO_DrawDoc: + return BMP_OO_DRAW_DOC_32; + case SvImageId::OO_MathDoc: + return BMP_OO_MATH_DOC_32; + case SvImageId::OO_GlobalDoc: + return BMP_OO_GLOBAL_DOC_32; + case SvImageId::OO_ImpressDoc: + return BMP_OO_IMPRESS_DOC_32; + case SvImageId::OO_CalcDoc: + return BMP_OO_CALC_DOC_32; + case SvImageId::OO_WriterDoc: + return BMP_OO_WRITER_DOC_32; + case SvImageId::OO_WriterTemplate: + return BMP_OO_WRITER_TEMPLATE_32; + default: break; + } + } + else if (eImageType == vcl::ImageType::Size26) + { + switch (nImageId) + { + case SvImageId::Impress: + return BMP_IMPRESS_LC; + case SvImageId::Bitmap: + return BMP_BITMAP_LC; + case SvImageId::Calc: + return BMP_CALC_LC; + case SvImageId::CalcTemplate: + return BMP_CALCTEMPLATE_LC; + case SvImageId::Database: + return BMP_DATABASE_LC; + case SvImageId::ImpressTemplate: + return BMP_IMPRESSTEMPLATE_LC; + case SvImageId::GIF: + return BMP_GIF_LC; + case SvImageId::HTML: + return BMP_HTML_LC; + case SvImageId::JPG: + return BMP_JPG_LC; + case SvImageId::Math: + return BMP_MATH_LC; + case SvImageId::MathTemplate: + return BMP_MATHTEMPLATE_LC; + case SvImageId::File: + return BMP_FILE_LC; + case SvImageId::PCD: + return BMP_PCD_LC; + case SvImageId::PCT: + return BMP_PCT_LC; + case SvImageId::PCX: + return BMP_PCX_LC; + case SvImageId::SIM: + return BMP_SIM_LC; + case SvImageId::TextFile: + return BMP_TEXTFILE_LC; + case SvImageId::TIFF: + return BMP_TIFF_LC; + case SvImageId::WMF: + return BMP_WMF_LC; + case SvImageId::Writer: + return BMP_WRITER_LC; + case SvImageId::WriterTemplate: + return BMP_WRITERTEMPLATE_LC; + case SvImageId::FixedDevice: + return BMP_FIXEDDEV_LC; + case SvImageId::RemoveableDevice: + return BMP_REMOVABLEDEV_LC; + case SvImageId::CDRomDevice: + return BMP_CDROMDEV_LC; + case SvImageId::NetworkDevice: + return BMP_NETWORKDEV_LC; + case SvImageId::Table: + return BMP_TABLE_LC; + case SvImageId::Folder: + return BMP_FOLDER_LC; + case SvImageId::DXF: + return BMP_DXF_LC; + case SvImageId::MET: + return BMP_MET_LC; + case SvImageId::PNG: + return BMP_PNG_LC; + case SvImageId::SVM: + return BMP_SVM_LC; + case SvImageId::GlobalDoc: + return BMP_GLOBAL_DOC_LC; + case SvImageId::Draw: + return BMP_DRAW_LC; + case SvImageId::DrawTemplate: + return BMP_DRAWTEMPLATE_LC; + case SvImageId::OO_DatabaseDoc: + return BMP_OO_DATABASE_DOC_LC; + case SvImageId::OO_DrawDoc: + return BMP_OO_DRAW_DOC_LC; + case SvImageId::OO_MathDoc: + return BMP_OO_MATH_DOC_LC; + case SvImageId::OO_GlobalDoc: + return BMP_OO_GLOBAL_DOC_LC; + case SvImageId::OO_ImpressDoc: + return BMP_OO_IMPRESS_DOC_LC; + case SvImageId::OO_CalcDoc: + return BMP_OO_CALC_DOC_LC; + case SvImageId::OO_WriterDoc: + return BMP_OO_WRITER_DOC_LC; + case SvImageId::OO_DrawTemplate: + return BMP_OO_DRAW_TEMPLATE_LC; + case SvImageId::OO_ImpressTemplate: + return BMP_OO_IMPRESS_TEMPLATE_LC; + case SvImageId::OO_CalcTemplate: + return BMP_OO_CALC_TEMPLATE_LC; + case SvImageId::OO_WriterTemplate: + return BMP_OO_WRITER_TEMPLATE_LC; + case SvImageId::Extension: + return BMP_EXTENSION_LC; + default: break; + } + } + else + { + switch (nImageId) + { + case SvImageId::Impress: + return BMP_IMPRESS_SC; + case SvImageId::Bitmap: + return BMP_BITMAP_SC; + case SvImageId::Calc: + return BMP_CALC_SC; + case SvImageId::CalcTemplate: + return BMP_CALCTEMPLATE_SC; + case SvImageId::Database: + return BMP_DATABASE_SC; + case SvImageId::ImpressTemplate: + return BMP_IMPRESSTEMPLATE_SC; + case SvImageId::GIF: + return BMP_GIF_SC; + case SvImageId::HTML: + return BMP_HTML_SC; + case SvImageId::JPG: + return BMP_JPG_SC; + case SvImageId::Math: + return BMP_MATH_SC; + case SvImageId::MathTemplate: + return BMP_MATHTEMPLATE_SC; + case SvImageId::File: + return BMP_FILE_SC; + case SvImageId::PCD: + return BMP_PCD_SC; + case SvImageId::PCT: + return BMP_PCT_SC; + case SvImageId::PCX: + return BMP_PCX_SC; + case SvImageId::SIM: + return BMP_SIM_SC; + case SvImageId::TextFile: + return BMP_TEXTFILE_SC; + case SvImageId::TIFF: + return BMP_TIFF_SC; + case SvImageId::WMF: + return BMP_WMF_SC; + case SvImageId::Writer: + return BMP_WRITER_SC; + case SvImageId::WriterTemplate: + return BMP_WRITERTEMPLATE_SC; + case SvImageId::FixedDevice: + return BMP_FIXEDDEV_SC; + case SvImageId::RemoveableDevice: + return BMP_REMOVABLEDEV_SC; + case SvImageId::CDRomDevice: + return BMP_CDROMDEV_SC; + case SvImageId::NetworkDevice: + return BMP_NETWORKDEV_SC; + case SvImageId::Table: + return BMP_TABLE_SC; + case SvImageId::Folder: + return RID_BMP_FOLDER; + case SvImageId::DXF: + return BMP_DXF_SC; + case SvImageId::MET: + return BMP_MET_SC; + case SvImageId::PNG: + return BMP_PNG_SC; + case SvImageId::SVM: + return BMP_SVM_SC; + case SvImageId::GlobalDoc: + return BMP_GLOBAL_DOC_SC; + case SvImageId::Draw: + return BMP_DRAW_SC; + case SvImageId::DrawTemplate: + return BMP_DRAWTEMPLATE_SC; + case SvImageId::OO_DatabaseDoc: + return BMP_OO_DATABASE_DOC_SC; + case SvImageId::OO_DrawDoc: + return BMP_OO_DRAW_DOC_SC; + case SvImageId::OO_MathDoc: + return BMP_OO_MATH_DOC_SC; + case SvImageId::OO_GlobalDoc: + return BMP_OO_GLOBAL_DOC_SC; + case SvImageId::OO_ImpressDoc: + return BMP_OO_IMPRESS_DOC_SC; + case SvImageId::OO_CalcDoc: + return BMP_OO_CALC_DOC_SC; + case SvImageId::OO_WriterDoc: + return BMP_OO_WRITER_DOC_SC; + case SvImageId::OO_DrawTemplate: + return BMP_OO_DRAW_TEMPLATE_SC; + case SvImageId::OO_ImpressTemplate: + return BMP_OO_IMPRESS_TEMPLATE_SC; + case SvImageId::OO_CalcTemplate: + return BMP_OO_CALC_TEMPLATE_SC; + case SvImageId::OO_WriterTemplate: + return BMP_OO_WRITER_TEMPLATE_SC; + case SvImageId::Extension: + return BMP_EXTENSION_SC; + default: break; + } + } + + return OUString(); +} + +static Image GetImageFromList_Impl( SvImageId nImageId, vcl::ImageType eImageType, Size aSize = Size()) +{ + OUString sImageName(GetImageNameFromList_Impl(nImageId, eImageType)); + if (!sImageName.isEmpty()) + return Image(StockImage::Yes, sImageName, aSize); + return Image(); +} + +OUString SvFileInformationManager::GetDescription_Impl( const INetURLObject& rObject, bool bDetectFolder ) +{ + OUString sExtension(rObject.getExtension()); + OUString sDescription, sURL( rObject.GetMainURL( INetURLObject::DecodeMechanism::NONE ) ); + const char* pResId = nullptr; + bool bShowExt = false, bOnlyFile = false; + bool bFolder = bDetectFolder && CONTENT_HELPER::IsFolder( sURL ); + if ( !bFolder ) + { + bool bDetected = false; + + if ( rObject.GetProtocol() == INetProtocol::PrivSoffice ) + { + OUString aURLPath = sURL.copy( strlen(URL_PREFIX_PRIV_SOFFICE) ); + OUString aType = aURLPath.getToken( 0, '/' ); + if ( aType == "factory" ) + { + sDescription = GetDescriptionByFactory_Impl( aURLPath.copy( aURLPath.indexOf( '/' ) + 1 ) ); + bDetected = true; + } + } + + if (!bDetected) + { + // search a description by extension + bool bExt = !sExtension.isEmpty(); + if ( bExt ) + { + sExtension = sExtension.toAsciiLowerCase(); + pResId = GetDescriptionId_Impl( sExtension, bShowExt ); + } + if (!pResId) + { + pResId = STR_DESCRIPTION_FILE; + bOnlyFile = bExt; + } + } + } + else + pResId = GetFolderDescriptionId_Impl( sURL ); + + if (pResId) + { + if ( bOnlyFile ) + { + bShowExt = false; + sExtension = sExtension.toAsciiUpperCase(); + sDescription = sExtension + "-"; + } + sDescription += SvtResId(pResId); + } + + DBG_ASSERT( !sDescription.isEmpty(), "file without description" ); + + if ( bShowExt ) + { + sDescription += " (" + sExtension + ")"; + } + + return sDescription; +} + +OUString SvFileInformationManager::GetImageId(const INetURLObject& rObject, bool bBig) +{ + SvImageId nImage = GetImageId_Impl( rObject, true ); + DBG_ASSERT( nImage != SvImageId::NONE, "invalid ImageId" ); + return GetImageNameFromList_Impl(nImage, bBig ? vcl::ImageType::Size26 : vcl::ImageType::Size16); +} + +Image SvFileInformationManager::GetImage(const INetURLObject& rObject, bool bBig, Size const & rPreferredSize) +{ + SvImageId nImage = GetImageId_Impl( rObject, true ); + DBG_ASSERT( nImage != SvImageId::NONE, "invalid ImageId" ); + return GetImageFromList_Impl(nImage, bBig ? vcl::ImageType::Size26 : vcl::ImageType::Size16, rPreferredSize); +} + +OUString SvFileInformationManager::GetFileImageId(const INetURLObject& rObject) +{ + SvImageId nImage = GetImageId_Impl( rObject, false ); + DBG_ASSERT( nImage != SvImageId::NONE, "invalid ImageId" ); + return GetImageNameFromList_Impl(nImage, vcl::ImageType::Size16); +} + +Image SvFileInformationManager::GetImageNoDefault(const INetURLObject& rObject, vcl::ImageType eImageType) +{ + SvImageId nImage = GetImageId_Impl(rObject, true); + DBG_ASSERT( nImage != SvImageId::NONE, "invalid ImageId" ); + + if ( nImage == SvImageId::File ) + return Image(); + + return GetImageFromList_Impl(nImage, eImageType); +} + +OUString SvFileInformationManager::GetFolderImageId( const svtools::VolumeInfo& rInfo ) +{ + SvImageId nImage = SvImageId::Folder; + DBG_ASSERT( nImage != SvImageId::NONE, "invalid ImageId" ); + + if ( rInfo.m_bIsRemote ) + nImage = SvImageId::NetworkDevice; + else if ( rInfo.m_bIsCompactDisc ) + nImage = SvImageId::CDRomDevice; + else if ( rInfo.m_bIsRemoveable || rInfo.m_bIsFloppy ) + nImage = SvImageId::RemoveableDevice; + else if ( rInfo.m_bIsVolume ) + nImage = SvImageId::FixedDevice; + + return GetImageNameFromList_Impl(nImage, vcl::ImageType::Size16); +} + +OUString SvFileInformationManager::GetDescription( const INetURLObject& rObject ) +{ + return SvFileInformationManager::GetDescription_Impl( rObject, true ); +} + +OUString SvFileInformationManager::GetFileDescription( const INetURLObject& rObject ) +{ + return SvFileInformationManager::GetDescription_Impl( rObject, false ); +} + +OUString SvFileInformationManager::GetFolderDescription( const svtools::VolumeInfo& rInfo ) +{ + const char* pResId = STR_DESCRIPTION_FOLDER; + if ( rInfo.m_bIsRemote ) + pResId = STR_DESCRIPTION_REMOTE_VOLUME; + else if ( rInfo.m_bIsFloppy ) + pResId = STR_DESCRIPTION_FLOPPY_VOLUME; + else if ( rInfo.m_bIsCompactDisc ) + pResId = STR_DESCRIPTION_CDROM_VOLUME; + else if ( rInfo.m_bIsRemoveable || rInfo.m_bIsVolume ) + pResId = STR_DESCRIPTION_LOCALE_VOLUME; + + return SvtResId(pResId); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/misc/imageresourceaccess.cxx b/svtools/source/misc/imageresourceaccess.cxx new file mode 100644 index 000000000..24db4ae50 --- /dev/null +++ b/svtools/source/misc/imageresourceaccess.cxx @@ -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 . + */ + + +#include <svtools/imageresourceaccess.hxx> + +#include <com/sun/star/io/NotConnectedException.hpp> +#include <com/sun/star/io/XSeekable.hpp> +#include <com/sun/star/graphic/GraphicProvider.hpp> +#include <com/sun/star/graphic/XGraphicProvider.hpp> +#include <com/sun/star/io/XStream.hpp> +#include <osl/diagnose.h> +#include <tools/stream.hxx> +#include <tools/diagnose_ex.h> +#include <unotools/streamwrap.hxx> +#include <cppuhelper/implbase.hxx> + +namespace svt::GraphicAccess +{ + +using namespace ::utl; +using namespace css; + +typedef ::cppu::WeakImplHelper<io::XStream, io::XSeekable> StreamSupplier_Base; + +namespace { + +class StreamSupplier : public StreamSupplier_Base +{ +private: + uno::Reference<io::XInputStream> m_xInput; + uno::Reference<io::XOutputStream> m_xOutput; + uno::Reference<io::XSeekable> m_xSeekable; + +public: + StreamSupplier(uno::Reference<io::XInputStream> const & rxInput, uno::Reference<io::XOutputStream> const & rxOutput); + +protected: + // XStream + virtual uno::Reference<io::XInputStream> SAL_CALL getInputStream() override; + virtual uno::Reference<io::XOutputStream> SAL_CALL getOutputStream() 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; +}; + +} + +StreamSupplier::StreamSupplier(uno::Reference<io::XInputStream> const & rxInput, uno::Reference<io::XOutputStream> const & rxOutput) + : m_xInput(rxInput) + , m_xOutput(rxOutput) +{ + m_xSeekable.set(m_xInput, uno::UNO_QUERY); + if (!m_xSeekable.is()) + m_xSeekable.set(m_xOutput, uno::UNO_QUERY); + OSL_ENSURE(m_xSeekable.is(), "StreamSupplier::StreamSupplier: at least one of both must be seekable!"); +} + +uno::Reference<io::XInputStream> SAL_CALL StreamSupplier::getInputStream() +{ + return m_xInput; +} + +uno::Reference<io::XOutputStream> SAL_CALL StreamSupplier::getOutputStream() +{ + return m_xOutput; +} + +void SAL_CALL StreamSupplier::seek(sal_Int64 nLocation) +{ + if (!m_xSeekable.is()) + throw io::NotConnectedException(); + m_xSeekable->seek(nLocation); +} + +sal_Int64 SAL_CALL StreamSupplier::getPosition() +{ + if (!m_xSeekable.is()) + throw io::NotConnectedException(); + return m_xSeekable->getPosition(); +} + +sal_Int64 SAL_CALL StreamSupplier::getLength() +{ + if (!m_xSeekable.is()) + throw io::NotConnectedException(); + + return m_xSeekable->getLength(); +} + +bool isSupportedURL(OUString const & rURL) +{ + return rURL.startsWith("private:resource/") + || rURL.startsWith("private:graphicrepository/") + || rURL.startsWith("private:standardimage/") + || rURL.startsWith("vnd.sun.star.extension://"); +} + +std::unique_ptr<SvStream> getImageStream(uno::Reference<uno::XComponentContext> const & rxContext, OUString const & rImageResourceURL) +{ + std::unique_ptr<SvMemoryStream> pMemBuffer; + + try + { + // get a GraphicProvider + uno::Reference<graphic::XGraphicProvider> xProvider = css::graphic::GraphicProvider::create(rxContext); + + // let it create a graphic from the given URL + uno::Sequence<beans::PropertyValue> aMediaProperties(1); + aMediaProperties[0].Name = "URL"; + aMediaProperties[0].Value <<= rImageResourceURL; + uno::Reference<graphic::XGraphic> xGraphic(xProvider->queryGraphic(aMediaProperties)); + + OSL_ENSURE(xGraphic.is(), "GraphicAccess::getImageStream: the provider did not give us a graphic object!"); + if (!xGraphic.is()) + return pMemBuffer; + + // copy the graphic to an in-memory buffer + pMemBuffer.reset(new SvMemoryStream); + uno::Reference<io::XStream> xBufferAccess = new StreamSupplier( + new OSeekableInputStreamWrapper(*pMemBuffer), + new OSeekableOutputStreamWrapper(*pMemBuffer)); + + aMediaProperties.realloc(2); + aMediaProperties[0].Name = "OutputStream"; + aMediaProperties[0].Value <<= xBufferAccess; + aMediaProperties[1].Name = "MimeType"; + aMediaProperties[1].Value <<= OUString("image/png"); + xProvider->storeGraphic(xGraphic, aMediaProperties); + + pMemBuffer->Seek(0); + } + catch (const uno::Exception&) + { + TOOLS_WARN_EXCEPTION("svtools", "GraphicAccess::getImageStream"); + pMemBuffer.reset(); + } + + return pMemBuffer; +} + +uno::Reference<io::XInputStream> getImageXStream(uno::Reference<uno::XComponentContext> const & rxContext, OUString const & rImageResourceURL) +{ + return new OSeekableInputStreamWrapper(getImageStream(rxContext, rImageResourceURL).release(), true); // take ownership +} + +} // namespace svt::GraphicAccess + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/misc/langhelp.cxx b/svtools/source/misc/langhelp.cxx new file mode 100644 index 000000000..acaf2c6e2 --- /dev/null +++ b/svtools/source/misc/langhelp.cxx @@ -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/. + */ + +#include <sal/config.h> + +#include <string_view> + +#include <comphelper/sequence.hxx> +#include <i18nlangtag/languagetag.hxx> +#include <i18nlangtag/mslangid.hxx> +#include <officecfg/Office/Common.hxx> +#include <officecfg/System.hxx> +#include <org/freedesktop/PackageKit/SyncDbusSessionHelper.hpp> +#include <rtl/ustring.hxx> +#include <svtools/langhelp.hxx> +#include <tools/diagnose_ex.h> +#include <vcl/idle.hxx> +#include <vcl/svapp.hxx> +#include <vcl/settings.hxx> +#include <vcl/window.hxx> +#include <config_langs.h> +#include <config_vendor.h> + +void localizeWebserviceURI( OUString& rURI ) +{ + OUString aLang = Application::GetSettings().GetUILanguageTag().getLanguage(); + if ( aLang.equalsIgnoreAsciiCase("pt") + && Application::GetSettings().GetUILanguageTag().getCountry().equalsIgnoreAsciiCase("br") ) + { + aLang = "pt-br"; + } + if ( aLang.equalsIgnoreAsciiCase("zh") ) + { + if ( Application::GetSettings().GetUILanguageTag().getCountry().equalsIgnoreAsciiCase("cn") ) + aLang = "zh-cn"; + if ( Application::GetSettings().GetUILanguageTag().getCountry().equalsIgnoreAsciiCase("tw") ) + aLang = "zh-tw"; + } + + rURI += aLang; +} + +OUString getInstalledLocaleForLanguage(css::uno::Sequence<OUString> const & installed, OUString const & locale) +{ + if (locale.isEmpty()) + return OUString(); // do not attempt to resolve anything + + if (comphelper::findValue(installed, locale) != -1) + return locale; + + std::vector<OUString> fallbacks(LanguageTag(locale).getFallbackStrings(false)); + auto pf = std::find_if(fallbacks.begin(), fallbacks.end(), + [&installed](const OUString& rf) { return comphelper::findValue(installed, rf) != -1; }); + if (pf != fallbacks.end()) + return *pf; + return OUString(); +} + +static std::unique_ptr<Idle> xLangpackInstaller; + +namespace { + +class InstallLangpack : public Idle +{ + std::vector<OUString> m_aPackages; +public: + explicit InstallLangpack(const std::vector<OUString>& rPackages) + : Idle("install langpack") + , m_aPackages(rPackages) + { + SetPriority(TaskPriority::LOWEST); + } + + virtual void Invoke() override + { + vcl::Window* pTopWindow = Application::GetActiveTopWindow(); + if (!pTopWindow) + pTopWindow = Application::GetFirstTopLevelWindow(); + if (!pTopWindow) + { + Start(); + return; + } + try + { + using namespace org::freedesktop::PackageKit; + css::uno::Reference<XSyncDbusSessionHelper> xSyncDbusSessionHelper(SyncDbusSessionHelper::create(comphelper::getProcessComponentContext())); + xSyncDbusSessionHelper->InstallPackageNames(comphelper::containerToSequence(m_aPackages), OUString()); + } + catch (const css::uno::Exception&) + { + TOOLS_INFO_EXCEPTION("svl", "trying to install a LibreOffice langpack"); + } + xLangpackInstaller.reset(); + } +}; + +} + +OUString getInstalledLocaleForSystemUILanguage(const css::uno::Sequence<OUString>& rLocaleElementNames, bool bRequestInstallIfMissing, const OUString& rPreferredLocale) +{ + OUString wantedLocale(rPreferredLocale); + if (wantedLocale.isEmpty()) + wantedLocale = officecfg::System::L10N::UILocale::get(); + + OUString locale = getInstalledLocaleForLanguage(rLocaleElementNames, wantedLocale); + if (bRequestInstallIfMissing && locale.isEmpty() && !wantedLocale.isEmpty() && !Application::IsHeadlessModeEnabled() && + officecfg::Office::Common::PackageKit::EnableLangpackInstallation::get()) + { + LanguageTag aWantedTag(wantedLocale); + if (aWantedTag.getLanguage() != "en") + { + // Get the list of langpacks that this build was configured to include + std::vector<OUString> aPackages; + OUString const sAvailableLocales(WITH_LANG); + std::vector<OUString> aAvailable; + sal_Int32 nIndex = 0; + do + { + aAvailable.emplace_back(sAvailableLocales.getToken(0, ' ', nIndex)); + } + while (nIndex >= 0); + // See which one matches the desired ui locale + OUString install = getInstalledLocaleForLanguage(comphelper::containerToSequence(aAvailable), wantedLocale); + if (!install.isEmpty() && install != "en-US") + { + std::string_view sVendor(OOO_VENDOR); + if (sVendor == "Red Hat, Inc." || sVendor == "The Fedora Project") + { + // langpack is the typical Fedora/RHEL naming convention + LanguageType eType = aWantedTag.getLanguageType(); + if (MsLangId::isSimplifiedChinese(eType)) + aPackages.emplace_back("libreoffice-langpack-zh-Hans"); + else if (MsLangId::isTraditionalChinese(eType)) + aPackages.emplace_back("libreoffice-langpack-zh-Hant"); + else if (install == "pt") + aPackages.emplace_back("libreoffice-langpack-pt-PT"); + else + aPackages.emplace_back("libreoffice-langpack-" + install); + } + else if (sVendor == "The Document Foundation/Debian" || sVendor == "The Document Foundation, Debian and Ubuntu") + { + // l10n is the typical Debian/Ubuntu naming convention + aPackages.emplace_back("libreoffice-l10n-" + install); + } + } + if (!aPackages.empty()) + { + xLangpackInstaller.reset(new InstallLangpack(aPackages)); + xLangpackInstaller->Start(); + } + } + } + if (locale.isEmpty()) + locale = getInstalledLocaleForLanguage(rLocaleElementNames, "en-US"); + if (locale.isEmpty() && rLocaleElementNames.hasElements()) + locale = rLocaleElementNames[0]; + return locale; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/misc/langtab.cxx b/svtools/source/misc/langtab.cxx new file mode 100644 index 000000000..7c655b1f0 --- /dev/null +++ b/svtools/source/misc/langtab.cxx @@ -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 . + */ + +#include <com/sun/star/container/XNameAccess.hpp> +#include <com/sun/star/i18n/DirectionProperty.hpp> +#include <com/sun/star/uno/Sequence.hxx> +#include <com/sun/star/uno/Any.h> + +#include <i18nlangtag/lang.h> +#include <i18nlangtag/mslangid.hxx> +#include <i18nlangtag/languagetag.hxx> + +#include <sal/log.hxx> +#include <svtools/svtresid.hxx> +#include <svtools/langtab.hxx> +#include <unotools/syslocale.hxx> +#include <unotools/charclass.hxx> +#include <tools/resary.hxx> +#include <officecfg/VCL.hxx> +#include <langtab.hrc> + +using namespace ::com::sun::star; + +namespace { + +class SvtLanguageTableImpl +{ +private: + std::vector<std::pair<OUString, LanguageType>> m_aStrings; +public: + + SvtLanguageTableImpl(); + + bool HasType( const LanguageType eType ) const; + OUString GetString( const LanguageType eType ) const; + LanguageType GetType( const OUString& rStr ) const; + sal_uInt32 GetEntryCount() const; + LanguageType GetTypeAtIndex( sal_uInt32 nIndex ) const; + sal_uInt32 AddItem(const OUString& rLanguage, const LanguageType eType) + { + m_aStrings.emplace_back(rLanguage, eType); + return m_aStrings.size(); + } + LanguageType GetValue(sal_uInt32 nIndex) const + { + return (nIndex < m_aStrings.size()) ? m_aStrings[nIndex].second : LANGUAGE_DONTKNOW; + } + sal_uInt32 FindIndex(LanguageType nValue) const + { + const size_t nItems = m_aStrings.size(); + for (size_t i = 0; i < nItems; ++i) + { + if (m_aStrings[i].second == nValue) + return i; + } + return RESARRAY_INDEX_NOTFOUND; + } +}; + +struct theLanguageTable : public rtl::Static< SvtLanguageTableImpl, theLanguageTable > {}; +} + +OUString ApplyLreOrRleEmbedding( const OUString &rText ) +{ + const sal_Int32 nLen = rText.getLength(); + if (nLen == 0) + return OUString(); + + const sal_Unicode cLRE_Embedding = 0x202A; // the start char of an LRE embedding + const sal_Unicode cRLE_Embedding = 0x202B; // the start char of an RLE embedding + const sal_Unicode cPopDirectionalFormat = 0x202C; // the unicode PDF (POP_DIRECTIONAL_FORMAT) char that terminates an LRE/RLE embedding + + // check if there are already embedding characters at the strings start + // if so change nothing + const sal_Unicode cChar = rText[0]; + if (cChar == cLRE_Embedding || cChar == cRLE_Embedding) + return rText; + + // since we only call the function getCharacterDirection + // it does not matter which locale the CharClass is for. + // Thus we can readily make use of SvtSysLocale::GetCharClass() + // which should come at no cost... + SvtSysLocale aSysLocale; + const CharClass &rCharClass = aSysLocale.GetCharClass(); + + // we should look for the first non-neutral LTR or RTL character + // and use that to determine the embedding of the whole text... + // Thus we can avoid to check every character of the text. + bool bFound = false; + bool bIsRtlText = false; + for (sal_Int32 i = 0; i < nLen && !bFound; ++i) + { + i18n::DirectionProperty nDirection = rCharClass.getCharacterDirection( rText, i ); + switch (nDirection) + { + case i18n::DirectionProperty_LEFT_TO_RIGHT : + case i18n::DirectionProperty_LEFT_TO_RIGHT_EMBEDDING : + case i18n::DirectionProperty_LEFT_TO_RIGHT_OVERRIDE : + case i18n::DirectionProperty_EUROPEAN_NUMBER : + case i18n::DirectionProperty_ARABIC_NUMBER : // yes! arabic numbers are written from left to right + { + bIsRtlText = false; + bFound = true; + break; + } + + case i18n::DirectionProperty_RIGHT_TO_LEFT : + case i18n::DirectionProperty_RIGHT_TO_LEFT_ARABIC : + case i18n::DirectionProperty_RIGHT_TO_LEFT_EMBEDDING : + case i18n::DirectionProperty_RIGHT_TO_LEFT_OVERRIDE : + { + bIsRtlText = true; + bFound = true; + break; + } + + default: + { + // nothing to be done, character is considered to be neutral we need to look further ... + } + } + } + + sal_Unicode cStart = cLRE_Embedding; // default is to use LRE embedding characters + if (bIsRtlText) + cStart = cRLE_Embedding; // then use RLE embedding + + // add embedding start and end chars to the text if the direction could be determined + OUString aRes( rText ); + if (bFound) + { + aRes = OUStringChar(cStart) + aRes + + OUStringChar(cPopDirectionalFormat); + } + + return aRes; +} + +static OUString lcl_getDescription( const OUString& rBcp47 ) +{ + // Place in curly brackets, so all on-the-fly tags are grouped together at + // the top of a listbox (but behind the "[None]" entry), and not sprinkled + // all over, which alphabetically might make sense in an English UI only + // anyway. Also a visual indicator that it is a programmatical name, IMHO. + /* TODO: pulling descriptive names (language, script, country, subtags) + * from liblangtag or ISO databases might be nice, but those are English + * only. Maybe ICU, that has translations for language and country. */ + return "{" + rBcp47 + "}"; +} + +SvtLanguageTableImpl::SvtLanguageTableImpl() +{ + for (size_t i = 0; i < SAL_N_ELEMENTS(STR_ARR_SVT_LANGUAGE_TABLE); ++i) + { + m_aStrings.emplace_back(SvtResId(STR_ARR_SVT_LANGUAGE_TABLE[i].first), STR_ARR_SVT_LANGUAGE_TABLE[i].second); + } + + auto xNA = officecfg::VCL::ExtraLanguages::get(); + const uno::Sequence <OUString> rElementNames = xNA->getElementNames(); + for (const OUString& rBcp47 : rElementNames) + { + OUString aName; + sal_Int32 nType = 0; + uno::Reference <container::XNameAccess> xNB; + xNA->getByName(rBcp47) >>= xNB; + bool bSuccess = (xNB->getByName("Name") >>= aName) && + (xNB->getByName("ScriptType") >>= nType); + if (bSuccess) + { + LanguageTag aLang(rBcp47); + LanguageType nLangType = aLang.getLanguageType(); + if (nType <= sal_Int32(LanguageTag::ScriptType::RTL) && nType > sal_Int32(LanguageTag::ScriptType::UNKNOWN)) + aLang.setScriptType(LanguageTag::ScriptType(nType)); + sal_uInt32 nPos = FindIndex(nLangType); + if (nPos == RESARRAY_INDEX_NOTFOUND) + AddItem((aName.isEmpty() ? lcl_getDescription(rBcp47) : aName), nLangType); + } + } +} + +bool SvtLanguageTableImpl::HasType( const LanguageType eType ) const +{ + LanguageType eLang = MsLangId::getReplacementForObsoleteLanguage( eType ); + sal_uInt32 nPos = FindIndex(eLang); + + return RESARRAY_INDEX_NOTFOUND != nPos && nPos < GetEntryCount(); +} + +bool SvtLanguageTable::HasLanguageType( const LanguageType eType ) +{ + return theLanguageTable::get().HasType( eType ); +} + +OUString SvtLanguageTableImpl::GetString( const LanguageType eType ) const +{ + LanguageType eLang = MsLangId::getReplacementForObsoleteLanguage( eType ); + sal_uInt32 nPos = FindIndex(eLang); + + if ( RESARRAY_INDEX_NOTFOUND != nPos && nPos < GetEntryCount() ) + return m_aStrings[nPos].first; + + //Rather than return a fairly useless "Unknown" name, return a geeky but usable-in-a-pinch lang-tag + OUString sLangTag( lcl_getDescription( LanguageTag::convertToBcp47(eType))); + SAL_WARN("svtools.misc", "Language: 0x" + << std::hex << eType + << " with unknown name, so returning lang-tag of: " + << sLangTag); + + // And add it to the table if it is an on-the-fly-id, which it usually is, + // so it is available in all subsequent language boxes. + if (LanguageTag::isOnTheFlyID( eType)) + const_cast<SvtLanguageTableImpl*>(this)->AddItem( sLangTag, eType); + + return sLangTag; +} + +OUString SvtLanguageTable::GetLanguageString( const LanguageType eType ) +{ + return theLanguageTable::get().GetString( eType ); +} + +LanguageType SvtLanguageTableImpl::GetType( const OUString& rStr ) const +{ + LanguageType eType = LANGUAGE_DONTKNOW; + sal_uInt32 nCount = GetEntryCount(); + + for ( sal_uInt32 i = 0; i < nCount; ++i ) + { + if (m_aStrings[i].first == rStr) + { + eType = GetValue(i); + break; + } + } + return eType; +} + +LanguageType SvtLanguageTable::GetLanguageType( const OUString& rStr ) +{ + return theLanguageTable::get().GetType( rStr ); +} + +sal_uInt32 SvtLanguageTableImpl::GetEntryCount() const +{ + return m_aStrings.size(); +} + +sal_uInt32 SvtLanguageTable::GetLanguageEntryCount() +{ + return theLanguageTable::get().GetEntryCount(); +} + + +LanguageType SvtLanguageTableImpl::GetTypeAtIndex( sal_uInt32 nIndex ) const +{ + LanguageType nType = LANGUAGE_DONTKNOW; + if (nIndex < GetEntryCount()) + nType = GetValue(nIndex); + return nType; +} + +LanguageType SvtLanguageTable::GetLanguageTypeAtIndex( sal_uInt32 nIndex ) +{ + return theLanguageTable::get().GetTypeAtIndex( nIndex); +} + + +sal_uInt32 SvtLanguageTable::AddLanguageTag( const LanguageTag& rLanguageTag ) +{ + return theLanguageTable::get().AddItem( lcl_getDescription(rLanguageTag.getBcp47()), + rLanguageTag.getLanguageType()); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/misc/openfiledroptargetlistener.cxx b/svtools/source/misc/openfiledroptargetlistener.cxx new file mode 100644 index 000000000..61d20c0bb --- /dev/null +++ b/svtools/source/misc/openfiledroptargetlistener.cxx @@ -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 . + */ + +#include <svtools/openfiledroptargetlistener.hxx> + +#include <com/sun/star/datatransfer/dnd/DNDConstants.hpp> +#include <com/sun/star/frame/XDispatch.hpp> +#include <com/sun/star/frame/XDispatchProvider.hpp> +#include <com/sun/star/frame/XFrame.hpp> +#include <com/sun/star/beans/PropertyValue.hpp> +#include <com/sun/star/util/URLTransformer.hpp> +#include <com/sun/star/util/XURLTransformer.hpp> + +#include <vcl/transfer.hxx> +#include <sot/filelist.hxx> + +#include <osl/file.hxx> +#include <vcl/svapp.hxx> + +OpenFileDropTargetListener::OpenFileDropTargetListener( const css::uno::Reference< css::uno::XComponentContext >& xContext, + const css::uno::Reference< css::frame::XFrame >& xFrame ) + : m_xContext ( xContext ) + , m_xTargetFrame ( xFrame ) +{ +} + + +OpenFileDropTargetListener::~OpenFileDropTargetListener() +{ + m_xTargetFrame.clear(); + m_xContext.clear(); +} + + +void SAL_CALL OpenFileDropTargetListener::disposing( const css::lang::EventObject& ) +{ + m_xTargetFrame.clear(); + m_xContext.clear(); +} + + +void SAL_CALL OpenFileDropTargetListener::drop( const css::datatransfer::dnd::DropTargetDropEvent& dtde ) +{ + const sal_Int8 nAction = dtde.DropAction; + + try + { + if ( css::datatransfer::dnd::DNDConstants::ACTION_NONE != nAction ) + { + TransferableDataHelper aHelper( dtde.Transferable ); + bool bFormatFound = false; + FileList aFileList; + + // at first check filelist format + if ( aHelper.GetFileList( SotClipboardFormatId::FILE_LIST, aFileList ) ) + { + sal_uLong i, nCount = aFileList.Count(); + for ( i = 0; i < nCount; ++i ) + implts_OpenFile( aFileList.GetFile(i) ); + bFormatFound = true; + } + + // then, if necessary, the file format + OUString aFilePath; + if ( !bFormatFound && aHelper.GetString( SotClipboardFormatId::SIMPLE_FILE, aFilePath ) ) + implts_OpenFile( aFilePath ); + } + dtde.Context->dropComplete( css::datatransfer::dnd::DNDConstants::ACTION_NONE != nAction ); + } + catch( const css::uno::Exception& ) + { + } +} + + +void SAL_CALL OpenFileDropTargetListener::dragEnter( const css::datatransfer::dnd::DropTargetDragEnterEvent& dtdee ) +{ + try + { + implts_BeginDrag( dtdee.SupportedDataFlavors ); + } + catch( const css::uno::Exception& ) + { + } + + dragOver( dtdee ); +} + + +void SAL_CALL OpenFileDropTargetListener::dragExit( const css::datatransfer::dnd::DropTargetEvent& ) +{ + try + { + implts_EndDrag(); + } + catch( const css::uno::Exception& ) + { + } +} + + +void SAL_CALL OpenFileDropTargetListener::dragOver( const css::datatransfer::dnd::DropTargetDragEvent& dtde ) +{ + try + { + bool bAccept = ( implts_IsDropFormatSupported( SotClipboardFormatId::SIMPLE_FILE ) || + implts_IsDropFormatSupported( SotClipboardFormatId::FILE_LIST ) ); + + if ( !bAccept ) + dtde.Context->rejectDrag(); + else + dtde.Context->acceptDrag( css::datatransfer::dnd::DNDConstants::ACTION_COPY ); + } + catch( const css::uno::Exception& ) + { + } +} + + +void SAL_CALL OpenFileDropTargetListener::dropActionChanged( const css::datatransfer::dnd::DropTargetDragEvent& ) +{ +} + +void OpenFileDropTargetListener::implts_BeginDrag( const css::uno::Sequence< css::datatransfer::DataFlavor >& rSupportedDataFlavors ) +{ + /* SAFE { */ + SolarMutexGuard aGuard; + + m_aFormats.clear(); + TransferableDataHelper::FillDataFlavorExVector(rSupportedDataFlavors, m_aFormats); + /* } SAFE */ +} + +void OpenFileDropTargetListener::implts_EndDrag() +{ + /* SAFE { */ + SolarMutexGuard aGuard; + + m_aFormats.clear(); + /* } SAFE */ +} + +bool OpenFileDropTargetListener::implts_IsDropFormatSupported( SotClipboardFormatId nFormat ) +{ + /* SAFE { */ + SolarMutexGuard aGuard; + + for (auto const& format : m_aFormats) + { + if (nFormat == format.mnSotId) + { + return true; + } + } + /* } SAFE */ + + return false; +} + +void OpenFileDropTargetListener::implts_OpenFile( const OUString& rFilePath ) +{ + OUString aFileURL; + if ( osl::FileBase::getFileURLFromSystemPath( rFilePath, aFileURL ) != osl::FileBase::E_None ) + aFileURL = rFilePath; + + ::osl::FileStatus aStatus( osl_FileStatus_Mask_FileURL ); + ::osl::DirectoryItem aItem; + if( ::osl::FileBase::E_None == ::osl::DirectoryItem::get( aFileURL, aItem ) && + ::osl::FileBase::E_None == aItem.getFileStatus( aStatus ) ) + aFileURL = aStatus.getFileURL(); + + // open file + /* SAFE { */ + SolarMutexGuard aGuard; + + css::uno::Reference< css::frame::XFrame > xTargetFrame( m_xTargetFrame.get(), css::uno::UNO_QUERY ); + css::uno::Reference< css::util::XURLTransformer > xParser ( css::util::URLTransformer::create(m_xContext) ); + + if (xTargetFrame.is() && xParser.is()) + { + css::util::URL aURL; + aURL.Complete = aFileURL; + xParser->parseStrict(aURL); + + css::uno::Reference < css::frame::XDispatchProvider > xProvider( xTargetFrame, css::uno::UNO_QUERY ); + // Create a new task or recycle an existing one + css::uno::Reference< css::frame::XDispatch > xDispatcher = xProvider->queryDispatch( aURL, "_default", 0 ); + if ( xDispatcher.is() ) + xDispatcher->dispatch( aURL, css::uno::Sequence < css::beans::PropertyValue >() ); + } + /* } SAFE */ +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/misc/sampletext.cxx b/svtools/source/misc/sampletext.cxx new file mode 100644 index 000000000..a08c2867a --- /dev/null +++ b/svtools/source/misc/sampletext.cxx @@ -0,0 +1,1678 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.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 <svtools/sampletext.hxx> +#include <vcl/font.hxx> +#include <vcl/outdev.hxx> +#include <vcl/virdev.hxx> +#include <vcl/fontcharmap.hxx> +#include <i18nutil/unicode.hxx> +#include <sal/log.hxx> +#include <com/sun/star/i18n/ScriptType.hpp> + +// This should only be used when a commonly used font incorrectly declares its +// coverage. If you add a font here, please leave a note explaining the issue +// that caused it to be added +static UScriptCode lcl_getHardCodedScriptNameForFont (const OutputDevice &rDevice) +{ + const OUString &rName = rDevice.GetFont().GetFamilyName(); + + if (rName == "GB18030 Bitmap") + { + // As of OSX 10.9, the system font "GB18030 Bitmap" incorrectly declares + // that it only covers "Phoenician" when in fact it's a Chinese font. + return USCRIPT_HAN; + } + else if (rName == "BiauKai") + { + // "BiauKai" makes crazy claims to cover BUGINESE, SUNDANESE, etc + // but in fact it's a Traditional Chinese font. + return USCRIPT_TRADITIONAL_HAN; + } + else if (rName == "GungSeo" || rName == "PCMyungjo" || rName == "PilGi") + { + // These have no OS/2 tables, but we know they are Korean fonts. + return USCRIPT_KOREAN; + } + else if (rName == "Hei" || rName == "Kai") + { + // These have no OS/2 tables, but we know they are Chinese fonts. + return USCRIPT_HAN; + } + else if (rName.startsWith("Bangla ")) + { + // "Bangla Sangam MN" claims it supports MALAYALAM, but it doesn't + // "Bangla MN" claims just DEVANAGARI and not an additional BENGALI + return USCRIPT_BENGALI; + } + else if (rName.startsWith("Gurmukhi ")) + { + // "Gurmukhi MN" claims it supports TAMIL, but it doesn't + return USCRIPT_GURMUKHI; + } + else if (rName.startsWith("Kannada ")) + { + // "Kannada MN" claims it supports TAMIL, but it doesn't + return USCRIPT_KANNADA; + } + else if (rName.startsWith("Lao ")) + { + // "Lao Sangam MN" claims it supports TAMIL, but it doesn't + return USCRIPT_LAO; + } + else if (rName.startsWith("Malayalam ")) + { + // "Malayalam MN" claims it supports TAMIL, but it doesn't + return USCRIPT_MALAYALAM; + } + else if (rName.startsWith("Sinhala ")) + { + // "Sinhala MN" claims it supports CYRILLIC + return USCRIPT_SINHALA; + } + else if (rName.startsWith("Telugu ")) + { + // "Telugu MN" claims it supports TAMIL, but it doesn't + return USCRIPT_TELUGU; + } + else if (rName.startsWith("Myanmar ")) + { + return USCRIPT_MYANMAR; + } + else if (rName == "InaiMathi") + { + // "InaiMathi" claims it supports GOTHIC and CJK_UNIFIED_IDEOGRAPHS as well as + // TAMIL, but it doesn't + return USCRIPT_TAMIL; + } + else if (rName == "Hannotate TC" || rName == "HanziPen TC" || rName == "Heiti TC" || rName == "Weibei TC") + { + // These fonts claim support for ARMENIAN and a bunch of other stuff they don't support + return USCRIPT_TRADITIONAL_HAN; + } + else if (rName == "Hannotate SC" || rName == "HanziPen SC" || rName == "Heiti SC" || rName == "Weibei SC") + { + // These fonts claim support for ARMENIAN and a bunch of other stuff they don't support + return USCRIPT_SIMPLIFIED_HAN; + } + + return USCRIPT_INVALID_CODE; +} + +bool isSymbolFont(const vcl::Font &rFont) +{ + return (rFont.GetCharSet() == RTL_TEXTENCODING_SYMBOL) || + rFont.GetFamilyName().equalsIgnoreAsciiCase("Apple Color Emoji") || + rFont.GetFamilyName().equalsIgnoreAsciiCase("cmsy10") || + rFont.GetFamilyName().equalsIgnoreAsciiCase("cmex10") || + rFont.GetFamilyName().equalsIgnoreAsciiCase("esint10") || + rFont.GetFamilyName().equalsIgnoreAsciiCase("feta26") || + rFont.GetFamilyName().equalsIgnoreAsciiCase("jsMath-cmsy10") || + rFont.GetFamilyName().equalsIgnoreAsciiCase("jsMath-cmex10") || + rFont.GetFamilyName().equalsIgnoreAsciiCase("msam10") || + rFont.GetFamilyName().equalsIgnoreAsciiCase("msbm10") || + rFont.GetFamilyName().equalsIgnoreAsciiCase("wasy10") || + rFont.GetFamilyName().equalsIgnoreAsciiCase("Denemo") || + rFont.GetFamilyName().equalsIgnoreAsciiCase("GlyphBasic1") || + rFont.GetFamilyName().equalsIgnoreAsciiCase("GlyphBasic2") || + rFont.GetFamilyName().equalsIgnoreAsciiCase("GlyphBasic3") || + rFont.GetFamilyName().equalsIgnoreAsciiCase("GlyphBasic4") || + rFont.GetFamilyName().equalsIgnoreAsciiCase("Letters Laughing") || + rFont.GetFamilyName().equalsIgnoreAsciiCase("MusiQwik") || + rFont.GetFamilyName().equalsIgnoreAsciiCase("MusiSync") || + rFont.GetFamilyName().equalsIgnoreAsciiCase("stmary10") || + rFont.GetFamilyName().equalsIgnoreAsciiCase("Symbol") || + rFont.GetFamilyName().equalsIgnoreAsciiCase("Webdings") || + rFont.GetFamilyName().equalsIgnoreAsciiCase("Wingdings") || + rFont.GetFamilyName().equalsIgnoreAsciiCase("Wingdings 2") || + rFont.GetFamilyName().equalsIgnoreAsciiCase("Wingdings 3") || + rFont.GetFamilyName().equalsIgnoreAsciiCase("Bookshelf Symbol 7") || + rFont.GetFamilyName().startsWith("STIXIntegrals") || + rFont.GetFamilyName().startsWith("STIXNonUnicode") || + rFont.GetFamilyName().startsWith("STIXSize") || + rFont.GetFamilyName().startsWith("STIXVariants") || + IsStarSymbol(rFont.GetFamilyName()); +} + +bool canRenderNameOfSelectedFont(OutputDevice const &rDevice) +{ + const vcl::Font &rFont = rDevice.GetFont(); + return !isSymbolFont(rFont) && ( -1 == rDevice.HasGlyphs(rFont, rFont.GetFamilyName()) ); +} + +OUString makeShortRepresentativeSymbolTextForSelectedFont(OutputDevice const &rDevice) +{ + if (rDevice.GetFont().GetFamilyName() == "Symbol") + { + static const sal_Unicode aImplAppleSymbolText[] = { + 0x03BC, 0x2202, 0x2211, 0x220F, 0x03C0, 0x222B, 0x03A9, 0x221A, 0}; + OUString sSampleText(aImplAppleSymbolText); + bool bHasSampleTextGlyphs = (-1 == rDevice.HasGlyphs(rDevice.GetFont(), sSampleText)); + //It's the Apple version + if (bHasSampleTextGlyphs) + return OUString(aImplAppleSymbolText); + static const sal_Unicode aImplAdobeSymbolText[] = { + 0xF06D, 0xF0B6, 0xF0E5, 0xF0D5, 0xF070, 0xF0F2, 0xF057, 0xF0D6, 0}; + return OUString(aImplAdobeSymbolText); + } + + const bool bOpenSymbol = IsStarSymbol(rDevice.GetFont().GetFamilyName()); + + if (!bOpenSymbol) + { + FontCharMapRef xFontCharMap; + bool bHasCharMap = rDevice.GetFontCharMap(xFontCharMap); + if( bHasCharMap ) + { + // use some sample characters available in the font + sal_Unicode aText[8]; + + // start just above the PUA used by most symbol fonts + sal_uInt32 cNewChar = 0xFF00; + + const int nMaxCount = SAL_N_ELEMENTS(aText) - 1; + int nSkip = xFontCharMap->GetCharCount() / nMaxCount; + if( nSkip > 10 ) + nSkip = 10; + else if( nSkip <= 0 ) + nSkip = 1; + for( int i = 0; i < nMaxCount; ++i ) + { + sal_uInt32 cOldChar = cNewChar; + for( int j = nSkip; --j >= 0; ) + cNewChar = xFontCharMap->GetPrevChar( cNewChar ); + if( cOldChar == cNewChar ) + break; + aText[ i ] = static_cast<sal_Unicode>(cNewChar); // TODO: support UCS4 samples + aText[ i+1 ] = 0; + } + + return OUString(aText); + } + } + + static const sal_Unicode aImplSymbolFontText[] = { + 0xF021,0xF032,0xF043,0xF054,0xF065,0xF076,0xF0B7,0xF0C8,0}; + static const sal_Unicode aImplStarSymbolText[] = { + 0x2702,0x2708,0x270D,0xE033,0x2211,0x2288,0}; + const sal_Unicode* pText = bOpenSymbol ? aImplStarSymbolText : aImplSymbolFontText; + OUString sSampleText(pText); + bool bHasSampleTextGlyphs = (-1 == rDevice.HasGlyphs(rDevice.GetFont(), sSampleText)); + return bHasSampleTextGlyphs ? sSampleText : OUString(); +} + +//These ones are typically for use in the font dropdown box beside the +//fontname, so say things roughly like "Script/Alphabet/Name-Of-Major-Language" + +//Here we don't always know the language of course, only the script that can be +//written with the font. Often that's one single language written in that +//script, or a handful of related languages where the name of the script is the +//same between languages, or the name in the major language is known by most +//readers of the minor languages, e.g. Yiddish is written with the HEBREW +//script as well, the vast majority of Yiddish readers will be able to read +//Hebrew as well. +OUString makeShortRepresentativeTextForScript(UScriptCode eScript) +{ + OUString sSampleText; + switch (eScript) + { + case USCRIPT_GREEK: + { + static const sal_Unicode aGrek[] = { + 0x0391, 0x03BB, 0x03C6, 0x03AC, 0x03B2, 0x03B7, 0x03C4, 0x03BF + }; + sSampleText = OUString(aGrek, SAL_N_ELEMENTS(aGrek)); + break; + } + case USCRIPT_HEBREW: + { + static const sal_Unicode aHebr[] = { + 0x05D0, 0x05B8, 0x05DC, 0x05B6, 0x05E3, 0x05BE, 0x05D1, 0x05B5, + 0x05BC, 0x05D9, 0x05EA, 0x0020, 0x05E2, 0x05B4, 0x05D1, 0x05B0, + 0x05E8, 0x05B4, 0x05D9 + }; + sSampleText = OUString(aHebr, SAL_N_ELEMENTS(aHebr)); + break; + } + case USCRIPT_ARABIC: + { + static const sal_Unicode aArab[] = { + 0x0623, 0x0628, 0x062C, 0x062F, 0x064A, 0x0629, 0x0020, 0x0639, + 0x0631, 0x0628, 0x064A, 0x0629 + }; + sSampleText = OUString(aArab, SAL_N_ELEMENTS(aArab)); + break; + } + case USCRIPT_ARMENIAN: + { + static const sal_Unicode aArmenian[] = { + 0x0561, 0x0575, 0x0562, 0x0578, 0x0582, 0x0562, 0x0565, + 0x0576 + }; + sSampleText = OUString(aArmenian, SAL_N_ELEMENTS(aArmenian)); + break; + } + case USCRIPT_DEVANAGARI: + { + static const sal_Unicode aDeva[] = { + 0x0926, 0x0947, 0x0935, 0x0928, 0x093E, 0x0917, 0x0930, 0x0940 + }; + sSampleText = OUString(aDeva, SAL_N_ELEMENTS(aDeva)); + break; + } + case USCRIPT_BENGALI: + { + static const sal_Unicode aBeng[] = { + 0x09AC, 0x09BE, 0x0982, 0x09B2, 0x09BE, 0x0020, 0x09B2, 0x09BF, + 0x09AA, 0x09BF + }; + sSampleText = OUString(aBeng, SAL_N_ELEMENTS(aBeng)); + break; + } + case USCRIPT_GURMUKHI: + { + static const sal_Unicode aGuru[] = { + 0x0A17, 0x0A41, 0x0A30, 0x0A2E, 0x0A41, 0x0A16, 0x0A40 + }; + sSampleText = OUString(aGuru, SAL_N_ELEMENTS(aGuru)); + break; + } + case USCRIPT_GUJARATI: + { + static const sal_Unicode aGujr[] = { + 0x0A97, 0x0AC1, 0x0A9C, 0x0AB0, 0x0ABE, 0x0AA4, 0x0aC0, 0x0020, + 0x0AB2, 0x0ABF, 0x0AAA, 0x0ABF + }; + sSampleText = OUString(aGujr, SAL_N_ELEMENTS(aGujr)); + break; + } + case USCRIPT_ORIYA: + { + static const sal_Unicode aOrya[] = { + 0x0B09, 0x0B24, 0x0B4D, 0x0B15, 0x0B33, 0x0020, 0x0B32, 0x0B3F, + 0x0B2A, 0x0B3F + }; + sSampleText = OUString(aOrya, SAL_N_ELEMENTS(aOrya)); + break; + } + case USCRIPT_TAMIL: + { + static const sal_Unicode aTaml[] = { + 0x0B85, 0x0BB0, 0x0BBF, 0x0B9A, 0x0BCD, 0x0B9A, 0x0BC1, 0x0BB5, + 0x0B9F, 0x0BBF + }; + sSampleText = OUString(aTaml, SAL_N_ELEMENTS(aTaml)); + break; + } + case USCRIPT_TELUGU: + { + static const sal_Unicode aTelu[] = { + 0x0C24, 0x0C46, 0x0C32, 0x0C41, 0x0C17, 0x0C41 + }; + sSampleText = OUString(aTelu, SAL_N_ELEMENTS(aTelu)); + break; + } + case USCRIPT_KANNADA: + { + static const sal_Unicode aKnda[] = { + 0x0C95, 0x0CA8, 0x0CCD, 0x0CA8, 0x0CA1, 0x0020, 0x0CB2, 0x0CBF, + 0x0CAA, 0x0CBF + }; + sSampleText = OUString(aKnda, SAL_N_ELEMENTS(aKnda)); + break; + } + case USCRIPT_MALAYALAM: + { + static const sal_Unicode aMlym[] = { + 0x0D2E, 0x0D32, 0x0D2F, 0x0D3E, 0x0D33, 0x0D32, 0x0D3F, 0x0D2A, + 0x0D3F + }; + sSampleText = OUString(aMlym, SAL_N_ELEMENTS(aMlym)); + break; + } + case USCRIPT_THAI: + { + static const sal_Unicode aThai[] = { + 0x0E2D, 0x0E31, 0x0E01, 0x0E29, 0x0E23, 0x0E44, 0x0E17, 0x0E22 + }; + sSampleText = OUString(aThai, SAL_N_ELEMENTS(aThai)); + break; + } + case USCRIPT_LAO: + { + static const sal_Unicode aLao[] = { + 0x0EAD, 0x0EB1, 0x0E81, 0x0EAA, 0x0EAD, 0x0E99, 0x0EA5, 0x0EB2, + 0x0EA7 + }; + sSampleText = OUString(aLao, SAL_N_ELEMENTS(aLao)); + break; + } + case USCRIPT_GEORGIAN: + { + static const sal_Unicode aGeorgian[] = { + 0x10D3, 0x10D0, 0x10DB, 0x10EC, 0x10D4, 0x10E0, 0x10DA, 0x10DD, + 0x10D1, 0x10D0 + }; + sSampleText = OUString(aGeorgian, SAL_N_ELEMENTS(aGeorgian)); + break; + } + case USCRIPT_HANGUL: + case USCRIPT_KOREAN: + { + static const sal_Unicode aHang[] = { + 0xD55C, 0xAE00 + }; + sSampleText = OUString(aHang, SAL_N_ELEMENTS(aHang)); + break; + } + case USCRIPT_TIBETAN: + { + static const sal_Unicode aTibt[] = { + 0x0F51, 0x0F56, 0x0F74, 0x0F0B, 0x0F45, 0x0F53, 0x0F0B + }; + sSampleText = OUString(aTibt, SAL_N_ELEMENTS(aTibt)); + break; + } + case USCRIPT_SYRIAC: + { + static const sal_Unicode aSyri[] = { + 0x0723, 0x071B, 0x072A, 0x0722, 0x0713, 0x0720, 0x0710 + }; + sSampleText = OUString(aSyri, SAL_N_ELEMENTS(aSyri)); + break; + } + case USCRIPT_THAANA: + { + static const sal_Unicode aThaa[] = { + 0x078C, 0x07A7, 0x0782, 0x07A6 + }; + sSampleText = OUString(aThaa, SAL_N_ELEMENTS(aThaa)); + break; + } + case USCRIPT_SINHALA: + { + static const sal_Unicode aSinh[] = { + 0x0DC1, 0x0DD4, 0x0DAF, 0x0DCA, 0x0DB0, 0x0020, 0x0DC3, 0x0DD2, + 0x0D82, 0x0DC4, 0x0DBD + }; + sSampleText = OUString(aSinh, SAL_N_ELEMENTS(aSinh)); + break; + } + case USCRIPT_MYANMAR: + { + static const sal_Unicode aMymr[] = { + 0x1019, 0x103C, 0x1014, 0x103A, 0x1019, 0x102C, 0x1021, 0x1000, + 0x1039, 0x1001, 0x101B, 0x102C + }; + sSampleText = OUString(aMymr, SAL_N_ELEMENTS(aMymr)); + break; + } + case USCRIPT_ETHIOPIC: + { + static const sal_Unicode aEthi[] = { + 0x130D, 0x12D5, 0x12DD + }; + sSampleText = OUString(aEthi, SAL_N_ELEMENTS(aEthi)); + break; + } + case USCRIPT_CHEROKEE: + { + static const sal_Unicode aCher[] = { + 0x13D7, 0x13AA, 0x13EA, 0x13B6, 0x13D9, 0x13D7 + }; + sSampleText = OUString(aCher, SAL_N_ELEMENTS(aCher)); + break; + } + case USCRIPT_KHMER: + { + static const sal_Unicode aKhmr[] = { + 0x17A2, 0x1780, 0x17D2, 0x1781, 0x179A, 0x1780, 0x17D2, 0x179A, + 0x1798, 0x1781, 0x17C1, 0x1798, 0x179A, 0x1797, 0x17B6, 0x179F, + 0x17B6 + }; + sSampleText = OUString(aKhmr, SAL_N_ELEMENTS(aKhmr)); + break; + } + case USCRIPT_MONGOLIAN: + { + static const sal_Unicode aMongolian[] = { + 0x182A, 0x1822, 0x1834, 0x1822, 0x182D, 0x180C + }; + sSampleText = OUString(aMongolian, SAL_N_ELEMENTS(aMongolian)); + break; + } + case USCRIPT_TAGALOG: + { + static const sal_Unicode aTagalog[] = { + 0x170A, 0x170A, 0x170C, 0x1712 + }; + sSampleText = OUString(aTagalog, SAL_N_ELEMENTS(aTagalog)); + break; + } + case USCRIPT_NEW_TAI_LUE: + { + static const sal_Unicode aTalu[] = { + 0x1991, 0x19BA, 0x199F, 0x19B9, 0x19C9 + }; + sSampleText = OUString(aTalu, SAL_N_ELEMENTS(aTalu)); + break; + } + case USCRIPT_TRADITIONAL_HAN: + { + static const sal_Unicode aHant[] = { + 0x7E41 + }; + sSampleText = OUString(aHant, SAL_N_ELEMENTS(aHant)); + break; + } + case USCRIPT_SIMPLIFIED_HAN: + { + static const sal_Unicode aHans[] = { + 0x7B80 + }; + sSampleText = OUString(aHans, SAL_N_ELEMENTS(aHans)); + break; + } + case USCRIPT_HAN: + { + static const sal_Unicode aSimplifiedAndTraditionalChinese[] = { + 0x7B80, 0x7E41 + }; + sSampleText = OUString(aSimplifiedAndTraditionalChinese, + SAL_N_ELEMENTS(aSimplifiedAndTraditionalChinese)); + break; + } + case USCRIPT_JAPANESE: + { + static const sal_Unicode aJpan[] = { + 0x65E5, 0x672C, 0x8A9E + }; + sSampleText = OUString(aJpan, SAL_N_ELEMENTS(aJpan)); + break; + } + case USCRIPT_YI: + { + static const sal_Unicode aYiii[] = { + 0xA188, 0xA320, 0xA071, 0xA0B7 + }; + sSampleText = OUString(aYiii, SAL_N_ELEMENTS(aYiii)); + break; + } + case USCRIPT_PHAGS_PA: + { + static const sal_Unicode aPhag[] = { + 0xA84F, 0xA861, 0xA843, 0x0020, 0xA863, 0xA861, 0xA859, 0x0020, + 0xA850, 0xA85C, 0xA85E + }; + sSampleText = OUString(aPhag, SAL_N_ELEMENTS(aPhag)); + break; + } + case USCRIPT_TAI_LE: + { + static const sal_Unicode aTale[] = { + 0x1956, 0x196D, 0x1970, 0x1956, 0x196C, 0x1973, 0x1951, 0x1968, + 0x1952, 0x1970 + }; + sSampleText = OUString(aTale, SAL_N_ELEMENTS(aTale)); + break; + } + case USCRIPT_LATIN: + sSampleText = "Lorem ipsum"; + break; + default: + break; + } + return sSampleText; +} + +static OUString makeRepresentativeTextForScript(UScriptCode eScript) +{ + OUString sSampleText; + switch (eScript) + { + case USCRIPT_TRADITIONAL_HAN: + case USCRIPT_SIMPLIFIED_HAN: + case USCRIPT_HAN: + { + //Three Character Classic + static const sal_Unicode aZh[] = { + 0x4EBA, 0x4E4B, 0x521D, 0x0020, 0x6027, 0x672C, 0x5584 + }; + sSampleText = OUString(aZh, SAL_N_ELEMENTS(aZh)); + break; + } + case USCRIPT_JAPANESE: + { + //'Beautiful Japanese' + static const sal_Unicode aJa[] = { + 0x7F8E, 0x3057, 0x3044, 0x65E5, 0x672C, 0x8A9E + }; + sSampleText = OUString(aJa, SAL_N_ELEMENTS(aJa)); + break; + } + case USCRIPT_KOREAN: + case USCRIPT_HANGUL: + { + //The essential condition for... + static const sal_Unicode aKo[] = { + 0xD0A4, 0xC2A4, 0xC758, 0x0020, 0xACE0, 0xC720, 0xC870, + 0xAC74, 0xC740 + }; + sSampleText = OUString(aKo, SAL_N_ELEMENTS(aKo)); + break; + } + default: + break; + } + + if (sSampleText.isEmpty()) + sSampleText = makeShortRepresentativeTextForScript(eScript); + return sSampleText; +} + +OUString makeShortMinimalTextForScript(UScriptCode eScript) +{ + OUString sSampleText; + switch (eScript) + { + case USCRIPT_GREEK: + { + static const sal_Unicode aGrek[] = { + 0x0391, 0x0392 + }; + sSampleText = OUString(aGrek, SAL_N_ELEMENTS(aGrek)); + break; + } + case USCRIPT_HEBREW: + { + static const sal_Unicode aHebr[] = { + 0x05D0, 0x05D1 + }; + sSampleText = OUString(aHebr, SAL_N_ELEMENTS(aHebr)); + break; + } + default: + break; + } + return sSampleText; +} + +static OUString makeMinimalTextForScript(UScriptCode eScript) +{ + return makeShortMinimalTextForScript(eScript); +} + +//These ones are typically for use in the font preview window in format +//character + +//There we generally know the language. Though its possible for the language to +//be "none". + +//Currently we fall back to makeShortRepresentativeTextForScript when we don't +//have suitable strings +static OUString makeRepresentativeTextForLanguage(LanguageType eLang) +{ + OUString sRet; + LanguageType pri = primary(eLang); + if( pri == primary(LANGUAGE_ARMENIAN) ) + sRet = makeRepresentativeTextForScript(USCRIPT_ARMENIAN); + else if( pri == primary(LANGUAGE_CHINESE) ) + sRet = makeRepresentativeTextForScript(USCRIPT_HAN); + else if( pri == primary(LANGUAGE_GREEK) ) + sRet = makeRepresentativeTextForScript(USCRIPT_GREEK); + else if( pri.anyOf( + primary(LANGUAGE_HEBREW), + primary(LANGUAGE_YIDDISH)) ) + sRet = makeRepresentativeTextForScript(USCRIPT_HEBREW); + else if( pri == primary(LANGUAGE_ARABIC_SAUDI_ARABIA) ) + sRet = makeRepresentativeTextForScript(USCRIPT_ARABIC); + else if( pri == primary(LANGUAGE_HINDI) ) + sRet = makeRepresentativeTextForScript(USCRIPT_DEVANAGARI); + else if( pri == primary(LANGUAGE_ASSAMESE) ) + { + static const sal_Unicode aAs[] = { + 0x0985, 0x09B8, 0x09AE, 0x09C0, 0x09AF, 0x09BC, 0x09BE, + 0x0020, 0x0986, 0x0996, 0x09F0 + }; + sRet = OUString(aAs, SAL_N_ELEMENTS(aAs)); + } + else if( pri == primary(LANGUAGE_BENGALI) ) + sRet = makeRepresentativeTextForScript(USCRIPT_BENGALI); + else if( pri == primary(LANGUAGE_PUNJABI) ) + sRet = makeRepresentativeTextForScript(USCRIPT_GURMUKHI); + else if( pri == primary(LANGUAGE_GUJARATI) ) + sRet = makeRepresentativeTextForScript(USCRIPT_GUJARATI); + else if( pri == primary(LANGUAGE_ODIA) ) + sRet = makeRepresentativeTextForScript(USCRIPT_ORIYA); + else if( pri == primary(LANGUAGE_TAMIL) ) + sRet = makeRepresentativeTextForScript(USCRIPT_TAMIL); + else if( pri == primary(LANGUAGE_TELUGU) ) + sRet = makeRepresentativeTextForScript(USCRIPT_TELUGU); + else if( pri == primary(LANGUAGE_KANNADA) ) + sRet = makeRepresentativeTextForScript(USCRIPT_KANNADA); + else if( pri == primary(LANGUAGE_MALAYALAM) ) + sRet = makeRepresentativeTextForScript(USCRIPT_MALAYALAM); + else if( pri == primary(LANGUAGE_THAI) ) + sRet = makeRepresentativeTextForScript(USCRIPT_THAI); + else if( pri == primary(LANGUAGE_LAO) ) + sRet = makeRepresentativeTextForScript(USCRIPT_LAO); + else if( pri == primary(LANGUAGE_GEORGIAN) ) + sRet = makeRepresentativeTextForScript(USCRIPT_GEORGIAN); + else if( pri == primary(LANGUAGE_KOREAN) ) + sRet = makeRepresentativeTextForScript(USCRIPT_KOREAN); + else if( pri == primary(LANGUAGE_TIBETAN) ) + sRet = makeRepresentativeTextForScript(USCRIPT_TIBETAN); + else if( pri == primary(LANGUAGE_SYRIAC) ) + sRet = makeRepresentativeTextForScript(USCRIPT_SYRIAC); + else if( pri == primary(LANGUAGE_SINHALESE_SRI_LANKA) ) + sRet = makeRepresentativeTextForScript(USCRIPT_SINHALA); + else if( pri == primary(LANGUAGE_BURMESE) ) + sRet = makeRepresentativeTextForScript(USCRIPT_MYANMAR); + else if( pri == primary(LANGUAGE_AMHARIC_ETHIOPIA) ) + sRet = makeRepresentativeTextForScript(USCRIPT_ETHIOPIC); + else if( pri == primary(LANGUAGE_CHEROKEE_UNITED_STATES) ) + sRet = makeRepresentativeTextForScript(USCRIPT_CHEROKEE); + else if( pri == primary(LANGUAGE_KHMER) ) + sRet = makeRepresentativeTextForScript(USCRIPT_KHMER); + else if( pri == primary(LANGUAGE_MONGOLIAN_MONGOLIAN_LSO) ) + { + if (eLang.anyOf( + LANGUAGE_MONGOLIAN_MONGOLIAN_MONGOLIA, + LANGUAGE_MONGOLIAN_MONGOLIAN_CHINA, + LANGUAGE_MONGOLIAN_MONGOLIAN_LSO)) + sRet = makeRepresentativeTextForScript(USCRIPT_MONGOLIAN); + } + else if( pri == primary(LANGUAGE_JAPANESE) ) + sRet = makeRepresentativeTextForScript(USCRIPT_JAPANESE); + else if( pri == primary(LANGUAGE_YI) ) + sRet = makeRepresentativeTextForScript(USCRIPT_YI); + else if( pri == primary(LANGUAGE_GAELIC_IRELAND) ) + { + static const sal_Unicode aGa[] = { + 'T', 0x00E9, 'a', 'c', 's', ' ', 'S', 'a', 'm', 'p', 'l', 'a', 'c', 'h' + }; + sRet = OUString(aGa, SAL_N_ELEMENTS(aGa)); + } + + return sRet; +} + +namespace +{ +#if OSL_DEBUG_LEVEL > 0 + void lcl_dump_unicode_coverage(const std::optional<std::bitset<vcl::UnicodeCoverage::MAX_UC_ENUM>> &roIn) + { + if (!roIn) + { + SAL_INFO("svtools", "<NOTHING>"); + return; + } + auto & rIn(*roIn); + if (rIn.none()) + { + SAL_INFO("svtools", "<NONE>"); + return; + } + if (rIn[vcl::UnicodeCoverage::BASIC_LATIN]) + SAL_INFO("svtools", "BASIC_LATIN"); + if (rIn[vcl::UnicodeCoverage::LATIN_1_SUPPLEMENT]) + SAL_INFO("svtools", "LATIN_1_SUPPLEMENT"); + if (rIn[vcl::UnicodeCoverage::LATIN_EXTENDED_A]) + SAL_INFO("svtools", "LATIN_EXTENDED_A"); + if (rIn[vcl::UnicodeCoverage::LATIN_EXTENDED_B]) + SAL_INFO("svtools", "LATIN_EXTENDED_B"); + if (rIn[vcl::UnicodeCoverage::IPA_EXTENSIONS]) + SAL_INFO("svtools", "IPA_EXTENSIONS"); + if (rIn[vcl::UnicodeCoverage::SPACING_MODIFIER_LETTERS]) + SAL_INFO("svtools", "SPACING_MODIFIER_LETTERS"); + if (rIn[vcl::UnicodeCoverage::COMBINING_DIACRITICAL_MARKS]) + SAL_INFO("svtools", "COMBINING_DIACRITICAL_MARKS"); + if (rIn[vcl::UnicodeCoverage::GREEK_AND_COPTIC]) + SAL_INFO("svtools", "GREEK_AND_COPTIC"); + if (rIn[vcl::UnicodeCoverage::COPTIC]) + SAL_INFO("svtools", "COPTIC"); + if (rIn[vcl::UnicodeCoverage::CYRILLIC]) + SAL_INFO("svtools", "CYRILLIC"); + if (rIn[vcl::UnicodeCoverage::ARMENIAN]) + SAL_INFO("svtools", "ARMENIAN"); + if (rIn[vcl::UnicodeCoverage::HEBREW]) + SAL_INFO("svtools", "HEBREW"); + if (rIn[vcl::UnicodeCoverage::VAI]) + SAL_INFO("svtools", "VAI"); + if (rIn[vcl::UnicodeCoverage::ARABIC]) + SAL_INFO("svtools", "ARABIC"); + if (rIn[vcl::UnicodeCoverage::NKO]) + SAL_INFO("svtools", "NKO"); + if (rIn[vcl::UnicodeCoverage::DEVANAGARI]) + SAL_INFO("svtools", "DEVANAGARI"); + if (rIn[vcl::UnicodeCoverage::BENGALI]) + SAL_INFO("svtools", "BENGALI"); + if (rIn[vcl::UnicodeCoverage::GURMUKHI]) + SAL_INFO("svtools", "GURMUKHI"); + if (rIn[vcl::UnicodeCoverage::GUJARATI]) + SAL_INFO("svtools", "GUJARATI"); + if (rIn[vcl::UnicodeCoverage::ODIA]) + SAL_INFO("svtools", "ODIA"); + if (rIn[vcl::UnicodeCoverage::TAMIL]) + SAL_INFO("svtools", "TAMIL"); + if (rIn[vcl::UnicodeCoverage::TELUGU]) + SAL_INFO("svtools", "TELUGU"); + if (rIn[vcl::UnicodeCoverage::KANNADA]) + SAL_INFO("svtools", "KANNADA"); + if (rIn[vcl::UnicodeCoverage::MALAYALAM]) + SAL_INFO("svtools", "MALAYALAM"); + if (rIn[vcl::UnicodeCoverage::THAI]) + SAL_INFO("svtools", "THAI"); + if (rIn[vcl::UnicodeCoverage::LAO]) + SAL_INFO("svtools", "LAO"); + if (rIn[vcl::UnicodeCoverage::GEORGIAN]) + SAL_INFO("svtools", "GEORGIAN"); + if (rIn[vcl::UnicodeCoverage::BALINESE]) + SAL_INFO("svtools", "BALINESE"); + if (rIn[vcl::UnicodeCoverage::HANGUL_JAMO]) + SAL_INFO("svtools", "HANGUL_JAMO"); + if (rIn[vcl::UnicodeCoverage::LATIN_EXTENDED_ADDITIONAL]) + SAL_INFO("svtools", "LATIN_EXTENDED_ADDITIONAL"); + if (rIn[vcl::UnicodeCoverage::GREEK_EXTENDED]) + SAL_INFO("svtools", "GREEK_EXTENDED"); + if (rIn[vcl::UnicodeCoverage::GENERAL_PUNCTUATION]) + SAL_INFO("svtools", "GENERAL_PUNCTUATION"); + if (rIn[vcl::UnicodeCoverage::SUPERSCRIPTS_AND_SUBSCRIPTS]) + SAL_INFO("svtools", "SUPERSCRIPTS_AND_SUBSCRIPTS"); + if (rIn[vcl::UnicodeCoverage::CURRENCY_SYMBOLS]) + SAL_INFO("svtools", "CURRENCY_SYMBOLS"); + if (rIn[vcl::UnicodeCoverage::COMBINING_DIACRITICAL_MARKS_FOR_SYMBOLS]) + SAL_INFO("svtools", "COMBINING_DIACRITICAL_MARKS_FOR_SYMBOLS"); + if (rIn[vcl::UnicodeCoverage::LETTERLIKE_SYMBOLS]) + SAL_INFO("svtools", "LETTERLIKE_SYMBOLS"); + if (rIn[vcl::UnicodeCoverage::NUMBER_FORMS]) + SAL_INFO("svtools", "NUMBER_FORMS"); + if (rIn[vcl::UnicodeCoverage::ARROWS]) + SAL_INFO("svtools", "ARROWS"); + if (rIn[vcl::UnicodeCoverage::MATHEMATICAL_OPERATORS]) + SAL_INFO("svtools", "MATHEMATICAL_OPERATORS"); + if (rIn[vcl::UnicodeCoverage::MISCELLANEOUS_TECHNICAL]) + SAL_INFO("svtools", "MISCELLANEOUS_TECHNICAL"); + if (rIn[vcl::UnicodeCoverage::CONTROL_PICTURES]) + SAL_INFO("svtools", "CONTROL_PICTURES"); + if (rIn[vcl::UnicodeCoverage::OPTICAL_CHARACTER_RECOGNITION]) + SAL_INFO("svtools", "OPTICAL_CHARACTER_RECOGNITION"); + if (rIn[vcl::UnicodeCoverage::ENCLOSED_ALPHANUMERICS]) + SAL_INFO("svtools", "ENCLOSED_ALPHANUMERICS"); + if (rIn[vcl::UnicodeCoverage::BOX_DRAWING]) + SAL_INFO("svtools", "BOX_DRAWING"); + if (rIn[vcl::UnicodeCoverage::BLOCK_ELEMENTS]) + SAL_INFO("svtools", "BLOCK_ELEMENTS"); + if (rIn[vcl::UnicodeCoverage::GEOMETRIC_SHAPES]) + SAL_INFO("svtools", "GEOMETRIC_SHAPES"); + if (rIn[vcl::UnicodeCoverage::MISCELLANEOUS_SYMBOLS]) + SAL_INFO("svtools", "MISCELLANEOUS_SYMBOLS"); + if (rIn[vcl::UnicodeCoverage::DINGBATS]) + SAL_INFO("svtools", "DINGBATS"); + if (rIn[vcl::UnicodeCoverage::CJK_SYMBOLS_AND_PUNCTUATION]) + SAL_INFO("svtools", "CJK_SYMBOLS_AND_PUNCTUATION"); + if (rIn[vcl::UnicodeCoverage::HIRAGANA]) + SAL_INFO("svtools", "HIRAGANA"); + if (rIn[vcl::UnicodeCoverage::KATAKANA]) + SAL_INFO("svtools", "KATAKANA"); + if (rIn[vcl::UnicodeCoverage::BOPOMOFO]) + SAL_INFO("svtools", "BOPOMOFO"); + if (rIn[vcl::UnicodeCoverage::HANGUL_COMPATIBILITY_JAMO]) + SAL_INFO("svtools", "HANGUL_COMPATIBILITY_JAMO"); + if (rIn[vcl::UnicodeCoverage::PHAGS_PA]) + SAL_INFO("svtools", "PHAGS_PA"); + if (rIn[vcl::UnicodeCoverage::ENCLOSED_CJK_LETTERS_AND_MONTHS]) + SAL_INFO("svtools", "ENCLOSED_CJK_LETTERS_AND_MONTHS"); + if (rIn[vcl::UnicodeCoverage::CJK_COMPATIBILITY]) + SAL_INFO("svtools", "CJK_COMPATIBILITY"); + if (rIn[vcl::UnicodeCoverage::HANGUL_SYLLABLES]) + SAL_INFO("svtools", "HANGUL_SYLLABLES"); + if (rIn[vcl::UnicodeCoverage::NONPLANE_0]) + SAL_INFO("svtools", "NONPLANE_0"); + if (rIn[vcl::UnicodeCoverage::PHOENICIAN]) + SAL_INFO("svtools", "PHOENICIAN"); + if (rIn[vcl::UnicodeCoverage::CJK_UNIFIED_IDEOGRAPHS]) + SAL_INFO("svtools", "CJK_UNIFIED_IDEOGRAPHS"); + if (rIn[vcl::UnicodeCoverage::PRIVATE_USE_AREA_PLANE_0]) + SAL_INFO("svtools", "PRIVATE_USE_AREA_PLANE_0"); + if (rIn[vcl::UnicodeCoverage::CJK_STROKES]) + SAL_INFO("svtools", "CJK_STROKES"); + if (rIn[vcl::UnicodeCoverage::ALPHABETIC_PRESENTATION_FORMS]) + SAL_INFO("svtools", "ALPHABETIC_PRESENTATION_FORMS"); + if (rIn[vcl::UnicodeCoverage::ARABIC_PRESENTATION_FORMS_A]) + SAL_INFO("svtools", "ARABIC_PRESENTATION_FORMS_A"); + if (rIn[vcl::UnicodeCoverage::COMBINING_HALF_MARKS]) + SAL_INFO("svtools", "COMBINING_HALF_MARKS"); + if (rIn[vcl::UnicodeCoverage::VERTICAL_FORMS]) + SAL_INFO("svtools", "VERTICAL_FORMS"); + if (rIn[vcl::UnicodeCoverage::SMALL_FORM_VARIANTS]) + SAL_INFO("svtools", "SMALL_FORM_VARIANTS"); + if (rIn[vcl::UnicodeCoverage::ARABIC_PRESENTATION_FORMS_B]) + SAL_INFO("svtools", "ARABIC_PRESENTATION_FORMS_B"); + if (rIn[vcl::UnicodeCoverage::HALFWIDTH_AND_FULLWIDTH_FORMS]) + SAL_INFO("svtools", "HALFWIDTH_AND_FULLWIDTH_FORMS"); + if (rIn[vcl::UnicodeCoverage::SPECIALS]) + SAL_INFO("svtools", "SPECIALS"); + if (rIn[vcl::UnicodeCoverage::TIBETAN]) + SAL_INFO("svtools", "TIBETAN"); + if (rIn[vcl::UnicodeCoverage::SYRIAC]) + SAL_INFO("svtools", "SYRIAC"); + if (rIn[vcl::UnicodeCoverage::THAANA]) + SAL_INFO("svtools", "THAANA"); + if (rIn[vcl::UnicodeCoverage::SINHALA]) + SAL_INFO("svtools", "SINHALA"); + if (rIn[vcl::UnicodeCoverage::MYANMAR]) + SAL_INFO("svtools", "MYANMAR"); + if (rIn[vcl::UnicodeCoverage::ETHIOPIC]) + SAL_INFO("svtools", "ETHIOPIC"); + if (rIn[vcl::UnicodeCoverage::CHEROKEE]) + SAL_INFO("svtools", "CHEROKEE"); + if (rIn[vcl::UnicodeCoverage::UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS]) + SAL_INFO("svtools", "UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS"); + if (rIn[vcl::UnicodeCoverage::OGHAM]) + SAL_INFO("svtools", "OGHAM"); + if (rIn[vcl::UnicodeCoverage::RUNIC]) + SAL_INFO("svtools", "RUNIC"); + if (rIn[vcl::UnicodeCoverage::KHMER]) + SAL_INFO("svtools", "KHMER"); + if (rIn[vcl::UnicodeCoverage::MONGOLIAN]) + SAL_INFO("svtools", "MONGOLIAN"); + if (rIn[vcl::UnicodeCoverage::BRAILLE_PATTERNS]) + SAL_INFO("svtools", "BRAILLE_PATTERNS"); + if (rIn[vcl::UnicodeCoverage::YI_SYLLABLES]) + SAL_INFO("svtools", "YI_SYLLABLES"); + if (rIn[vcl::UnicodeCoverage::TAGALOG]) + SAL_INFO("svtools", "TAGALOG"); + if (rIn[vcl::UnicodeCoverage::OLD_ITALIC]) + SAL_INFO("svtools", "OLD_ITALIC"); + if (rIn[vcl::UnicodeCoverage::GOTHIC]) + SAL_INFO("svtools", "GOTHIC"); + if (rIn[vcl::UnicodeCoverage::DESERET]) + SAL_INFO("svtools", "DESERET"); + if (rIn[vcl::UnicodeCoverage::BYZANTINE_MUSICAL_SYMBOLS]) + SAL_INFO("svtools", "BYZANTINE_MUSICAL_SYMBOLS"); + if (rIn[vcl::UnicodeCoverage::MATHEMATICAL_ALPHANUMERIC_SYMBOLS]) + SAL_INFO("svtools", "MATHEMATICAL_ALPHANUMERIC_SYMBOLS"); + if (rIn[vcl::UnicodeCoverage::PRIVATE_USE_PLANE_15]) + SAL_INFO("svtools", "PRIVATE_USE_PLANE_15"); + if (rIn[vcl::UnicodeCoverage::VARIATION_SELECTORS]) + SAL_INFO("svtools", "VARIATION_SELECTORS"); + if (rIn[vcl::UnicodeCoverage::TAGS]) + SAL_INFO("svtools", "TAGS"); + if (rIn[vcl::UnicodeCoverage::LIMBU]) + SAL_INFO("svtools", "LIMBU"); + if (rIn[vcl::UnicodeCoverage::TAI_LE]) + SAL_INFO("svtools", "TAI_LE"); + if (rIn[vcl::UnicodeCoverage::NEW_TAI_LUE]) + SAL_INFO("svtools", "NEW_TAI_LUE"); + if (rIn[vcl::UnicodeCoverage::BUGINESE]) + SAL_INFO("svtools", "BUGINESE"); + if (rIn[vcl::UnicodeCoverage::GLAGOLITIC]) + SAL_INFO("svtools", "GLAGOLITIC"); + if (rIn[vcl::UnicodeCoverage::TIFINAGH]) + SAL_INFO("svtools", "TIFINAGH"); + if (rIn[vcl::UnicodeCoverage::YIJING_HEXAGRAM_SYMBOLS]) + SAL_INFO("svtools", "YIJING_HEXAGRAM_SYMBOLS"); + if (rIn[vcl::UnicodeCoverage::SYLOTI_NAGRI]) + SAL_INFO("svtools", "SYLOTI_NAGRI"); + if (rIn[vcl::UnicodeCoverage::LINEAR_B_SYLLABARY]) + SAL_INFO("svtools", "LINEAR_B_SYLLABARY"); + if (rIn[vcl::UnicodeCoverage::ANCIENT_GREEK_NUMBERS]) + SAL_INFO("svtools", "ANCIENT_GREEK_NUMBERS"); + if (rIn[vcl::UnicodeCoverage::UGARITIC]) + SAL_INFO("svtools", "UGARITIC"); + if (rIn[vcl::UnicodeCoverage::OLD_PERSIAN]) + SAL_INFO("svtools", "OLD_PERSIAN"); + if (rIn[vcl::UnicodeCoverage::SHAVIAN]) + SAL_INFO("svtools", "SHAVIAN"); + if (rIn[vcl::UnicodeCoverage::OSMANYA]) + SAL_INFO("svtools", "OSMANYA"); + if (rIn[vcl::UnicodeCoverage::CYPRIOT_SYLLABARY]) + SAL_INFO("svtools", "CYPRIOT_SYLLABARY"); + if (rIn[vcl::UnicodeCoverage::KHAROSHTHI]) + SAL_INFO("svtools", "KHAROSHTHI"); + if (rIn[vcl::UnicodeCoverage::TAI_XUAN_JING_SYMBOLS]) + SAL_INFO("svtools", "TAI_XUAN_JING_SYMBOLS"); + if (rIn[vcl::UnicodeCoverage::CUNEIFORM]) + SAL_INFO("svtools", "CUNEIFORM"); + if (rIn[vcl::UnicodeCoverage::COUNTING_ROD_NUMERALS]) + SAL_INFO("svtools", "COUNTING_ROD_NUMERALS"); + if (rIn[vcl::UnicodeCoverage::SUNDANESE]) + SAL_INFO("svtools", "SUNDANESE"); + if (rIn[vcl::UnicodeCoverage::LEPCHA]) + SAL_INFO("svtools", "LEPCHA"); + if (rIn[vcl::UnicodeCoverage::OL_CHIKI]) + SAL_INFO("svtools", "OL_CHIKI"); + if (rIn[vcl::UnicodeCoverage::SAURASHTRA]) + SAL_INFO("svtools", "SAURASHTRA"); + if (rIn[vcl::UnicodeCoverage::KAYAH_LI]) + SAL_INFO("svtools", "KAYAH_LI"); + if (rIn[vcl::UnicodeCoverage::REJANG]) + SAL_INFO("svtools", "REJANG"); + if (rIn[vcl::UnicodeCoverage::CHAM]) + SAL_INFO("svtools", "CHAM"); + if (rIn[vcl::UnicodeCoverage::ANCIENT_SYMBOLS]) + SAL_INFO("svtools", "ANCIENT_SYMBOLS"); + if (rIn[vcl::UnicodeCoverage::PHAISTOS_DISC]) + SAL_INFO("svtools", "PHAISTOS_DISC"); + if (rIn[vcl::UnicodeCoverage::CARIAN]) + SAL_INFO("svtools", "CARIAN"); + if (rIn[vcl::UnicodeCoverage::DOMINO_TILES]) + SAL_INFO("svtools", "DOMINO_TILES"); + if (rIn[vcl::UnicodeCoverage::RESERVED1]) + SAL_INFO("svtools", "RESERVED1"); + if (rIn[vcl::UnicodeCoverage::RESERVED2]) + SAL_INFO("svtools", "RESERVED2"); + if (rIn[vcl::UnicodeCoverage::RESERVED3]) + SAL_INFO("svtools", "RESERVED3"); + if (rIn[vcl::UnicodeCoverage::RESERVED4]) + SAL_INFO("svtools", "RESERVED4"); + if (rIn[vcl::UnicodeCoverage::RESERVED5]) + SAL_INFO("svtools", "RESERVED5"); + } + + void lcl_dump_codepage_coverage(const std::optional<std::bitset<vcl::CodePageCoverage::MAX_CP_ENUM>> &roIn) + { + if (!roIn) + { + SAL_INFO("svtools", "<NOTHING>"); + return; + } + auto & rIn(*roIn); + if (rIn.none()) + { + SAL_INFO("svtools", "<NONE>"); + return; + } + if (rIn[vcl::CodePageCoverage::CP1252]) + SAL_INFO("svtools", "CP1252"); + if (rIn[vcl::CodePageCoverage::CP1250]) + SAL_INFO("svtools", "CP1250"); + if (rIn[vcl::CodePageCoverage::CP1251]) + SAL_INFO("svtools", "CP1251"); + if (rIn[vcl::CodePageCoverage::CP1253]) + SAL_INFO("svtools", "CP1253"); + if (rIn[vcl::CodePageCoverage::CP1254]) + SAL_INFO("svtools", "CP1254"); + if (rIn[vcl::CodePageCoverage::CP1255]) + SAL_INFO("svtools", "CP1255"); + if (rIn[vcl::CodePageCoverage::CP1256]) + SAL_INFO("svtools", "CP1256"); + if (rIn[vcl::CodePageCoverage::CP1257]) + SAL_INFO("svtools", "CP1257"); + if (rIn[vcl::CodePageCoverage::CP1258]) + SAL_INFO("svtools", "CP1258"); + if (rIn[vcl::CodePageCoverage::CP874]) + SAL_INFO("svtools", "CP874"); + if (rIn[vcl::CodePageCoverage::CP932]) + SAL_INFO("svtools", "CP932"); + if (rIn[vcl::CodePageCoverage::CP936]) + SAL_INFO("svtools", "CP936"); + if (rIn[vcl::CodePageCoverage::CP949]) + SAL_INFO("svtools", "CP949"); + if (rIn[vcl::CodePageCoverage::CP950]) + SAL_INFO("svtools", "CP950"); + if (rIn[vcl::CodePageCoverage::CP1361]) + SAL_INFO("svtools", "CP1361"); + if (rIn[vcl::CodePageCoverage::CP869]) + SAL_INFO("svtools", "CP869"); + if (rIn[vcl::CodePageCoverage::CP866]) + SAL_INFO("svtools", "CP866"); + if (rIn[vcl::CodePageCoverage::CP865]) + SAL_INFO("svtools", "CP865"); + if (rIn[vcl::CodePageCoverage::CP864]) + SAL_INFO("svtools", "CP864"); + if (rIn[vcl::CodePageCoverage::CP863]) + SAL_INFO("svtools", "CP863"); + if (rIn[vcl::CodePageCoverage::CP862]) + SAL_INFO("svtools", "CP862"); + if (rIn[vcl::CodePageCoverage::CP861]) + SAL_INFO("svtools", "CP861"); + if (rIn[vcl::CodePageCoverage::CP860]) + SAL_INFO("svtools", "CP860"); + if (rIn[vcl::CodePageCoverage::CP857]) + SAL_INFO("svtools", "CP857"); + if (rIn[vcl::CodePageCoverage::CP855]) + SAL_INFO("svtools", "CP855"); + if (rIn[vcl::CodePageCoverage::CP852]) + SAL_INFO("svtools", "CP852"); + if (rIn[vcl::CodePageCoverage::CP775]) + SAL_INFO("svtools", "CP775"); + if (rIn[vcl::CodePageCoverage::CP737]) + SAL_INFO("svtools", "CP737"); + if (rIn[vcl::CodePageCoverage::CP780]) + SAL_INFO("svtools", "CP780"); + if (rIn[vcl::CodePageCoverage::CP850]) + SAL_INFO("svtools", "CP850"); + if (rIn[vcl::CodePageCoverage::CP437]) + SAL_INFO("svtools", "CP437"); + } +#endif + + std::bitset<vcl::UnicodeCoverage::MAX_UC_ENUM> getMaskByScriptType(sal_Int16 nScriptType) + { + std::bitset<vcl::UnicodeCoverage::MAX_UC_ENUM> aMask; + aMask.set(); + + for (size_t i = 0; i < vcl::UnicodeCoverage::MAX_UC_ENUM; ++i) + { + using vcl::UnicodeCoverage::UnicodeCoverageEnum; + UScriptCode eScriptCode = otCoverageToScript(static_cast<UnicodeCoverageEnum>(i)); + if (unicode::getScriptClassFromUScriptCode(eScriptCode) == nScriptType) + aMask.set(i, false); + } + + return aMask; + } + + //false for all bits considered "Latin" by LibreOffice + std::bitset<vcl::UnicodeCoverage::MAX_UC_ENUM> const & getLatinMask() + { + static std::bitset<vcl::UnicodeCoverage::MAX_UC_ENUM> s_Mask(getMaskByScriptType(css::i18n::ScriptType::LATIN)); + return s_Mask; + } + + //false for all bits considered "Asian" by LibreOffice + std::bitset<vcl::UnicodeCoverage::MAX_UC_ENUM> const & getCJKMask() + { + static std::bitset<vcl::UnicodeCoverage::MAX_UC_ENUM> s_Mask(getMaskByScriptType(css::i18n::ScriptType::ASIAN)); + return s_Mask; + } + + //false for all bits considered "Complex" by LibreOffice + std::bitset<vcl::UnicodeCoverage::MAX_UC_ENUM> const & getCTLMask() + { + static std::bitset<vcl::UnicodeCoverage::MAX_UC_ENUM> s_Mask(getMaskByScriptType(css::i18n::ScriptType::COMPLEX)); + return s_Mask; + } + + //false for all bits considered "WEAK" by LibreOffice + std::bitset<vcl::UnicodeCoverage::MAX_UC_ENUM> const & getWeakMask() + { + static std::bitset<vcl::UnicodeCoverage::MAX_UC_ENUM> s_Mask(getMaskByScriptType(css::i18n::ScriptType::WEAK)); + return s_Mask; + } + + //Nearly every font supports some basic Latin + std::bitset<vcl::UnicodeCoverage::MAX_UC_ENUM> getCommonLatnSubsetMask() + { + std::bitset<vcl::UnicodeCoverage::MAX_UC_ENUM> aMask; + aMask.set(); + aMask.set(vcl::UnicodeCoverage::BASIC_LATIN, false); + aMask.set(vcl::UnicodeCoverage::LATIN_1_SUPPLEMENT, false); + aMask.set(vcl::UnicodeCoverage::LATIN_EXTENDED_A, false); + aMask.set(vcl::UnicodeCoverage::LATIN_EXTENDED_B, false); + aMask.set(vcl::UnicodeCoverage::LATIN_EXTENDED_ADDITIONAL, false); + return aMask; + } + + template<size_t N> + size_t find_first(std::bitset<N> const& rSet) + { + for (size_t i = 0; i < N; ++i) + { + if (rSet.test(i)) + return i; + } + assert(false); // see current usage + return N; + } + + UScriptCode getScript(const vcl::FontCapabilities &rFontCapabilities) + { + using vcl::UnicodeCoverage::UnicodeCoverageEnum; + + std::bitset<vcl::UnicodeCoverage::MAX_UC_ENUM> aMasked; + if (rFontCapabilities.oUnicodeRange) + { + aMasked = *rFontCapabilities.oUnicodeRange & getWeakMask(); + } + + if (aMasked.count() == 1) + return otCoverageToScript(static_cast<UnicodeCoverageEnum>(find_first(aMasked))); + + if (aMasked[vcl::UnicodeCoverage::ARABIC]) + { + aMasked.set(vcl::UnicodeCoverage::ARABIC_PRESENTATION_FORMS_A, false); + aMasked.set(vcl::UnicodeCoverage::ARABIC_PRESENTATION_FORMS_B, false); + aMasked.set(vcl::UnicodeCoverage::NKO, false); + //Probably strongly tuned for Arabic + if (aMasked.count() == 1) + return USCRIPT_ARABIC; + if (aMasked.count() == 2 && aMasked[vcl::UnicodeCoverage::SYRIAC]) + return USCRIPT_SYRIAC; + } + + if (aMasked[vcl::UnicodeCoverage::DEVANAGARI]) + { + aMasked.set(vcl::UnicodeCoverage::DEVANAGARI, false); + //Probably strongly tuned for a single Indic script + if (aMasked.count() == 1) + return otCoverageToScript(static_cast<UnicodeCoverageEnum>(find_first(aMasked))); + } + + aMasked.set(vcl::UnicodeCoverage::GREEK_EXTENDED, false); + aMasked.set(vcl::UnicodeCoverage::GREEK_AND_COPTIC, false); + if (aMasked.count() == 1) + return otCoverageToScript(static_cast<UnicodeCoverageEnum>(find_first(aMasked))); + + if (aMasked[vcl::UnicodeCoverage::CYRILLIC]) + { + //Probably strongly tuned for Georgian + if (aMasked.count() == 2 && aMasked[vcl::UnicodeCoverage::GEORGIAN]) + return USCRIPT_GEORGIAN; + } + + aMasked &= getCJKMask(); + + aMasked.set(vcl::UnicodeCoverage::CYRILLIC, false); + aMasked.set(vcl::UnicodeCoverage::THAI, false); + aMasked.set(vcl::UnicodeCoverage::DESERET, false); + aMasked.set(vcl::UnicodeCoverage::PHAGS_PA, false); + + //So, possibly a CJK font + if (!aMasked.count() && rFontCapabilities.oCodePageRange) + { + std::bitset<vcl::CodePageCoverage::MAX_CP_ENUM> aCJKCodePageMask; + aCJKCodePageMask.set(vcl::CodePageCoverage::CP932); + aCJKCodePageMask.set(vcl::CodePageCoverage::CP936); + aCJKCodePageMask.set(vcl::CodePageCoverage::CP949); + aCJKCodePageMask.set(vcl::CodePageCoverage::CP950); + aCJKCodePageMask.set(vcl::CodePageCoverage::CP1361); + std::bitset<vcl::CodePageCoverage::MAX_CP_ENUM> aMaskedCodePage = + *rFontCapabilities.oCodePageRange & aCJKCodePageMask; + //fold Korean + if (aMaskedCodePage[vcl::CodePageCoverage::CP1361]) + { + aMaskedCodePage.set(vcl::CodePageCoverage::CP949); + aMaskedCodePage.set(vcl::CodePageCoverage::CP1361, false); + } + + if (aMaskedCodePage.count() == 1) + { + if (aMaskedCodePage[vcl::CodePageCoverage::CP932]) + return USCRIPT_JAPANESE; + if (aMaskedCodePage[vcl::CodePageCoverage::CP949]) + return USCRIPT_KOREAN; + if (aMaskedCodePage[vcl::CodePageCoverage::CP936]) + return USCRIPT_SIMPLIFIED_HAN; + if (aMaskedCodePage[vcl::CodePageCoverage::CP950]) + return USCRIPT_TRADITIONAL_HAN; + } + + if (aMaskedCodePage.count()) + return USCRIPT_HAN; + } + + return USCRIPT_COMMON; + } +} + +namespace +{ + UScriptCode attemptToDisambiguateHan(UScriptCode eScript, OutputDevice const &rDevice) + { + //If we're a CJK font, see if we seem to be tuned for C, J or K + if (eScript == USCRIPT_HAN) + { + const vcl::Font &rFont = rDevice.GetFont(); + + bool bKore = false, bJpan = false, bHant = false, bHans = false; + + static const sal_Unicode aKorean[] = { 0x3131 }; + OUString sKorean(aKorean, SAL_N_ELEMENTS(aKorean)); + if (-1 == rDevice.HasGlyphs(rFont, sKorean)) + bKore = true; + + static const sal_Unicode aJapanese[] = { 0x3007, 0x9F9D }; + OUString sJapanese(aJapanese, SAL_N_ELEMENTS(aJapanese)); + if (-1 == rDevice.HasGlyphs(rFont, sJapanese)) + bJpan = true; + + static const sal_Unicode aTraditionalChinese[] = { 0x570B }; + OUString sTraditionalChinese(aTraditionalChinese, SAL_N_ELEMENTS(aTraditionalChinese)); + if (-1 == rDevice.HasGlyphs(rFont, sTraditionalChinese)) + bHant = true; + + static const sal_Unicode aSimplifiedChinese[] = { 0x56FD }; + OUString sSimplifiedChinese(aSimplifiedChinese, SAL_N_ELEMENTS(aSimplifiedChinese)); + if (-1 == rDevice.HasGlyphs(rFont, sSimplifiedChinese)) + bHans = true; + + if (bKore && !bJpan && !bHans) + eScript = USCRIPT_KOREAN; + else if (bJpan && !bKore && !bHans) + eScript = USCRIPT_JAPANESE; + else if (bHant && !bHans && !bKore && !bJpan) + eScript = USCRIPT_TRADITIONAL_HAN; + else if (bHans && !bHant && !bKore && !bJpan) + eScript = USCRIPT_SIMPLIFIED_HAN; + //otherwise fall-through as USCRIPT_HAN and expect a combined Hant/Hans preview + } + return eScript; + } +} + +OUString makeShortRepresentativeTextForSelectedFont(OutputDevice const &rDevice) +{ + UScriptCode eScript = lcl_getHardCodedScriptNameForFont(rDevice); + if (eScript == USCRIPT_INVALID_CODE) + { + vcl::FontCapabilities aFontCapabilities; + if (!rDevice.GetFontCapabilities(aFontCapabilities)) + return OUString(); + +#if OSL_DEBUG_LEVEL > 0 + lcl_dump_unicode_coverage(aFontCapabilities.oUnicodeRange); + lcl_dump_codepage_coverage(aFontCapabilities.oCodePageRange); +#endif + + if (aFontCapabilities.oUnicodeRange) + *aFontCapabilities.oUnicodeRange &= getCommonLatnSubsetMask(); + + //If this font is probably tuned to display a single non-Latin + //script and the font name is itself in Latin, then show a small + //chunk of representative text for that script + eScript = getScript(aFontCapabilities); + if (eScript == USCRIPT_COMMON) + return OUString(); + + eScript = attemptToDisambiguateHan(eScript, rDevice); + } + + OUString sSampleText = makeShortRepresentativeTextForScript(eScript); + bool bHasSampleTextGlyphs = (-1 == rDevice.HasGlyphs(rDevice.GetFont(), sSampleText)); + return bHasSampleTextGlyphs ? sSampleText : OUString(); +} + +UScriptCode otCoverageToScript(vcl::UnicodeCoverage::UnicodeCoverageEnum eOTCoverage) +{ + UScriptCode eRet = USCRIPT_COMMON; + switch (eOTCoverage) + { + case vcl::UnicodeCoverage::BASIC_LATIN: + case vcl::UnicodeCoverage::LATIN_1_SUPPLEMENT: + case vcl::UnicodeCoverage::LATIN_EXTENDED_A: + case vcl::UnicodeCoverage::LATIN_EXTENDED_B: + eRet = USCRIPT_LATIN; + break; + case vcl::UnicodeCoverage::COMBINING_DIACRITICAL_MARKS: + eRet = USCRIPT_INHERITED; + break; + case vcl::UnicodeCoverage::GREEK_AND_COPTIC: + eRet = USCRIPT_GREEK; + break; + case vcl::UnicodeCoverage::COPTIC: + eRet = USCRIPT_COPTIC; + break; + case vcl::UnicodeCoverage::CYRILLIC: + eRet = USCRIPT_CYRILLIC; + break; + case vcl::UnicodeCoverage::ARMENIAN: + eRet = USCRIPT_ARMENIAN; + break; + case vcl::UnicodeCoverage::HEBREW: + eRet = USCRIPT_HEBREW; + break; + case vcl::UnicodeCoverage::VAI: + eRet = USCRIPT_VAI; + break; + case vcl::UnicodeCoverage::ARABIC: + eRet = USCRIPT_ARABIC; + break; + case vcl::UnicodeCoverage::NKO: + eRet = USCRIPT_NKO; + break; + case vcl::UnicodeCoverage::DEVANAGARI: + eRet = USCRIPT_DEVANAGARI; + break; + case vcl::UnicodeCoverage::BENGALI: + eRet = USCRIPT_BENGALI; + break; + case vcl::UnicodeCoverage::GURMUKHI: + eRet = USCRIPT_GURMUKHI; + break; + case vcl::UnicodeCoverage::GUJARATI: + eRet = USCRIPT_GUJARATI; + break; + case vcl::UnicodeCoverage::ODIA: + eRet = USCRIPT_ORIYA; + break; + case vcl::UnicodeCoverage::TAMIL: + eRet = USCRIPT_TAMIL; + break; + case vcl::UnicodeCoverage::TELUGU: + eRet = USCRIPT_TELUGU; + break; + case vcl::UnicodeCoverage::KANNADA: + eRet = USCRIPT_KANNADA; + break; + case vcl::UnicodeCoverage::MALAYALAM: + eRet = USCRIPT_MALAYALAM; + break; + case vcl::UnicodeCoverage::THAI: + eRet = USCRIPT_THAI; + break; + case vcl::UnicodeCoverage::LAO: + eRet = USCRIPT_LAO; + break; + case vcl::UnicodeCoverage::GEORGIAN: + eRet = USCRIPT_GEORGIAN; + break; + case vcl::UnicodeCoverage::BALINESE: + eRet = USCRIPT_BALINESE; + break; + case vcl::UnicodeCoverage::HANGUL_JAMO: + eRet = USCRIPT_HANGUL; + break; + case vcl::UnicodeCoverage::LATIN_EXTENDED_ADDITIONAL: + eRet = USCRIPT_LATIN; + break; + case vcl::UnicodeCoverage::GREEK_EXTENDED: + eRet = USCRIPT_GREEK; + break; + case vcl::UnicodeCoverage::CURRENCY_SYMBOLS: + eRet = USCRIPT_SYMBOLS; + break; + case vcl::UnicodeCoverage::COMBINING_DIACRITICAL_MARKS_FOR_SYMBOLS: + eRet = USCRIPT_INHERITED; + break; + case vcl::UnicodeCoverage::LETTERLIKE_SYMBOLS: + case vcl::UnicodeCoverage::NUMBER_FORMS: + case vcl::UnicodeCoverage::ARROWS: + eRet = USCRIPT_SYMBOLS; + break; + case vcl::UnicodeCoverage::MATHEMATICAL_OPERATORS: + eRet = USCRIPT_MATHEMATICAL_NOTATION; + break; + case vcl::UnicodeCoverage::MISCELLANEOUS_TECHNICAL: + case vcl::UnicodeCoverage::OPTICAL_CHARACTER_RECOGNITION: + case vcl::UnicodeCoverage::BOX_DRAWING: + case vcl::UnicodeCoverage::BLOCK_ELEMENTS: + case vcl::UnicodeCoverage::GEOMETRIC_SHAPES: + case vcl::UnicodeCoverage::MISCELLANEOUS_SYMBOLS: + case vcl::UnicodeCoverage::DINGBATS: + case vcl::UnicodeCoverage::CJK_SYMBOLS_AND_PUNCTUATION: + eRet = USCRIPT_SYMBOLS; + break; + case vcl::UnicodeCoverage::HIRAGANA: + eRet = USCRIPT_HIRAGANA; + break; + case vcl::UnicodeCoverage::KATAKANA: + eRet = USCRIPT_KATAKANA; + break; + case vcl::UnicodeCoverage::BOPOMOFO: + eRet = USCRIPT_BOPOMOFO; + break; + case vcl::UnicodeCoverage::HANGUL_COMPATIBILITY_JAMO: + eRet = USCRIPT_HANGUL; + break; + case vcl::UnicodeCoverage::PHAGS_PA: + eRet = USCRIPT_PHAGS_PA; + break; + case vcl::UnicodeCoverage::ENCLOSED_CJK_LETTERS_AND_MONTHS: + eRet = USCRIPT_HANGUL; + break; + case vcl::UnicodeCoverage::CJK_COMPATIBILITY: + eRet = USCRIPT_HAN; + break; + case vcl::UnicodeCoverage::HANGUL_SYLLABLES: + eRet = USCRIPT_HANGUL; + break; + case vcl::UnicodeCoverage::PHOENICIAN: + eRet = USCRIPT_PHOENICIAN; + break; + case vcl::UnicodeCoverage::CJK_UNIFIED_IDEOGRAPHS: + case vcl::UnicodeCoverage::CJK_STROKES: + eRet = USCRIPT_HAN; + break; + case vcl::UnicodeCoverage::ARABIC_PRESENTATION_FORMS_A: + eRet = USCRIPT_ARABIC; + break; + case vcl::UnicodeCoverage::COMBINING_HALF_MARKS: + eRet = USCRIPT_INHERITED; + break; + case vcl::UnicodeCoverage::ARABIC_PRESENTATION_FORMS_B: + eRet = USCRIPT_ARABIC; + break; + case vcl::UnicodeCoverage::TIBETAN: + eRet = USCRIPT_TIBETAN; + break; + case vcl::UnicodeCoverage::SYRIAC: + eRet = USCRIPT_SYRIAC; + break; + case vcl::UnicodeCoverage::THAANA: + eRet = USCRIPT_THAANA; + break; + case vcl::UnicodeCoverage::SINHALA: + eRet = USCRIPT_SINHALA; + break; + case vcl::UnicodeCoverage::MYANMAR: + eRet = USCRIPT_MYANMAR; + break; + case vcl::UnicodeCoverage::ETHIOPIC: + eRet = USCRIPT_ETHIOPIC; + break; + case vcl::UnicodeCoverage::CHEROKEE: + eRet = USCRIPT_CHEROKEE; + break; + case vcl::UnicodeCoverage::UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS: + eRet = USCRIPT_CANADIAN_ABORIGINAL; + break; + case vcl::UnicodeCoverage::OGHAM: + eRet = USCRIPT_OGHAM; + break; + case vcl::UnicodeCoverage::RUNIC: + eRet = USCRIPT_RUNIC; + break; + case vcl::UnicodeCoverage::KHMER: + eRet = USCRIPT_KHMER; + break; + case vcl::UnicodeCoverage::MONGOLIAN: + eRet = USCRIPT_MONGOLIAN; + break; + case vcl::UnicodeCoverage::BRAILLE_PATTERNS: + eRet = USCRIPT_BRAILLE; + break; + case vcl::UnicodeCoverage::YI_SYLLABLES: + eRet = USCRIPT_YI; + break; + case vcl::UnicodeCoverage::TAGALOG: + eRet = USCRIPT_TAGALOG; + break; + case vcl::UnicodeCoverage::OLD_ITALIC: + eRet = USCRIPT_OLD_ITALIC; + break; + case vcl::UnicodeCoverage::GOTHIC: + eRet = USCRIPT_GOTHIC; + break; + case vcl::UnicodeCoverage::DESERET: + eRet = USCRIPT_DESERET; + break; + case vcl::UnicodeCoverage::BYZANTINE_MUSICAL_SYMBOLS: + case vcl::UnicodeCoverage::MATHEMATICAL_ALPHANUMERIC_SYMBOLS: + case vcl::UnicodeCoverage::PRIVATE_USE_PLANE_15: + eRet = USCRIPT_SYMBOLS; + break; + case vcl::UnicodeCoverage::VARIATION_SELECTORS: + eRet = USCRIPT_INHERITED; + break; + case vcl::UnicodeCoverage::TAGS: + eRet = USCRIPT_SYMBOLS; + break; + case vcl::UnicodeCoverage::LIMBU: + eRet = USCRIPT_LIMBU; + break; + case vcl::UnicodeCoverage::TAI_LE: + eRet = USCRIPT_TAI_LE; + break; + case vcl::UnicodeCoverage::NEW_TAI_LUE: + eRet = USCRIPT_NEW_TAI_LUE; + break; + case vcl::UnicodeCoverage::BUGINESE: + eRet = USCRIPT_BUGINESE; + break; + case vcl::UnicodeCoverage::GLAGOLITIC: + eRet = USCRIPT_GLAGOLITIC; + break; + case vcl::UnicodeCoverage::TIFINAGH: + eRet = USCRIPT_TIFINAGH; + break; + case vcl::UnicodeCoverage::YIJING_HEXAGRAM_SYMBOLS: + eRet = USCRIPT_SYMBOLS; + break; + case vcl::UnicodeCoverage::SYLOTI_NAGRI: + eRet = USCRIPT_SYLOTI_NAGRI; + break; + case vcl::UnicodeCoverage::LINEAR_B_SYLLABARY: + eRet = USCRIPT_LINEAR_B; + break; + case vcl::UnicodeCoverage::ANCIENT_GREEK_NUMBERS: + eRet = USCRIPT_GREEK; + break; + case vcl::UnicodeCoverage::UGARITIC: + eRet = USCRIPT_UGARITIC; + break; + case vcl::UnicodeCoverage::OLD_PERSIAN: + eRet = USCRIPT_OLD_PERSIAN; + break; + case vcl::UnicodeCoverage::SHAVIAN: + eRet = USCRIPT_SHAVIAN; + break; + case vcl::UnicodeCoverage::OSMANYA: + eRet = USCRIPT_OSMANYA; + break; + case vcl::UnicodeCoverage::CYPRIOT_SYLLABARY: + eRet = USCRIPT_CYPRIOT; + break; + case vcl::UnicodeCoverage::KHAROSHTHI: + eRet = USCRIPT_KHAROSHTHI; + break; + case vcl::UnicodeCoverage::CUNEIFORM: + eRet = USCRIPT_CUNEIFORM; + break; + case vcl::UnicodeCoverage::SUNDANESE: + eRet = USCRIPT_SUNDANESE; + break; + case vcl::UnicodeCoverage::LEPCHA: + eRet = USCRIPT_LEPCHA; + break; + case vcl::UnicodeCoverage::OL_CHIKI: + eRet = USCRIPT_OL_CHIKI; + break; + case vcl::UnicodeCoverage::SAURASHTRA: + eRet = USCRIPT_SAURASHTRA; + break; + case vcl::UnicodeCoverage::KAYAH_LI: + eRet = USCRIPT_KAYAH_LI; + break; + case vcl::UnicodeCoverage::REJANG: + eRet = USCRIPT_REJANG; + break; + case vcl::UnicodeCoverage::CHAM: + eRet = USCRIPT_CHAM; + break; + case vcl::UnicodeCoverage::CARIAN: + eRet = USCRIPT_CARIAN; + break; + case vcl::UnicodeCoverage::DOMINO_TILES: + case vcl::UnicodeCoverage::TAI_XUAN_JING_SYMBOLS: + case vcl::UnicodeCoverage::COUNTING_ROD_NUMERALS: + case vcl::UnicodeCoverage::ANCIENT_SYMBOLS: + case vcl::UnicodeCoverage::PHAISTOS_DISC: + eRet = USCRIPT_SYMBOLS; + break; + case vcl::UnicodeCoverage::IPA_EXTENSIONS: + case vcl::UnicodeCoverage::SPECIALS: + case vcl::UnicodeCoverage::HALFWIDTH_AND_FULLWIDTH_FORMS: + case vcl::UnicodeCoverage::VERTICAL_FORMS: + case vcl::UnicodeCoverage::SMALL_FORM_VARIANTS: + case vcl::UnicodeCoverage::ALPHABETIC_PRESENTATION_FORMS: + case vcl::UnicodeCoverage::PRIVATE_USE_AREA_PLANE_0: + case vcl::UnicodeCoverage::NONPLANE_0: + case vcl::UnicodeCoverage::ENCLOSED_ALPHANUMERICS: + case vcl::UnicodeCoverage::CONTROL_PICTURES: + case vcl::UnicodeCoverage::SUPERSCRIPTS_AND_SUBSCRIPTS: + case vcl::UnicodeCoverage::GENERAL_PUNCTUATION: + case vcl::UnicodeCoverage::SPACING_MODIFIER_LETTERS: + case vcl::UnicodeCoverage::RESERVED1: + case vcl::UnicodeCoverage::RESERVED2: + case vcl::UnicodeCoverage::RESERVED3: + case vcl::UnicodeCoverage::RESERVED4: + case vcl::UnicodeCoverage::RESERVED5: + case vcl::UnicodeCoverage::MAX_UC_ENUM: + break; + } + return eRet; +} + +OUString makeRepresentativeTextForFont(sal_Int16 nScriptType, const vcl::Font &rFont) +{ + OUString sRet(makeRepresentativeTextForLanguage(rFont.GetLanguage())); + + ScopedVclPtrInstance< VirtualDevice > aDevice; + if (sRet.isEmpty() || (-1 != aDevice->HasGlyphs(rFont, sRet))) + { + aDevice->SetFont(rFont); + vcl::FontCapabilities aFontCapabilities; + if (aDevice->GetFontCapabilities(aFontCapabilities)) + { +#if OSL_DEBUG_LEVEL > 0 + lcl_dump_unicode_coverage(aFontCapabilities.oUnicodeRange); +#endif + + if (aFontCapabilities.oUnicodeRange) + { + *aFontCapabilities.oUnicodeRange &= getWeakMask(); + + if (nScriptType != css::i18n::ScriptType::ASIAN) + { + *aFontCapabilities.oUnicodeRange &= getCJKMask(); + aFontCapabilities.oCodePageRange.reset(); + } + if (nScriptType != css::i18n::ScriptType::LATIN) + *aFontCapabilities.oUnicodeRange &= getLatinMask(); + if (nScriptType != css::i18n::ScriptType::COMPLEX) + *aFontCapabilities.oUnicodeRange &= getCTLMask(); + } + +#if OSL_DEBUG_LEVEL > 0 + SAL_INFO("svtools", "minimal"); + lcl_dump_unicode_coverage(aFontCapabilities.oUnicodeRange); + lcl_dump_codepage_coverage(aFontCapabilities.oCodePageRange); +#endif + + UScriptCode eScript = getScript(aFontCapabilities); + + if (nScriptType == css::i18n::ScriptType::ASIAN) + eScript = attemptToDisambiguateHan(eScript, *aDevice); + + sRet = makeRepresentativeTextForScript(eScript); + } + + if (sRet.isEmpty()) + { + if (nScriptType == css::i18n::ScriptType::COMPLEX) + { + sRet = makeRepresentativeTextForScript(USCRIPT_HEBREW); + if (-1 != aDevice->HasGlyphs(rFont, sRet)) + { + sRet = makeMinimalTextForScript(USCRIPT_HEBREW); + if (-1 != aDevice->HasGlyphs(rFont, sRet)) + sRet = makeRepresentativeTextForScript(USCRIPT_ARABIC); + } + } + else if (nScriptType == css::i18n::ScriptType::LATIN) + sRet = makeRepresentativeTextForScript(USCRIPT_LATIN); + } + } + + return sRet; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/misc/stringtransfer.cxx b/svtools/source/misc/stringtransfer.cxx new file mode 100644 index 000000000..14e805fc6 --- /dev/null +++ b/svtools/source/misc/stringtransfer.cxx @@ -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 . + */ + +#include <sal/config.h> + +#include <rtl/ref.hxx> +#include <sot/exchange.hxx> +#include <svtools/stringtransfer.hxx> + + +namespace svt +{ + + + using namespace ::com::sun::star::uno; + using namespace ::com::sun::star::datatransfer; + + + //= OStringTransferable + + + OStringTransferable::OStringTransferable(const OUString& _rContent) + :TransferableHelper() + ,m_sContent( _rContent ) + { + } + + + void OStringTransferable::AddSupportedFormats() + { + AddFormat(SotClipboardFormatId::STRING); + } + + + bool OStringTransferable::GetData( const DataFlavor& _rFlavor, const OUString& /*rDestDoc*/ ) + { + SotClipboardFormatId nFormat = SotExchange::GetFormat( _rFlavor ); + if (SotClipboardFormatId::STRING == nFormat) + return SetString( m_sContent, _rFlavor ); + + return false; + } + + + //= OStringTransfer + + + void OStringTransfer::CopyString( const OUString& _rContent, vcl::Window* _pWindow ) + { + rtl::Reference<OStringTransferable> pTransferable = new OStringTransferable( _rContent ); + pTransferable->CopyToClipboard( _pWindow ); + } + + + bool OStringTransfer::PasteString( OUString& _rContent, vcl::Window* _pWindow ) + { + TransferableDataHelper aClipboardData = TransferableDataHelper::CreateFromSystemClipboard( _pWindow ); + + // check for a string format + const DataFlavorExVector& rFormats = aClipboardData.GetDataFlavorExVector(); + for (auto const& format : rFormats) + { + if (SotClipboardFormatId::STRING == format.mnSotId) + { + OUString sContent; + bool bSuccess = aClipboardData.GetString( SotClipboardFormatId::STRING, sContent ); + _rContent = sContent; + return bSuccess; + } + } + + return false; + } + + + void OStringTransfer::StartStringDrag( const OUString& _rContent, vcl::Window* _pWindow, sal_Int8 _nDragSourceActions ) + { + rtl::Reference<OStringTransferable> pTransferable = new OStringTransferable( _rContent ); + pTransferable->StartDrag(_pWindow, _nDragSourceActions); + } + + +} // namespace svt + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/misc/svtresid.cxx b/svtools/source/misc/svtresid.cxx new file mode 100644 index 000000000..cc03beeb1 --- /dev/null +++ b/svtools/source/misc/svtresid.cxx @@ -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 . + */ + +#include <unotools/resmgr.hxx> +#include <svtools/svtresid.hxx> + +std::locale SvtResLocale() +{ + return Translate::Create("svt"); +} + +OUString SvtResId(const char* pId) +{ + return Translate::get(pId, SvtResLocale()); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/misc/templatefoldercache.cxx b/svtools/source/misc/templatefoldercache.cxx new file mode 100644 index 000000000..8a0c338be --- /dev/null +++ b/svtools/source/misc/templatefoldercache.cxx @@ -0,0 +1,802 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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/config.h> +#include <sal/log.hxx> + +#include <osl/file.hxx> +#include <svtools/templatefoldercache.hxx> +#include <unotools/ucbstreamhelper.hxx> +#include <com/sun/star/sdbc/XResultSet.hpp> +#include <com/sun/star/ucb/XDynamicResultSet.hpp> +#include <com/sun/star/sdbc/XRow.hpp> +#include <com/sun/star/ucb/CommandAbortedException.hpp> +#include <com/sun/star/ucb/XContentAccess.hpp> +#include <com/sun/star/uno/XComponentContext.hpp> +#include <com/sun/star/util/theOfficeInstallationDirectories.hpp> +#include <ucbhelper/content.hxx> +#include <osl/diagnose.h> +#include <rtl/ref.hxx> +#include <salhelper/simplereferenceobject.hxx> +#include <tools/time.hxx> +#include <tools/urlobj.hxx> +#include <tools/debug.hxx> +#include <tools/diagnose_ex.h> +#include <unotools/pathoptions.hxx> + +#include <comphelper/processfactory.hxx> + +#include <vector> +#include <algorithm> + + +namespace svt +{ + + + using namespace ::utl; + using namespace ::com::sun::star; + using namespace ::com::sun::star::sdbc; + using namespace ::com::sun::star::ucb; + using namespace ::com::sun::star::uno; + + + //= helpers + + + static SvStream& WriteDateTime( SvStream& _rStorage, const util::DateTime& _rDate ) + { + sal_uInt16 hundredthSeconds = static_cast< sal_uInt16 >( _rDate.NanoSeconds / tools::Time::nanoPerCenti ); + _rStorage.WriteUInt16( hundredthSeconds ); + + _rStorage.WriteUInt16( _rDate.Seconds ); + _rStorage.WriteUInt16( _rDate.Minutes ); + _rStorage.WriteUInt16( _rDate.Hours ); + _rStorage.WriteUInt16( _rDate.Day ); + _rStorage.WriteUInt16( _rDate.Month ); + _rStorage.WriteInt16( _rDate.Year ); + + return _rStorage; + } + + + static SvStream& operator >> ( SvStream& _rStorage, util::DateTime& _rDate ) + { + sal_uInt16 hundredthSeconds; + _rStorage.ReadUInt16( hundredthSeconds ); + _rDate.NanoSeconds = static_cast< sal_uInt32 >( hundredthSeconds ) * tools::Time::nanoPerCenti; + + _rStorage.ReadUInt16( _rDate.Seconds ); + _rStorage.ReadUInt16( _rDate.Minutes ); + _rStorage.ReadUInt16( _rDate.Hours ); + _rStorage.ReadUInt16( _rDate.Day ); + _rStorage.ReadUInt16( _rDate.Month ); + _rStorage.ReadInt16( _rDate.Year ); + + return _rStorage; + } + + //= TemplateContent + + namespace { + + struct TemplateContent; + + } + + typedef ::std::vector< ::rtl::Reference< TemplateContent > > TemplateFolderContent; + typedef TemplateFolderContent::const_iterator ConstFolderIterator; + typedef TemplateFolderContent::iterator FolderIterator; + + namespace { + + /** a struct describing one content in one of the template dirs (or at least it's relevant aspects) + */ + struct TemplateContent : public ::salhelper::SimpleReferenceObject + { + public: + + private: + INetURLObject m_aURL; + util::DateTime m_aLastModified; // date of last modification as reported by UCP + TemplateFolderContent m_aSubContents; // sorted (by name) list of the children + + private: + void implResetDate( ) + { + m_aLastModified.NanoSeconds = m_aLastModified.Seconds = m_aLastModified.Minutes = m_aLastModified.Hours = 0; + m_aLastModified.Day = m_aLastModified.Month = m_aLastModified.Year = 0; + } + + private: + virtual ~TemplateContent() override; + + public: + explicit TemplateContent( const INetURLObject& _rURL ); + + // attribute access + OUString getURL( ) const { return m_aURL.GetMainURL( INetURLObject::DecodeMechanism::ToIUri ); } + void setModDate( const util::DateTime& _rDate ) { m_aLastModified = _rDate; } + const util::DateTime& getModDate( ) const { return m_aLastModified; } + + TemplateFolderContent& getSubContents() { return m_aSubContents; } + const TemplateFolderContent& getSubContents() const { return m_aSubContents; } + + ConstFolderIterator end() const { return m_aSubContents.end(); } + TemplateFolderContent::size_type + size() const { return m_aSubContents.size(); } + + void push_back( const ::rtl::Reference< TemplateContent >& _rxNewElement ) + { m_aSubContents.push_back( _rxNewElement ); } + }; + + } + + TemplateContent::TemplateContent( const INetURLObject& _rURL ) + :m_aURL( _rURL ) + { + DBG_ASSERT( INetProtocol::NotValid != m_aURL.GetProtocol(), "TemplateContent::TemplateContent: invalid URL!" ); + implResetDate(); + } + + + TemplateContent::~TemplateContent() + { + } + + + //= stl helpers + + namespace { + + /// compares two TemplateContent by URL + struct TemplateContentURLLess + { + bool operator() ( const ::rtl::Reference< TemplateContent >& _rxLHS, const ::rtl::Reference< TemplateContent >& _rxRHS ) const + { + return _rxLHS->getURL() < _rxRHS->getURL(); + } + }; + + + /// sorts the sib contents of a TemplateFolderContent + struct SubContentSort + { + void operator() ( TemplateFolderContent& _rFolder ) const + { + // sort the directory by name + ::std::sort( + _rFolder.begin(), + _rFolder.end(), + TemplateContentURLLess() + ); + + // sort the sub directories by name + ::std::for_each( + _rFolder.begin(), + _rFolder.end(), + *this + ); + } + + void operator() ( const ::rtl::Reference< TemplateContent >& _rxContent ) const + { + if ( _rxContent.is() && _rxContent->size() ) + { + operator()( _rxContent->getSubContents() ); + } + } + }; + + /** does a deep compare of two template contents + */ + struct TemplateContentEqual + { + + bool operator() (const ::rtl::Reference< TemplateContent >& _rLHS, const ::rtl::Reference< TemplateContent >& _rRHS ) + { + if ( !_rLHS.is() || !_rRHS.is() ) + { + OSL_FAIL( "TemplateContentEqual::operator(): invalid contents!" ); + return true; + // this is not strictly true, in case only one is invalid - but this is a heavy error anyway + } + + if ( _rLHS->getURL() != _rRHS->getURL() ) + return false; + + if ( _rLHS->getModDate() != _rRHS->getModDate() ) + return false; + + if ( _rLHS->getSubContents().size() != _rRHS->getSubContents().size() ) + return false; + + if ( !_rLHS->getSubContents().empty() ) + { // there are children + // -> compare them + ::std::pair< FolderIterator, FolderIterator > aFirstDifferent = ::std::mismatch( + _rLHS->getSubContents().begin(), + _rLHS->getSubContents().end(), + _rRHS->getSubContents().begin(), + *this + ); + if ( aFirstDifferent.first != _rLHS->getSubContents().end() ) + return false;// the sub contents differ + } + + return true; + } + }; + + + /// base class for functors which act on a SvStream + struct StorageHelper + { + protected: + SvStream& m_rStorage; + explicit StorageHelper( SvStream& _rStorage ) : m_rStorage( _rStorage ) { } + }; + + + struct StoreContentURL : public StorageHelper + { + uno::Reference< util::XOfficeInstallationDirectories > m_xOfficeInstDirs; + + StoreContentURL( SvStream& _rStorage, + const uno::Reference< + util::XOfficeInstallationDirectories > & + xOfficeInstDirs ) + : StorageHelper( _rStorage ), m_xOfficeInstDirs( xOfficeInstDirs ) { } + + void operator() ( const ::rtl::Reference< TemplateContent >& _rxContent ) const + { + // use the base class operator with the local name of the content + OUString sURL = _rxContent->getURL(); + // #116281# Keep office installation relocatable. Never store + // any direct references to office installation directory. + sURL = m_xOfficeInstDirs->makeRelocatableURL( sURL ); + m_rStorage.WriteUniOrByteString( sURL, m_rStorage.GetStreamCharSet() ); + } + }; + + + /// functor which stores the complete content of a TemplateContent + struct StoreFolderContent : public StorageHelper + { + uno::Reference< util::XOfficeInstallationDirectories > m_xOfficeInstDirs; + + public: + StoreFolderContent( SvStream& _rStorage, + const uno::Reference< + util::XOfficeInstallationDirectories > & + xOfficeInstDirs ) + : StorageHelper( _rStorage ), m_xOfficeInstDirs( xOfficeInstDirs ) { } + + + void operator() ( const TemplateContent& _rContent ) const + { + // store the info about this content + WriteDateTime( m_rStorage, _rContent.getModDate() ); + + // store the info about the children + // the number + m_rStorage.WriteInt32( _rContent.size() ); + // their URLs ( the local name is not enough, since URL might be not a hierarchical one, "expand:" for example ) + ::std::for_each( + _rContent.getSubContents().begin(), + _rContent.getSubContents().end(), + StoreContentURL( m_rStorage, m_xOfficeInstDirs ) + ); + // their content + ::std::for_each( + _rContent.getSubContents().begin(), + _rContent.getSubContents().end(), + *this + ); + } + + + void operator() ( const ::rtl::Reference< TemplateContent >& _rxContent ) const + { + if ( _rxContent.is() ) + { + operator()( *_rxContent ); + } + } + }; + + + /// functor which reads a complete TemplateContent instance + struct ReadFolderContent : public StorageHelper + { + uno::Reference< util::XOfficeInstallationDirectories > m_xOfficeInstDirs; + + ReadFolderContent( SvStream& _rStorage, + const uno::Reference< + util::XOfficeInstallationDirectories > & + xOfficeInstDirs ) + : StorageHelper( _rStorage ), m_xOfficeInstDirs( xOfficeInstDirs ) { } + + + void operator() ( TemplateContent& _rContent ) const + { + // store the info about this content + util::DateTime aModDate; + m_rStorage >> aModDate; + _rContent.setModDate( aModDate ); + + // store the info about the children + // the number + sal_Int32 nChildren = 0; + m_rStorage.ReadInt32( nChildren ); + TemplateFolderContent& rChildren = _rContent.getSubContents(); + rChildren.resize( 0 ); + rChildren.reserve( nChildren ); + // initialize them with their (local) names + while ( nChildren-- ) + { + OUString sURL = m_rStorage.ReadUniOrByteString(m_rStorage.GetStreamCharSet()); + sURL = m_xOfficeInstDirs->makeAbsoluteURL( sURL ); + INetURLObject aChildURL( sURL ); + rChildren.push_back( new TemplateContent( aChildURL ) ); + } + + // their content + ::std::for_each( + _rContent.getSubContents().begin(), + _rContent.getSubContents().end(), + *this + ); + } + + + void operator() ( const ::rtl::Reference< TemplateContent >& _rxContent ) const + { + if ( _rxContent.is() ) + { + operator()( *_rxContent ); + } + } + }; + + } + + //= TemplateFolderCacheImpl + + class TemplateFolderCacheImpl + { + private: + TemplateFolderContent m_aPreviousState; // the current state of the template dirs (as found on the HD) + TemplateFolderContent m_aCurrentState; // the previous state of the template dirs (as found in the cache file) + + osl::Mutex m_aMutex; + // will be lazy inited; never access directly; use getOfficeInstDirs(). + uno::Reference< util::XOfficeInstallationDirectories > m_xOfficeInstDirs; + + std::unique_ptr<SvStream> m_pCacheStream; + bool m_bNeedsUpdate : 1; + bool m_bKnowState : 1; + bool m_bValidCurrentState : 1; + bool m_bAutoStoreState : 1; + + public: + explicit TemplateFolderCacheImpl( bool _bAutoStoreState ); + ~TemplateFolderCacheImpl( ); + + bool needsUpdate(); + void storeState(); + + private: + bool openCacheStream( bool _bForRead ); + void closeCacheStream( ); + + /// read the state of the dirs from the cache file + bool readPreviousState(); + /// read the current state of the dirs + bool readCurrentState(); + + static OUString implParseSmart( const OUString& _rPath ); + + bool implReadFolder( const ::rtl::Reference< TemplateContent >& _rxRoot ); + + static sal_Int32 getMagicNumber(); + static void normalize( TemplateFolderContent& _rState ); + + // @return <TRUE/> if the states equal + static bool equalStates( const TemplateFolderContent& _rLHS, const TemplateFolderContent& _rRHS ); + + // late initialize m_xOfficeInstDirs + uno::Reference< util::XOfficeInstallationDirectories > getOfficeInstDirs(); + }; + + + TemplateFolderCacheImpl::TemplateFolderCacheImpl( bool _bAutoStoreState ) + :m_bNeedsUpdate ( true ) + ,m_bKnowState ( false ) + ,m_bValidCurrentState ( false ) + ,m_bAutoStoreState ( _bAutoStoreState ) + { + } + + + TemplateFolderCacheImpl::~TemplateFolderCacheImpl( ) + { + // store the current state if possible and required + if ( m_bValidCurrentState && m_bAutoStoreState ) + storeState(); + + closeCacheStream( ); + } + + + sal_Int32 TemplateFolderCacheImpl::getMagicNumber() + { + return (sal_Int8('T') << 12) + | (sal_Int8('D') << 8) + | (sal_Int8('S') << 4) + | (sal_Int8('C')); + } + + + void TemplateFolderCacheImpl::normalize( TemplateFolderContent& _rState ) + { + SubContentSort()( _rState ); + } + + + bool TemplateFolderCacheImpl::equalStates( const TemplateFolderContent& _rLHS, const TemplateFolderContent& _rRHS ) + { + if ( _rLHS.size() != _rRHS.size() ) + return false; + + // as both arrays are sorted (by definition - this is a precondition of this method) + // we can simply go from the front to the back and compare the single elements + + ::std::pair< ConstFolderIterator, ConstFolderIterator > aFirstDifferent = ::std::mismatch( + _rLHS.begin(), + _rLHS.end(), + _rRHS.begin(), + TemplateContentEqual() + ); + + return aFirstDifferent.first == _rLHS.end(); + } + + + void TemplateFolderCacheImpl::storeState() + { + if ( !m_bValidCurrentState ) + readCurrentState( ); + + if ( !(m_bValidCurrentState && openCacheStream( false )) ) + return; + + m_pCacheStream->WriteInt32( getMagicNumber() ); + + // store the template root folders + // the size + m_pCacheStream->WriteInt32( m_aCurrentState.size() ); + // the complete URLs + ::std::for_each( + m_aCurrentState.begin(), + m_aCurrentState.end(), + StoreContentURL( *m_pCacheStream, getOfficeInstDirs() ) + ); + + // the contents + ::std::for_each( + m_aCurrentState.begin(), + m_aCurrentState.end(), + StoreFolderContent( *m_pCacheStream, getOfficeInstDirs() ) + ); + } + + + OUString TemplateFolderCacheImpl::implParseSmart( const OUString& _rPath ) + { + INetURLObject aParser; + aParser.SetSmartProtocol( INetProtocol::File ); + aParser.SetURL( _rPath ); + if ( INetProtocol::NotValid == aParser.GetProtocol() ) + { + OUString sURL; + osl::FileBase::getFileURLFromSystemPath( _rPath, sURL ); + aParser.SetURL( sURL ); + } + return aParser.GetMainURL( INetURLObject::DecodeMechanism::ToIUri ); + } + + + void TemplateFolderCacheImpl::closeCacheStream( ) + { + m_pCacheStream.reset(); + } + + + bool TemplateFolderCacheImpl::implReadFolder( const ::rtl::Reference< TemplateContent >& _rxRoot ) + { + try + { + // create a content for the current folder root + Reference< XResultSet > xResultSet; + Sequence< OUString > aContentProperties( 4); + aContentProperties[0] = "Title"; + aContentProperties[1] = "DateModified"; + aContentProperties[2] = "DateCreated"; + aContentProperties[3] = "IsFolder"; + + // get the set of sub contents in the folder + try + { + Reference< XDynamicResultSet > xDynResultSet; + + ::ucbhelper::Content aTemplateRoot( _rxRoot->getURL(), Reference< XCommandEnvironment >(), comphelper::getProcessComponentContext() ); + xDynResultSet = aTemplateRoot.createDynamicCursor( aContentProperties ); + if ( xDynResultSet.is() ) + xResultSet = xDynResultSet->getStaticResultSet(); + } + catch( CommandAbortedException& ) + { + SAL_WARN( "svtools.misc", "TemplateFolderCacheImpl::implReadFolder: caught a CommandAbortedException!" ); + return false; + } + catch( css::uno::Exception& ) + { + } + + // collect the infos about the sub contents + if ( xResultSet.is() ) + { + Reference< XRow > xRow( xResultSet, UNO_QUERY_THROW ); + Reference< XContentAccess > xContentAccess( xResultSet, UNO_QUERY_THROW ); + + while ( xResultSet->next() ) + { + INetURLObject aSubContentURL( xContentAccess->queryContentIdentifierString() ); + + // a new content instance + ::rtl::Reference< TemplateContent > xChild = new TemplateContent( aSubContentURL ); + + // the modified date + xChild->setModDate( xRow->getTimestamp( 2 ) ); // date modified + if ( xRow->wasNull() ) + xChild->setModDate( xRow->getTimestamp( 3 ) ); // fallback: date created + + // push back this content + _rxRoot->push_back( xChild ); + + // is it a folder? + if ( xRow->getBoolean( 4 ) && !xRow->wasNull() ) + { // yes -> step down + ConstFolderIterator aNextLevelRoot = _rxRoot->end(); + --aNextLevelRoot; + implReadFolder( *aNextLevelRoot ); + } + } + } + } + catch( const Exception& ) + { + TOOLS_WARN_EXCEPTION( "svtools", "TemplateFolderCacheImpl::implReadFolder" ); + return false; + } + return true; + } + + + bool TemplateFolderCacheImpl::readCurrentState() + { + // reset + m_bValidCurrentState = false; + TemplateFolderContent aTemplateFolderContent; + m_aCurrentState.swap( aTemplateFolderContent ); + + // the template directories from the config + const SvtPathOptions aPathOptions; + const OUString& aDirs = aPathOptions.GetTemplatePath(); + + // loop through all the root-level template folders + sal_Int32 nIndex = 0; + do + { + OUString sTemplatePath( aDirs.getToken(0, ';', nIndex) ); + sTemplatePath = aPathOptions.ExpandMacros( sTemplatePath ); + + // Make sure excess ".." path segments (from expanding bootstrap + // variables in paths) are normalized in the same way they are + // normalized for paths read from the .templdir.cache file (where + // paths have gone through makeRelocatable URL on writing out and + // then through makeAbsoluteURL when reading back in), as otherwise + // equalStates() in needsUpdate() could erroneously consider + // m_aCurrentState and m_aPreviousState as different: + sTemplatePath = getOfficeInstDirs()->makeAbsoluteURL( + getOfficeInstDirs()->makeRelocatableURL(sTemplatePath)); + + // create a new entry + m_aCurrentState.push_back( new TemplateContent( INetURLObject( sTemplatePath ) ) ); + TemplateFolderContent::iterator aCurrentRoot = m_aCurrentState.end(); + --aCurrentRoot; + + if ( !implReadFolder( *aCurrentRoot ) ) + return false; + } + while ( nIndex >= 0 ); + + // normalize the array (which basically means "sort it") + normalize( m_aCurrentState ); + + m_bValidCurrentState = true; + return m_bValidCurrentState; + } + + + bool TemplateFolderCacheImpl::readPreviousState() + { + DBG_ASSERT( m_pCacheStream, "TemplateFolderCacheImpl::readPreviousState: not to be called without stream!" ); + + // reset + TemplateFolderContent aTemplateFolderContent; + m_aPreviousState.swap( aTemplateFolderContent ); + + // check the magic number + sal_Int32 nMagic = 0; + m_pCacheStream->ReadInt32( nMagic ); + DBG_ASSERT( getMagicNumber() == nMagic, "TemplateFolderCacheImpl::readPreviousState: invalid cache file!" ); + if ( getMagicNumber() != nMagic ) + return false; + + // the root directories + // their number + sal_Int32 nRootDirectories = 0; + m_pCacheStream->ReadInt32( nRootDirectories ); + // init empty TemplateContents with the URLs + m_aPreviousState.reserve( nRootDirectories ); + while ( nRootDirectories-- ) + { + OUString sURL = m_pCacheStream->ReadUniOrByteString(m_pCacheStream->GetStreamCharSet()); + // #116281# Keep office installation relocatable. Never store + // any direct references to office installation directory. + sURL = getOfficeInstDirs()->makeAbsoluteURL( sURL ); + m_aPreviousState.push_back( + new TemplateContent( INetURLObject(sURL) ) ); + } + + // read the contents of the root folders + ::std::for_each( + m_aPreviousState.begin(), + m_aPreviousState.end(), + ReadFolderContent( *m_pCacheStream, getOfficeInstDirs() ) + ); + + DBG_ASSERT( !m_pCacheStream->GetErrorCode(), "TemplateFolderCacheImpl::readPreviousState: unknown error during reading the state cache!" ); + + // normalize the array (which basically means "sort it") + normalize( m_aPreviousState ); + + return true; + } + + + bool TemplateFolderCacheImpl::openCacheStream( bool _bForRead ) + { + // close any old stream instance + closeCacheStream( ); + + // get the storage directory + OUString sStorageURL = implParseSmart( SvtPathOptions().GetStoragePath() ); + INetURLObject aStorageURL( sStorageURL ); + if ( INetProtocol::NotValid == aStorageURL.GetProtocol() ) + { + OSL_FAIL( "TemplateFolderCacheImpl::openCacheStream: invalid storage path!" ); + return false; + } + + // append our name + aStorageURL.Append( ".templdir.cache" ); + + // open the stream + m_pCacheStream = UcbStreamHelper::CreateStream( aStorageURL.GetMainURL( INetURLObject::DecodeMechanism::ToIUri ), + _bForRead ? StreamMode::READ | StreamMode::NOCREATE : StreamMode::WRITE | StreamMode::TRUNC ); + DBG_ASSERT( m_pCacheStream, "TemplateFolderCacheImpl::openCacheStream: could not open/create the cache stream!" ); + if ( m_pCacheStream && m_pCacheStream->GetErrorCode() ) + { + m_pCacheStream.reset(); + } + + if ( m_pCacheStream ) + m_pCacheStream->SetStreamCharSet( RTL_TEXTENCODING_UTF8 ); + + return nullptr != m_pCacheStream; + } + + + bool TemplateFolderCacheImpl::needsUpdate() + { + if ( m_bKnowState ) + return m_bNeedsUpdate; + + m_bNeedsUpdate = true; + m_bKnowState = true; + + if ( readCurrentState() ) + { + // open the stream which contains the cached state of the directories + if ( openCacheStream( true ) ) + { // opening the stream succeeded + if ( readPreviousState() ) + { + m_bNeedsUpdate = !equalStates( m_aPreviousState, m_aCurrentState ); + } + else + { + closeCacheStream(); + } + } + } + return m_bNeedsUpdate; + } + + + uno::Reference< util::XOfficeInstallationDirectories > + TemplateFolderCacheImpl::getOfficeInstDirs() + { + if ( !m_xOfficeInstDirs.is() ) + { + osl::MutexGuard aGuard( m_aMutex ); + if ( !m_xOfficeInstDirs.is() ) + { + uno::Reference< uno::XComponentContext > xCtx( + comphelper::getProcessComponentContext() ); + m_xOfficeInstDirs = util::theOfficeInstallationDirectories::get(xCtx); + } + } + return m_xOfficeInstDirs; + } + + + //= TemplateFolderCache + + + TemplateFolderCache::TemplateFolderCache( bool _bAutoStoreState ) + :m_pImpl( new TemplateFolderCacheImpl( _bAutoStoreState ) ) + { + } + + + TemplateFolderCache::~TemplateFolderCache( ) + { + } + + + bool TemplateFolderCache::needsUpdate() + { + return m_pImpl->needsUpdate(); + } + + + void TemplateFolderCache::storeState() + { + m_pImpl->storeState(); + } + + +} // namespace sfx2 + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/misc/unitconv.cxx b/svtools/source/misc/unitconv.cxx new file mode 100644 index 000000000..93dab6ada --- /dev/null +++ b/svtools/source/misc/unitconv.cxx @@ -0,0 +1,618 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <svtools/unitconv.hxx> +#include <tools/debug.hxx> +#include <vcl/outdev.hxx> +#include <vcl/weld.hxx> + +void SetFieldUnit(weld::MetricSpinButton& rField, FieldUnit eUnit, bool bAll) +{ + int nMin, nMax; + rField.get_range(nMin, nMax, FieldUnit::TWIP); + int nValue = rField.get_value(FieldUnit::TWIP); + nMin = rField.denormalize(nMin); + nMax = rField.denormalize(nMax); + nValue = rField.denormalize(nValue); + + if (!bAll) + { + switch (eUnit) + { + case FieldUnit::M: + case FieldUnit::KM: + eUnit = FieldUnit::CM; + break; + case FieldUnit::FOOT: + case FieldUnit::MILE: + eUnit = FieldUnit::INCH; + break; + default: //prevent warning + break; + } + } + + rField.set_unit(eUnit); + + if (FieldUnit::POINT == eUnit) + { + if (rField.get_digits() > 1) + rField.set_digits(1); + } + else + rField.set_digits(2); + + switch (eUnit) + { + // _CHAR and _LINE sets the step of "char" and "line" unit, they are same as FieldUnit::MM + case FieldUnit::CHAR: + case FieldUnit::LINE: + case FieldUnit::MM: + rField.set_increments(50, 500, eUnit); + break; + case FieldUnit::INCH: + rField.set_increments(2, 20, eUnit); + break; + default: + rField.set_increments(10, 100, eUnit); + break; + } + + if (!bAll) + { + nMin = rField.normalize(nMin); + nMax = rField.normalize(nMax); + rField.set_range(nMin, nMax, FieldUnit::TWIP); + } + + rField.set_value(rField.normalize(nValue), FieldUnit::TWIP); +} + +void SetMetricValue(weld::MetricSpinButton& rField, int nCoreValue, MapUnit eUnit) +{ + auto nVal = OutputDevice::LogicToLogic(nCoreValue, eUnit, MapUnit::Map100thMM); + nVal = rField.normalize(nVal); + rField.set_value(nVal, FieldUnit::MM_100TH); +} + +int GetCoreValue(const weld::MetricSpinButton& rField, MapUnit eUnit) +{ + int nVal = rField.get_value(FieldUnit::MM_100TH); + // avoid rounding issues + const int nSizeMask = 0xff000000; + bool bRoundBefore = true; + if( nVal >= 0 ) + { + if( (nVal & nSizeMask) == 0 ) + bRoundBefore = false; + } + else + { + if( ((-nVal) & nSizeMask ) == 0 ) + bRoundBefore = false; + } + if( bRoundBefore ) + nVal = rField.denormalize( nVal ); + auto nUnitVal = OutputDevice::LogicToLogic(nVal, MapUnit::Map100thMM, eUnit); + if (!bRoundBefore) + nUnitVal = rField.denormalize(nUnitVal); + return nUnitVal; +} + +long CalcToUnit( float nIn, MapUnit eUnit ) +{ + // nIn is in Points + + DBG_ASSERT( eUnit == MapUnit::MapTwip || + eUnit == MapUnit::Map100thMM || + eUnit == MapUnit::Map10thMM || + eUnit == MapUnit::MapMM || + eUnit == MapUnit::MapCM, "this unit is not implemented" ); + + float nTmp = nIn; + + if ( MapUnit::MapTwip != eUnit ) + nTmp = nIn * 10 / 567; + + switch ( eUnit ) + { + case MapUnit::Map100thMM: nTmp *= 100; break; + case MapUnit::Map10thMM: nTmp *= 10; break; + case MapUnit::MapMM: break; + case MapUnit::MapCM: nTmp /= 10; break; + default: ;//prevent warning + } + + nTmp *= 20; + long nRet = static_cast<long>(nTmp); + return nRet; +//! return (long)(nTmp * 20); +} + + +long ItemToControl( long nIn, MapUnit eItem, FieldUnit eCtrl ) +{ + long nOut = 0; + + switch ( eItem ) + { + case MapUnit::Map100thMM: + case MapUnit::Map10thMM: + case MapUnit::MapMM: + { + if ( eItem == MapUnit::Map10thMM ) + nIn /= 10; + else if ( eItem == MapUnit::Map100thMM ) + nIn /= 100; + nOut = TransformMetric( nIn, FieldUnit::MM, eCtrl ); + } + break; + + case MapUnit::MapCM: + { + nOut = TransformMetric( nIn, FieldUnit::CM, eCtrl ); + } + break; + + case MapUnit::Map1000thInch: + case MapUnit::Map100thInch: + case MapUnit::Map10thInch: + case MapUnit::MapInch: + { + if ( eItem == MapUnit::Map10thInch ) + nIn /= 10; + else if ( eItem == MapUnit::Map100thInch ) + nIn /= 100; + else if ( eItem == MapUnit::Map1000thInch ) + nIn /= 1000; + nOut = TransformMetric( nIn, FieldUnit::INCH, eCtrl ); + } + break; + + case MapUnit::MapPoint: + { + nOut = TransformMetric( nIn, FieldUnit::POINT, eCtrl ); + } + break; + + case MapUnit::MapTwip: + { + nOut = TransformMetric( nIn, FieldUnit::TWIP, eCtrl ); + } + break; + default: ;//prevent warning + } + return nOut; +} + + +long ControlToItem( long nIn, FieldUnit eCtrl, MapUnit eItem ) +{ + return ItemToControl( nIn, eItem, eCtrl ); +} + + +FieldUnit MapToFieldUnit( const MapUnit eUnit ) +{ + switch ( eUnit ) + { + case MapUnit::Map100thMM: + case MapUnit::Map10thMM: + case MapUnit::MapMM: + return FieldUnit::MM; + + case MapUnit::MapCM: + return FieldUnit::CM; + + case MapUnit::Map1000thInch: + case MapUnit::Map100thInch: + case MapUnit::Map10thInch: + case MapUnit::MapInch: + return FieldUnit::INCH; + + case MapUnit::MapPoint: + return FieldUnit::POINT; + + case MapUnit::MapTwip: + return FieldUnit::TWIP; + default: ;//prevent warning + } + return FieldUnit::NONE; +} + + +long CalcToPoint( long nIn, MapUnit eUnit, sal_uInt16 nFactor ) +{ + DBG_ASSERT( eUnit == MapUnit::MapTwip || + eUnit == MapUnit::Map100thMM || + eUnit == MapUnit::Map10thMM || + eUnit == MapUnit::MapMM || + eUnit == MapUnit::MapCM, "this unit is not implemented" ); + + long nRet = 0; + + if ( MapUnit::MapTwip == eUnit ) + nRet = nIn; + else + nRet = nIn * 567; + + switch ( eUnit ) + { + case MapUnit::Map100thMM: nRet /= 100; break; + case MapUnit::Map10thMM: nRet /= 10; break; + case MapUnit::MapMM: break; + case MapUnit::MapCM: nRet *= 10; break; + default: ;//prevent warning + } + + // round up if necessary + if ( MapUnit::MapTwip != eUnit ) + { + long nTmp = nRet % 10; + + if ( nTmp >= 4 ) + nRet += 10 - nTmp; + nRet /= 10; + } + return nRet * nFactor / 20; +} + + +static long CMToTwips( long nIn ) +{ + long nRet = 0; + + if ( nIn <= ( LONG_MAX / 567 ) && nIn >= ( LONG_MIN / 567 ) ) + nRet = nIn * 567; + return nRet; +} + + +static long MMToTwips( long nIn ) +{ + long nRet = 0; + + if ( nIn <= ( LONG_MAX / 567 ) && nIn >= ( LONG_MIN / 567 ) ) + nRet = nIn * 567 / 10; + return nRet; +} + + +static long InchToTwips( long nIn ) +{ + long nRet = 0; + + if ( nIn <= ( LONG_MAX / 1440 ) && nIn >= ( LONG_MIN / 1440 ) ) + nRet = nIn * 1440; + return nRet; +} + + +long PointToTwips( long nIn ) +{ + long nRet = 0; + + if ( nIn <= ( LONG_MAX / 20 ) && nIn >= ( LONG_MIN / 20 ) ) + nRet = nIn * 20; + return nRet; +} + + +static long PicaToTwips( long nIn ) +{ + long nRet = 0; + + if ( nIn <= ( LONG_MAX / 240 ) && nIn >= ( LONG_MIN / 240 ) ) + nRet = nIn * 240; + return nRet; +} + + +static long TwipsToCM( long nIn ) +{ + long nRet = nIn / 567; + return nRet; +} + + +static long InchToCM( long nIn ) +{ + long nRet = 0; + + if ( nIn <= ( LONG_MAX / 254 ) && nIn >= ( LONG_MIN / 254 ) ) + nRet = nIn * 254 / 100; + return nRet; +} + + +static long MMToCM( long nIn ) +{ + long nRet = nIn / 10; + return nRet; +} + + +static long PointToCM( long nIn ) +{ + long nRet = 0; + + if ( nIn <= ( LONG_MAX / 20 ) && nIn >= ( LONG_MIN / 20 ) ) + nRet = nIn * 20 / 567; + return nRet; +} + + +static long PicaToCM( long nIn) +{ + long nRet = 0; + + if ( nIn <= ( LONG_MAX / 12 / 20 ) && nIn >= ( LONG_MIN / 12 / 20 ) ) + nRet = nIn * 12 * 20 / 567; + return nRet; +} + + +static long TwipsToMM( long nIn ) +{ + long nRet = 0; + + if ( nIn <= ( LONG_MAX / 10 ) && nIn >= ( LONG_MIN / 10 ) ) + nRet = nIn * 10 / 566; + return nRet; +} + + +static long CMToMM( long nIn ) +{ + long nRet = 0; + + if ( nIn <= ( LONG_MAX / 10 ) && nIn >= ( LONG_MIN / 10 ) ) + nRet = nIn * 10; + return nRet; +} + + +static long InchToMM( long nIn ) +{ + long nRet = 0; + + if ( nIn <= ( LONG_MAX / 254 ) && nIn >= ( LONG_MIN / 254 ) ) + nRet = nIn * 254 / 10; + return nRet; +} + + +static long PointToMM( long nIn ) +{ + long nRet = 0; + + if ( nIn <= ( LONG_MAX / 200 ) && nIn >= ( LONG_MIN / 200 ) ) + nRet = nIn * 200 / 567; + return nRet; +} + + +static long PicaToMM( long nIn ) +{ + long nRet = 0; + + if ( nIn <= ( LONG_MAX / 12 / 200 ) && nIn >= ( LONG_MIN / 12 / 200 ) ) + nRet = nIn * 12 * 200 / 567; + return nRet; +} + + +static long TwipsToInch( long nIn ) +{ + long nRet = nIn / 1440; + return nRet; +} + + +static long CMToInch( long nIn ) +{ + long nRet = 0; + + if ( nIn <= ( LONG_MAX / 100 ) && nIn >= ( LONG_MIN / 100 ) ) + nRet = nIn * 100 / 254; + return nRet; +} + + +static long MMToInch( long nIn ) +{ + long nRet = 0; + + if ( nIn <= ( LONG_MAX / 10 ) && nIn >= ( LONG_MIN / 10 ) ) + nRet = nIn * 10 / 254; + return nRet; +} + + +static long PointToInch( long nIn ) +{ + long nRet = nIn / 72; + return nRet; +} + + +static long PicaToInch( long nIn ) +{ + long nRet = nIn / 6; + return nRet; +} + + +static long TwipsToPoint( long nIn ) +{ + long nRet = nIn / 20; + return nRet; +} + + +static long InchToPoint( long nIn ) +{ + long nRet = 0; + + if ( nIn <= ( LONG_MAX / 72 ) && nIn >= ( LONG_MIN / 72 ) ) + nRet = nIn * 72; + return nRet; +} + + +static long CMToPoint( long nIn ) +{ + long nRet = 0; + + if ( nIn <= ( LONG_MAX / 567 ) && nIn >= ( LONG_MIN / 567 ) ) + nRet = nIn * 567 / 20; + return nRet; +} + + +static long MMToPoint( long nIn ) +{ + long nRet = 0; + + if ( nIn <= ( LONG_MAX / 567 ) && nIn >= ( LONG_MIN / 567 ) ) + nRet = nIn * 567 / 200; + return nRet; +} + + +static long PicaToPoint( long nIn ) +{ + long nRet = nIn / 12; + return nRet; +} + + +static long TwipsToPica( long nIn ) +{ + long nRet = nIn / 240; + return nRet; +} + + +static long InchToPica( long nIn ) +{ + long nRet = 0; + + if ( nIn <= ( LONG_MAX / 6 ) && nIn >= ( LONG_MIN / 6 ) ) + nRet = nIn * 6; + return nRet; +} + + +static long PointToPica( long nIn ) +{ + long nRet = 0; + + if ( nIn <= ( LONG_MAX / 12 ) && nIn >= ( LONG_MIN / 12 ) ) + nRet = nIn * 12; + return nRet; +} + + +static long CMToPica( long nIn ) +{ + long nRet = 0; + + if ( nIn <= ( LONG_MAX / 567 ) && nIn >= ( LONG_MIN / 567 ) ) + nRet = nIn * 567 / 20 / 12; + return nRet; +} + + +static long MMToPica( long nIn ) +{ + long nRet = 0; + + if ( nIn <= ( LONG_MAX / 567 ) && nIn >= ( LONG_MIN / 567 ) ) + nRet = nIn * 567 / 200 / 12; + return nRet; +} + + +static long Nothing( long nIn ) +{ + long nRet = nIn; + return nRet; +} + +FUNC_CONVERT const ConvertTable[6][6] = +{ +// CM, MM INCH POINT PICAS=32 TWIPS + { Nothing, CMToMM, CMToInch, CMToPoint, CMToPica, CMToTwips }, + { MMToCM, Nothing, MMToInch, MMToPoint, MMToPica, MMToTwips }, + { InchToCM, InchToMM, Nothing, InchToPoint, InchToPica, InchToTwips }, + { PointToCM, PointToMM, PointToInch, Nothing, PointToPica, PointToTwips }, + { PicaToCM, PicaToMM, PicaToInch, PicaToPoint, Nothing, PicaToTwips }, + { TwipsToCM, TwipsToMM, TwipsToInch, TwipsToPoint,TwipsToPica, Nothing } +}; + + +long TransformMetric( long nVal, FieldUnit aOld, FieldUnit aNew ) +{ + if ( aOld == FieldUnit::NONE || aNew == FieldUnit::NONE || + aOld == FieldUnit::CUSTOM || aNew == FieldUnit::CUSTOM ) + { + return nVal; + } + + sal_uInt16 nOld = 0; + sal_uInt16 nNew = 0; + + switch ( aOld ) + { + case FieldUnit::CM: + nOld = 0; break; + case FieldUnit::MM: + nOld = 1; break; + case FieldUnit::INCH: + nOld = 2; break; + case FieldUnit::POINT: + nOld = 3; break; + case FieldUnit::PICA: + nOld = 4; break; + case FieldUnit::TWIP: + nOld = 5; break; + default: ;//prevent warning + } + + switch ( aNew ) + { + case FieldUnit::CM: + nNew = 0; break; + case FieldUnit::MM: + nNew = 1; break; + case FieldUnit::INCH: + nNew = 2; break; + case FieldUnit::POINT: + nNew = 3; break; + case FieldUnit::PICA: + nNew = 4; break; + case FieldUnit::TWIP: + nNew = 5; break; + default: ;//prevent warning + } + return ConvertTable[nOld][nNew]( nVal ); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/svhtml/HtmlWriter.cxx b/svtools/source/svhtml/HtmlWriter.cxx new file mode 100644 index 000000000..7414b40b1 --- /dev/null +++ b/svtools/source/svhtml/HtmlWriter.cxx @@ -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/. + * + */ + +#include <svtools/HtmlWriter.hxx> +#include <tools/stream.hxx> + +HtmlWriter::HtmlWriter(SvStream& rStream, const OString& rNamespace) : + mrStream(rStream), + mbElementOpen(false), + mbCharactersWritten(false), + mbPrettyPrint(true) +{ + if (!rNamespace.isEmpty()) + { + // Convert namespace alias to a prefix. + maNamespace = rNamespace + ":"; + } +} + +HtmlWriter::~HtmlWriter() +{} + +void HtmlWriter::prettyPrint(bool b) +{ + mbPrettyPrint = b; +} + +void HtmlWriter::start(const OString& aElement) +{ + if (mbElementOpen) + { + mrStream.WriteChar('>'); + if (mbPrettyPrint) + mrStream.WriteChar('\n'); + } + maElementStack.push_back(aElement); + + if (mbPrettyPrint) + { + for(size_t i = 0; i < maElementStack.size() - 1; i++) + { + mrStream.WriteCharPtr(" "); + } + } + + mrStream.WriteChar('<'); + mrStream.WriteOString(maNamespace + aElement); + mbElementOpen = true; +} + +void HtmlWriter::single(const OString &aContent) +{ + start(aContent); + end(); +} + +void HtmlWriter::endAttribute() +{ + if (mbElementOpen) + { + mrStream.WriteCharPtr("/>"); + if (mbPrettyPrint) + mrStream.WriteCharPtr("\n"); + mbElementOpen = false; + } +} + +void HtmlWriter::flushStack() +{ + while (!maElementStack.empty()) + { + end(); + } +} + +void HtmlWriter::end() +{ + if (mbElementOpen && !mbCharactersWritten) + { + mrStream.WriteCharPtr("/>"); + if (mbPrettyPrint) + mrStream.WriteCharPtr("\n"); + } + else + { + if (mbPrettyPrint) + { + for(size_t i = 0; i < maElementStack.size() - 1; i++) + { + mrStream.WriteCharPtr(" "); + } + } + mrStream.WriteCharPtr("</"); + mrStream.WriteOString(maNamespace + maElementStack.back()); + mrStream.WriteCharPtr(">"); + if (mbPrettyPrint) + mrStream.WriteCharPtr("\n"); + } + maElementStack.pop_back(); + mbElementOpen = false; + mbCharactersWritten = false; +} + +void HtmlWriter::attribute(const OString &aAttribute, const OString& aValue) +{ + if (mbElementOpen && !aAttribute.isEmpty() && !aValue.isEmpty()) + { + mrStream.WriteChar(' '); + mrStream.WriteOString(aAttribute); + mrStream.WriteChar('='); + mrStream.WriteChar('"'); + mrStream.WriteOString(aValue); + mrStream.WriteChar('"'); + } +} + +void HtmlWriter::attribute(const OString& aAttribute, const sal_Int32 aValue) +{ + attribute(aAttribute, OString::number(aValue)); +} + +void HtmlWriter::attribute(const OString& aAttribute, const char* pValue) +{ + attribute(aAttribute, OString(pValue)); +} + +void HtmlWriter::attribute(const OString& aAttribute, const OUString& aValue) +{ + attribute(aAttribute, OUStringToOString(aValue, RTL_TEXTENCODING_UTF8)); +} + +void HtmlWriter::attribute(const OString& aAttribute) +{ + if (mbElementOpen && !aAttribute.isEmpty()) + { + mrStream.WriteChar(' '); + mrStream.WriteOString(aAttribute); + } +} + +void HtmlWriter::characters(const OString& rChars) +{ + if (!mbCharactersWritten) + mrStream.WriteCharPtr(">"); + mrStream.WriteOString(rChars); + mbCharactersWritten = true; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/svhtml/htmlkywd.cxx b/svtools/source/svhtml/htmlkywd.cxx new file mode 100644 index 000000000..70bc2ebe4 --- /dev/null +++ b/svtools/source/svhtml/htmlkywd.cxx @@ -0,0 +1,812 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <algorithm> +#include <sal/types.h> +#include <string.h> +#include <rtl/ustring.hxx> +#include <svtools/htmltokn.h> +#include <svtools/htmlkywd.hxx> + +namespace { + +template<typename T> +struct TokenEntry +{ + OUStringLiteral sToken; + T nToken; +}; + +} + +template<typename T> +static bool sortCompare(const TokenEntry<T> & lhs, const TokenEntry<T> & rhs) +{ + return strcmp(lhs.sToken.data, rhs.sToken.data) < 0; +} +template<typename T> +static bool findCompare(const TokenEntry<T> & lhs, const OUString & rhs) +{ + return rhs.compareToAscii(lhs.sToken.data) > 0; +} +template<typename T, size_t LEN> +static T search(TokenEntry<T> const (&dataTable)[LEN], const OUString & key, T notFoundValue) +{ + auto findIt = std::lower_bound( std::begin(dataTable), std::end(dataTable), + key, findCompare<T> ); + if (findIt != std::end(dataTable) && key.compareToAscii(findIt->sToken.data)==0) + return findIt->nToken; + return notFoundValue; +} + +using HTML_TokenEntry = TokenEntry<HtmlTokenId>; + +// this array is sorted by the name (even if it doesn't look like it from the constant names) +static HTML_TokenEntry const aHTMLTokenTab[] = { + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_comment), HtmlTokenId::COMMENT}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_doctype), HtmlTokenId::DOCTYPE}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_anchor), HtmlTokenId::ANCHOR_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_abbreviation), HtmlTokenId::ABBREVIATION_ON}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_acronym), HtmlTokenId::ACRONYM_ON}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_address), HtmlTokenId::ADDRESS_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_applet), HtmlTokenId::APPLET_ON}, // HotJava + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_area), HtmlTokenId::AREA}, // Netscape 2.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_author), HtmlTokenId::AUTHOR_ON}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_bold), HtmlTokenId::BOLD_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_banner), HtmlTokenId::BANNER_ON}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_base), HtmlTokenId::BASE}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_basefont), HtmlTokenId::BASEFONT_ON}, // Netscape + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_bigprint), HtmlTokenId::BIGPRINT_ON}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_blink), HtmlTokenId::BLINK_ON}, // Netscape + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_blockquote), HtmlTokenId::BLOCKQUOTE_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_body), HtmlTokenId::BODY_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_blockquote30), HtmlTokenId::BLOCKQUOTE30_ON}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_linebreak), HtmlTokenId::LINEBREAK}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_caption), HtmlTokenId::CAPTION_ON}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_center), HtmlTokenId::CENTER_ON}, // Netscape + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_citiation), HtmlTokenId::CITIATION_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_code), HtmlTokenId::CODE_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_col), HtmlTokenId::COL_ON}, // HTML 3 Table Model Draft + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_colgroup), HtmlTokenId::COLGROUP_ON}, // HTML 3 Table Model Draft + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_comment2), HtmlTokenId::COMMENT2_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_credit), HtmlTokenId::CREDIT_ON}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_dd), HtmlTokenId::DD_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_deletedtext), HtmlTokenId::DELETEDTEXT_ON}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_definstance), HtmlTokenId::DEFINSTANCE_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_dirlist), HtmlTokenId::DIRLIST_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_division), HtmlTokenId::DIVISION_ON}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_deflist), HtmlTokenId::DEFLIST_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_dt), HtmlTokenId::DT_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_emphasis), HtmlTokenId::EMPHASIS_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_embed), HtmlTokenId::EMBED}, // Netscape 2.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_figure), HtmlTokenId::FIGURE_ON}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_footnote), HtmlTokenId::FOOTNOTE_ON}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_font), HtmlTokenId::FONT_ON}, // Netscape + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_form), HtmlTokenId::FORM_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_frame), HtmlTokenId::FRAME_ON}, // Netscape 2.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_frameset), HtmlTokenId::FRAMESET_ON}, // Netscape 2.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_head1), HtmlTokenId::HEAD1_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_head2), HtmlTokenId::HEAD2_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_head3), HtmlTokenId::HEAD3_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_head4), HtmlTokenId::HEAD4_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_head5), HtmlTokenId::HEAD5_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_head6), HtmlTokenId::HEAD6_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_head), HtmlTokenId::HEAD_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_horzrule), HtmlTokenId::HORZRULE}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_html), HtmlTokenId::HTML_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_italic), HtmlTokenId::ITALIC_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_iframe), HtmlTokenId::IFRAME_ON}, // IE 3.0b2 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_image), HtmlTokenId::IMAGE}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_input), HtmlTokenId::INPUT}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_insertedtext), HtmlTokenId::INSERTEDTEXT_ON}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_keyboard), HtmlTokenId::KEYBOARD_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_language), HtmlTokenId::LANGUAGE_ON}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_listheader), HtmlTokenId::LISTHEADER_ON}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_li), HtmlTokenId::LI_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_link), HtmlTokenId::LINK}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_listing), HtmlTokenId::LISTING_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_map), HtmlTokenId::MAP_ON}, // Netscape 2.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_marquee), HtmlTokenId::MARQUEE_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_menulist), HtmlTokenId::MENULIST_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_meta), HtmlTokenId::META}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_multicol), HtmlTokenId::MULTICOL_ON}, // Netscape 3.0b5 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_nobr), HtmlTokenId::NOBR_ON}, // Netscape + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_noembed), HtmlTokenId::NOEMBED_ON}, // Netscape 2.0 ??? + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_noframe), HtmlTokenId::NOFRAMES_ON}, // Netscape 2.0 ??? + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_noframes), HtmlTokenId::NOFRAMES_ON}, // Netscape 2.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_noscript), HtmlTokenId::NOSCRIPT_ON}, // Netscape 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_note), HtmlTokenId::NOTE_ON}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_object), HtmlTokenId::OBJECT_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_orderlist), HtmlTokenId::ORDERLIST_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_option), HtmlTokenId::OPTION}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_parabreak), HtmlTokenId::PARABREAK_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_param), HtmlTokenId::PARAM}, // HotJava + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_person), HtmlTokenId::PERSON_ON}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_plaintext2), HtmlTokenId::PLAINTEXT2_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_preformtxt), HtmlTokenId::PREFORMTXT_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_shortquote), HtmlTokenId::SHORTQUOTE_ON}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_strikethrough), HtmlTokenId::STRIKETHROUGH_ON}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_sample), HtmlTokenId::SAMPLE_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_script), HtmlTokenId::SCRIPT_ON}, // HTML 3.2 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_sdfield), HtmlTokenId::SDFIELD_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_select), HtmlTokenId::SELECT_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_smallprint), HtmlTokenId::SMALLPRINT_ON}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_spacer), HtmlTokenId::SPACER}, // Netscape 3.0b5 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_span), HtmlTokenId::SPAN_ON}, // Style Sheets + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_strike), HtmlTokenId::STRIKE_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_strong), HtmlTokenId::STRONG_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_style), HtmlTokenId::STYLE_ON}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_subscript), HtmlTokenId::SUBSCRIPT_ON}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_superscript), HtmlTokenId::SUPERSCRIPT_ON}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_plaintext), HtmlTokenId::PLAINTEXT_ON}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_table), HtmlTokenId::TABLE_ON}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_tbody), HtmlTokenId::TBODY_ON}, // HTML 3 Table Model Draft + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_tabledata), HtmlTokenId::TABLEDATA_ON}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_textarea), HtmlTokenId::TEXTAREA_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_tfoot), HtmlTokenId::TFOOT_ON}, // HTML 3 Table Model Draft + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_tableheader), HtmlTokenId::TABLEHEADER_ON}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_thead), HtmlTokenId::THEAD_ON}, // HTML 3 Table Model Draft + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_title), HtmlTokenId::TITLE_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_tablerow), HtmlTokenId::TABLEROW_ON}, // HTML 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_teletype), HtmlTokenId::TELETYPE_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_underline), HtmlTokenId::UNDERLINE_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_unorderlist), HtmlTokenId::UNORDERLIST_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_variable), HtmlTokenId::VARIABLE_ON}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_xmp), HtmlTokenId::XMP_ON}, +}; + + +HtmlTokenId GetHTMLToken( const OUString& rName ) +{ + static bool bSortKeyWords = false; + if( !bSortKeyWords ) + { + assert( std::is_sorted( std::begin(aHTMLTokenTab), std::end(aHTMLTokenTab), sortCompare<HtmlTokenId> ) ); + bSortKeyWords = true; + } + + if( rName.startsWith( OOO_STRING_SVTOOLS_HTML_comment )) + return HtmlTokenId::COMMENT; + + return search( aHTMLTokenTab, rName, HtmlTokenId::NONE); +} + +using HTML_CharEntry = TokenEntry<sal_Unicode>; + +// Flag: RTF token table has already been sorted +static bool bSortCharKeyWords = false; + +static HTML_CharEntry aHTMLCharNameTab[] = { + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_lt), 60}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_gt), 62}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_amp), 38}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_quot), 34}, + + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_Agrave), 192}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_Aacute), 193}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_Acirc), 194}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_Atilde), 195}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_Auml), 196}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_Aring), 197}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_AElig), 198}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_Ccedil), 199}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_Egrave), 200}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_Eacute), 201}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_Ecirc), 202}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_Euml), 203}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_Igrave), 204}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_Iacute), 205}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_Icirc), 206}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_Iuml), 207}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_ETH), 208}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_Ntilde), 209}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_Ograve), 210}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_Oacute), 211}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_Ocirc), 212}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_Otilde), 213}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_Ouml), 214}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_Oslash), 216}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_Ugrave), 217}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_Uacute), 218}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_Ucirc), 219}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_Uuml), 220}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_Yacute), 221}, + + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_THORN), 222}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_C_szlig), 223}, + + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_agrave), 224}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_aacute), 225}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_acirc), 226}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_atilde), 227}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_auml), 228}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_aring), 229}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_aelig), 230}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_ccedil), 231}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_egrave), 232}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_eacute), 233}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_ecirc), 234}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_euml), 235}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_igrave), 236}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_iacute), 237}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_icirc), 238}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_iuml), 239}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_eth), 240}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_ntilde), 241}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_ograve), 242}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_oacute), 243}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_ocirc), 244}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_otilde), 245}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_ouml), 246}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_oslash), 248}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_ugrave), 249}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_uacute), 250}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_ucirc), 251}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_uuml), 252}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_yacute), 253}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_thorn), 254}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_yuml), 255}, + +// special characters + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_acute), 180}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_brvbar), 166}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_cedil), 184}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_cent), 162}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_copy), 169}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_curren), 164}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_deg), 176}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_divide), 247}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_frac12), 189}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_frac14), 188}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_frac34), 190}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_iexcl), 161}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_iquest), 191}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_laquo), 171}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_macr), 175}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_micro), 181}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_middot), 183}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_not), 172}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_ordf), 170}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_ordm), 186}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_para), 182}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_plusmn), 177}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_pound), 163}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_raquo), 187}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_reg), 174}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_sect), 167}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_sup1), 185}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_sup2), 178}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_sup3), 179}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_times), 215}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_uml), 168}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_yen), 165}, + +// special characters), which will be converted to tokens !!! + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_nbsp), 1}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_shy), 2}, + + +// HTML4 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_OElig), 338}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_oelig), 339}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_Scaron), 352}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_scaron), 353}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_Yuml), 376}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_fnof), 402}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_circ), 710}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_tilde), 732}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_Alpha), 913}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_Beta), 914}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_Gamma), 915}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_Delta), 916}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_Epsilon), 917}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_Zeta), 918}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_Eta), 919}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_Theta), 920}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_Iota), 921}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_Kappa), 922}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_Lambda), 923}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_Mu), 924}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_Nu), 925}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_Xi), 926}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_Omicron), 927}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_Pi), 928}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_Rho), 929}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_Sigma), 931}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_Tau), 932}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_Upsilon), 933}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_Phi), 934}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_Chi), 935}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_Psi), 936}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_Omega), 937}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_alpha), 945}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_beta), 946}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_gamma), 947}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_delta), 948}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_epsilon), 949}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_zeta), 950}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_eta), 951}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_theta), 952}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_iota), 953}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_kappa), 954}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_lambda), 955}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_mu), 956}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_nu), 957}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_xi), 958}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_omicron), 959}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_pi), 960}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_rho), 961}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_sigmaf), 962}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_sigma), 963}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_tau), 964}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_upsilon), 965}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_phi), 966}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_chi), 967}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_psi), 968}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_omega), 969}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_thetasym), 977}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_upsih), 978}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_piv), 982}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_ensp), 8194}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_emsp), 8195}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_thinsp), 8201}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_zwnj), 8204}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_zwj), 8205}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_lrm), 8206}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_rlm), 8207}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_ndash), 8211}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_mdash), 8212}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_lsquo), 8216}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_rsquo), 8217}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_sbquo), 8218}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_ldquo), 8220}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_rdquo), 8221}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_bdquo), 8222}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_dagger), 8224}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_Dagger), 8225}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_bull), 8226}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_hellip), 8230}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_permil), 8240}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_prime), 8242}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_Prime), 8243}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_lsaquo), 8249}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_rsaquo), 8250}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_oline), 8254}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_frasl), 8260}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_euro), 8364}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_image), 8465}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_weierp), 8472}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_real), 8476}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_trade), 8482}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_alefsym), 8501}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_larr), 8592}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_uarr), 8593}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_rarr), 8594}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_darr), 8595}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_harr), 8596}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_crarr), 8629}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_lArr), 8656}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_uArr), 8657}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_rArr), 8658}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_dArr), 8659}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_hArr), 8660}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_forall), 8704}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_part), 8706}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_exist), 8707}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_empty), 8709}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_nabla), 8711}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_isin), 8712}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_notin), 8713}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_ni), 8715}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_prod), 8719}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_sum), 8721}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_minus), 8722}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_lowast), 8727}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_radic), 8730}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_prop), 8733}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_infin), 8734}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_ang), 8736}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_and), 8743}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_or), 8744}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_cap), 8745}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_cup), 8746}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_int), 8747}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_there4), 8756}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_sim), 8764}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_cong), 8773}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_asymp), 8776}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_ne), 8800}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_equiv), 8801}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_le), 8804}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_ge), 8805}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_sub), 8834}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_sup), 8835}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_nsub), 8836}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_sube), 8838}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_supe), 8839}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_oplus), 8853}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_otimes), 8855}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_perp), 8869}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_sdot), 8901}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_lceil), 8968}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_rceil), 8969}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_lfloor), 8970}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_rfloor), 8971}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_lang), 9001}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_rang), 9002}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_loz), 9674}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_spades), 9824}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_clubs), 9827}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_hearts), 9829}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_S_diams), 9830} +}; + +sal_Unicode GetHTMLCharName( const OUString& rName ) +{ + if( !bSortCharKeyWords ) + { + std::sort( std::begin(aHTMLCharNameTab), std::end(aHTMLCharNameTab), + sortCompare<sal_Unicode> ); + bSortCharKeyWords = true; + } + + return search<sal_Unicode>( aHTMLCharNameTab, rName, 0); +} + +// Flag: Options table has already been sorted +static bool bSortOptionKeyWords = false; + +using HTML_OptionEntry = TokenEntry<HtmlOptionId>; + +static HTML_OptionEntry aHTMLOptionTab[] = { + +// Attributes without value + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_checked), HtmlOptionId::CHECKED}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_compact), HtmlOptionId::COMPACT}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_declare), HtmlOptionId::DECLARE}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_disabled), HtmlOptionId::DISABLED}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_ismap), HtmlOptionId::ISMAP}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_mayscript), HtmlOptionId::MAYSCRIPT}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_multiple), HtmlOptionId::MULTIPLE}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_nohref), HtmlOptionId::NOHREF}, // Netscape 2.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_noresize), HtmlOptionId::NORESIZE}, // Netscape 2.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_noshade), HtmlOptionId::NOSHADE}, // Netscape 2.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_nowrap), HtmlOptionId::NOWRAP}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_sdfixed), HtmlOptionId::SDFIXED}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_selected), HtmlOptionId::SELECTED}, + +// Attributes with a string value + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_accept), HtmlOptionId::ACCEPT}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_accesskey), HtmlOptionId::ACCESSKEY}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_alt), HtmlOptionId::ALT}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_axis), HtmlOptionId::AXIS}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_char), HtmlOptionId::CHAR}, // HTML 3 Table Model Draft + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_charset), HtmlOptionId::CHARSET}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_class), HtmlOptionId::CLASS}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_code), HtmlOptionId::CODE}, // HotJava + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_codetype), HtmlOptionId::CODETYPE}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_content), HtmlOptionId::CONTENT}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_coords), HtmlOptionId::COORDS}, // Netscape 2.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_enctype), HtmlOptionId::ENCTYPE}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_face), HtmlOptionId::FACE}, // IExplorer 2.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_frameborder), HtmlOptionId::FRAMEBORDER}, // IExplorer 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_httpequiv), HtmlOptionId::HTTPEQUIV}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_language), HtmlOptionId::LANGUAGE}, // JavaScript + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_name), HtmlOptionId::NAME}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_prompt), HtmlOptionId::PROMPT}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_shape), HtmlOptionId::SHAPE}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_standby), HtmlOptionId::STANDBY}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_style), HtmlOptionId::STYLE}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_title), HtmlOptionId::TITLE}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_value), HtmlOptionId::VALUE}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_SDval), HtmlOptionId::SDVAL}, // StarDiv NumberValue + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_SDnum), HtmlOptionId::SDNUM}, // StarDiv NumberFormat + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_sdlibrary), HtmlOptionId::SDLIBRARY}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_sdmodule), HtmlOptionId::SDMODULE}, + +// Attributes with a SGML identifier value + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_id), HtmlOptionId::ID}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_target), HtmlOptionId::TARGET}, // Netscape 2.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_to), HtmlOptionId::TO}, + +// Attributes with a URI value + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_action), HtmlOptionId::ACTION}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_archive), HtmlOptionId::ARCHIVE}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_background), HtmlOptionId::BACKGROUND}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_classid), HtmlOptionId::CLASSID}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_codebase), HtmlOptionId::CODEBASE}, // HotJava + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_data), HtmlOptionId::DATA}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_href), HtmlOptionId::HREF}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_script), HtmlOptionId::SCRIPT}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_src), HtmlOptionId::SRC}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_usemap), HtmlOptionId::USEMAP}, // Netscape 2.0 + +// Attributes with a color value (all Netscape versions) + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_alink), HtmlOptionId::ALINK}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_bgcolor), HtmlOptionId::BGCOLOR}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_bordercolor), HtmlOptionId::BORDERCOLOR}, // IExplorer 2.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_bordercolorlight), HtmlOptionId::BORDERCOLORLIGHT}, // IExplorer 2.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_bordercolordark), HtmlOptionId::BORDERCOLORDARK}, // IExplorer 2.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_color), HtmlOptionId::COLOR}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_link), HtmlOptionId::LINK}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_text), HtmlOptionId::TEXT}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_vlink), HtmlOptionId::VLINK}, + +// Attributes with a numerical value + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_border), HtmlOptionId::BORDER}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_cellspacing),HtmlOptionId::CELLSPACING}, // HTML 3 Table Model Draft + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_cellpadding),HtmlOptionId::CELLPADDING}, // HTML 3 Table Model Draft + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_charoff), HtmlOptionId::CHAROFF}, // HTML 3 Table Model Draft + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_colspan), HtmlOptionId::COLSPAN}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_framespacing), HtmlOptionId::FRAMESPACING}, // IExplorer 3.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_gutter), HtmlOptionId::GUTTER}, // Netscape 3.0b5 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_height), HtmlOptionId::HEIGHT}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_hspace), HtmlOptionId::HSPACE}, // Netscape + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_left), HtmlOptionId::LEFT}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_loop), HtmlOptionId::LOOP}, // IExplorer 2.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_marginheight),HtmlOptionId::MARGINHEIGHT}, // Netscape 2.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_marginwidth),HtmlOptionId::MARGINWIDTH}, // Netscape 2.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_maxlength), HtmlOptionId::MAXLENGTH}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_rowspan), HtmlOptionId::ROWSPAN}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_scrollamount), HtmlOptionId::SCROLLAMOUNT}, // IExplorer 2.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_scrolldelay), HtmlOptionId::SCROLLDELAY}, // IExplorer 2.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_span), HtmlOptionId::SPAN}, // HTML 3 Table Model Draft + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_tabindex), HtmlOptionId::TABINDEX}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_vspace), HtmlOptionId::VSPACE}, // Netscape + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_width), HtmlOptionId::WIDTH}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_zindex), HtmlOptionId::ZINDEX}, + +// Attributes with enum values + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_behavior), HtmlOptionId::BEHAVIOR}, // IExplorer 2.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_clear), HtmlOptionId::CLEAR}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_dir), HtmlOptionId::DIR}, // HTML 3 Table Model Draft + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_direction), HtmlOptionId::DIRECTION}, // IExplorer 2.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_format), HtmlOptionId::FORMAT}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_frame), HtmlOptionId::FRAME}, // HTML 3 Table Model Draft + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_lang), HtmlOptionId::LANG}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_method), HtmlOptionId::METHOD}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_rel), HtmlOptionId::REL}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_rev), HtmlOptionId::REV}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_rules), HtmlOptionId::RULES}, // HTML 3 Table Model Draft + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_scrolling), HtmlOptionId::SCROLLING}, // Netscape 2.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_sdreadonly), HtmlOptionId::SDREADONLY}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_subtype), HtmlOptionId::SUBTYPE}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_type), HtmlOptionId::TYPE}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_valign), HtmlOptionId::VALIGN}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_valuetype), HtmlOptionId::VALUETYPE}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_wrap), HtmlOptionId::WRAP}, + +// Attributes with script code value + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_onblur), HtmlOptionId::ONBLUR}, // JavaScript + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_onchange), HtmlOptionId::ONCHANGE}, // JavaScript + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_onclick), HtmlOptionId::ONCLICK}, // JavaScript + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_onfocus), HtmlOptionId::ONFOCUS}, // JavaScript + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_onload), HtmlOptionId::ONLOAD}, // JavaScript + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_onmouseover), HtmlOptionId::ONMOUSEOVER}, // JavaScript + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_onreset), HtmlOptionId::ONRESET}, // JavaScript + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_onselect), HtmlOptionId::ONSELECT}, // JavaScript + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_onsubmit), HtmlOptionId::ONSUBMIT}, // JavaScript + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_onunload), HtmlOptionId::ONUNLOAD}, // JavaScript + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_onabort), HtmlOptionId::ONABORT}, // JavaScript + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_onerror), HtmlOptionId::ONERROR}, // JavaScript + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_onmouseout), HtmlOptionId::ONMOUSEOUT}, // JavaScript + + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_SDonblur), HtmlOptionId::SDONBLUR}, // StarBasic + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_SDonchange), HtmlOptionId::SDONCHANGE}, // StarBasic + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_SDonclick), HtmlOptionId::SDONCLICK}, // StarBasic + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_SDonfocus), HtmlOptionId::SDONFOCUS}, // StarBasic + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_SDonload), HtmlOptionId::SDONLOAD}, // StarBasic + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_SDonmouseover), HtmlOptionId::SDONMOUSEOVER}, // StarBasic + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_SDonreset), HtmlOptionId::SDONRESET}, // StarBasic + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_SDonselect), HtmlOptionId::SDONSELECT}, // StarBasic + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_SDonsubmit), HtmlOptionId::SDONSUBMIT}, // StarBasic + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_SDonunload), HtmlOptionId::SDONUNLOAD}, // StarBasic + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_SDonabort), HtmlOptionId::SDONABORT}, // StarBasic + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_SDonerror), HtmlOptionId::SDONERROR}, // StarBasic + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_SDonmouseout), HtmlOptionId::SDONMOUSEOUT}, // StarBasic + +// Attributes with context sensitive values + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_align), HtmlOptionId::ALIGN}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_cols), HtmlOptionId::COLS}, // Netscape 2.0 vs HTML 2.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_rows), HtmlOptionId::ROWS}, // Netscape 2.0 vs HTML 2.0 + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_size), HtmlOptionId::SIZE}, + {OUStringLiteral(OOO_STRING_SVTOOLS_HTML_O_start), HtmlOptionId::START}, // Netscape 2.0 vs IExplorer 2.0 +}; + +HtmlOptionId GetHTMLOption( const OUString& rName ) +{ + if( !bSortOptionKeyWords ) + { + std::sort( std::begin(aHTMLOptionTab), std::end(aHTMLOptionTab), sortCompare<HtmlOptionId> ); + bSortOptionKeyWords = true; + } + + return search( aHTMLOptionTab, rName, HtmlOptionId::UNKNOWN); +} + + +using HTML_ColorEntry = TokenEntry<sal_uInt32>; + +// Flag: color table has already been sorted +static bool bSortColorKeyWords = false; + +#define HTML_NO_COLOR 0xffffffffUL + +// Color names are not exported (source: +// "http://www.uio.no/~mnbjerke/colors_w.html") +// "http://www.infi.net/wwwimages/colorindex.html" seem to be buggy. +static HTML_ColorEntry const aHTMLColorNameTab[] = { + { OUStringLiteral("aliceblue"), 0x00f0f8ffUL }, + { OUStringLiteral("antiquewhite"), 0x00faebd7UL }, + { OUStringLiteral("aqua"), 0x0000ffffUL }, + { OUStringLiteral("aquamarine"), 0x007fffd4UL }, + { OUStringLiteral("azure"), 0x00f0ffffUL }, + { OUStringLiteral("beige"), 0x00f5f5dcUL }, + { OUStringLiteral("bisque"), 0x00ffe4c4UL }, + { OUStringLiteral("black"), 0x00000000UL }, + { OUStringLiteral("blanchedalmond"), 0x00ffebcdUL }, + { OUStringLiteral("blue"), 0x000000ffUL }, + { OUStringLiteral("blueviolet"), 0x008a2be2UL }, + { OUStringLiteral("brown"), 0x00a52a2aUL }, + { OUStringLiteral("burlywood"), 0x00deb887UL }, + { OUStringLiteral("cadetblue"), 0x005f9ea0UL }, + { OUStringLiteral("chartreuse"), 0x007fff00UL }, + { OUStringLiteral("chocolate"), 0x00d2691eUL }, + { OUStringLiteral("coral"), 0x00ff7f50UL }, + { OUStringLiteral("cornflowerblue"), 0x006495edUL }, + { OUStringLiteral("cornsilk"), 0x00fff8dcUL }, + { OUStringLiteral("crimson"), 0x00dc143cUL }, + { OUStringLiteral("cyan"), 0x0000ffffUL }, + { OUStringLiteral("darkblue"), 0x0000008bUL }, + { OUStringLiteral("darkcyan"), 0x00008b8bUL }, + { OUStringLiteral("darkgoldenrod"), 0x00b8860bUL }, + { OUStringLiteral("darkgray"), 0x00a9a9a9UL }, + { OUStringLiteral("darkgreen"), 0x00006400UL }, + { OUStringLiteral("darkkhaki"), 0x00bdb76bUL }, + { OUStringLiteral("darkmagenta"), 0x008b008bUL }, + { OUStringLiteral("darkolivegreen"), 0x00556b2fUL }, + { OUStringLiteral("darkorange"), 0x00ff8c00UL }, + { OUStringLiteral("darkorchid"), 0x009932ccUL }, + { OUStringLiteral("darkred"), 0x008b0000UL }, + { OUStringLiteral("darksalmon"), 0x00e9967aUL }, + { OUStringLiteral("darkseagreen"), 0x008fbc8fUL }, + { OUStringLiteral("darkslateblue"), 0x00483d8bUL }, + { OUStringLiteral("darkslategray"), 0x002f4f4fUL }, + { OUStringLiteral("darkturquoise"), 0x0000ced1UL }, + { OUStringLiteral("darkviolet"), 0x009400d3UL }, + { OUStringLiteral("deeppink"), 0x00ff1493UL }, + { OUStringLiteral("deepskyblue"), 0x0000bfffUL }, + { OUStringLiteral("dimgray"), 0x00696969UL }, + { OUStringLiteral("dodgerblue"), 0x001e90ffUL }, + { OUStringLiteral("firebrick"), 0x00b22222UL }, + { OUStringLiteral("floralwhite"), 0x00fffaf0UL }, + { OUStringLiteral("forestgreen"), 0x00228b22UL }, + { OUStringLiteral("fuchsia"), 0x00ff00ffUL }, + { OUStringLiteral("gainsboro"), 0x00dcdcdcUL }, + { OUStringLiteral("ghostwhite"), 0x00f8f8ffUL }, + { OUStringLiteral("gold"), 0x00ffd700UL }, + { OUStringLiteral("goldenrod"), 0x00daa520UL }, + { OUStringLiteral("gray"), 0x00808080UL }, + { OUStringLiteral("green"), 0x00008000UL }, + { OUStringLiteral("greenyellow"), 0x00adff2fUL }, + { OUStringLiteral("honeydew"), 0x00f0fff0UL }, + { OUStringLiteral("hotpink"), 0x00ff69b4UL }, + { OUStringLiteral("indianred"), 0x00cd5c5cUL }, + { OUStringLiteral("indigo"), 0x004b0082UL }, + { OUStringLiteral("ivory"), 0x00fffff0UL }, + { OUStringLiteral("khaki"), 0x00f0e68cUL }, + { OUStringLiteral("lavender"), 0x00e6e6faUL }, + { OUStringLiteral("lavenderblush"), 0x00fff0f5UL }, + { OUStringLiteral("lawngreen"), 0x007cfc00UL }, + { OUStringLiteral("lemonchiffon"), 0x00fffacdUL }, + { OUStringLiteral("lightblue"), 0x00add8e6UL }, + { OUStringLiteral("lightcoral"), 0x00f08080UL }, + { OUStringLiteral("lightcyan"), 0x00e0ffffUL }, + { OUStringLiteral("lightgoldenrodyellow"), 0x00fafad2UL }, + { OUStringLiteral("lightgreen"), 0x0090ee90UL }, + { OUStringLiteral("lightgrey"), 0x00d3d3d3UL }, + { OUStringLiteral("lightpink"), 0x00ffb6c1UL }, + { OUStringLiteral("lightsalmon"), 0x00ffa07aUL }, + { OUStringLiteral("lightseagreen"), 0x0020b2aaUL }, + { OUStringLiteral("lightskyblue"), 0x0087cefaUL }, + { OUStringLiteral("lightslategray"), 0x00778899UL }, + { OUStringLiteral("lightsteelblue"), 0x00b0c4deUL }, + { OUStringLiteral("lightyellow"), 0x00ffffe0UL }, + { OUStringLiteral("lime"), 0x0000ff00UL }, + { OUStringLiteral("limegreen"), 0x0032cd32UL }, + { OUStringLiteral("linen"), 0x00faf0e6UL }, + { OUStringLiteral("magenta"), 0x00ff00ffUL }, + { OUStringLiteral("maroon"), 0x00800000UL }, + { OUStringLiteral("mediumaquamarine"), 0x0066cdaaUL }, + { OUStringLiteral("mediumblue"), 0x000000cdUL }, + { OUStringLiteral("mediumorchid"), 0x00ba55d3UL }, + { OUStringLiteral("mediumpurple"), 0x009370dbUL }, + { OUStringLiteral("mediumseagreen"), 0x003cb371UL }, + { OUStringLiteral("mediumslateblue"), 0x007b68eeUL }, + { OUStringLiteral("mediumspringgreen"), 0x0000fa9aUL }, + { OUStringLiteral("mediumturquoise"), 0x0048d1ccUL }, + { OUStringLiteral("mediumvioletred"), 0x00c71585UL }, + { OUStringLiteral("midnightblue"), 0x00191970UL }, + { OUStringLiteral("mintcream"), 0x00f5fffaUL }, + { OUStringLiteral("mistyrose"), 0x00ffe4e1UL }, + { OUStringLiteral("moccasin"), 0x00ffe4b5UL }, + { OUStringLiteral("navajowhite"), 0x00ffdeadUL }, + { OUStringLiteral("navy"), 0x00000080UL }, + { OUStringLiteral("oldlace"), 0x00fdf5e6UL }, + { OUStringLiteral("olive"), 0x00808000UL }, + { OUStringLiteral("olivedrab"), 0x006b8e23UL }, + { OUStringLiteral("orange"), 0x00ffa500UL }, + { OUStringLiteral("orangered"), 0x00ff4500UL }, + { OUStringLiteral("orchid"), 0x00da70d6UL }, + { OUStringLiteral("palegoldenrod"), 0x00eee8aaUL }, + { OUStringLiteral("palegreen"), 0x0098fb98UL }, + { OUStringLiteral("paleturquoise"), 0x00afeeeeUL }, + { OUStringLiteral("palevioletred"), 0x00db7093UL }, + { OUStringLiteral("papayawhip"), 0x00ffefd5UL }, + { OUStringLiteral("peachpuff"), 0x00ffdab9UL }, + { OUStringLiteral("peru"), 0x00cd853fUL }, + { OUStringLiteral("pink"), 0x00ffc0cbUL }, + { OUStringLiteral("plum"), 0x00dda0ddUL }, + { OUStringLiteral("powderblue"), 0x00b0e0e6UL }, + { OUStringLiteral("purple"), 0x00800080UL }, + { OUStringLiteral("red"), 0x00ff0000UL }, + { OUStringLiteral("rosybrown"), 0x00bc8f8fUL }, + { OUStringLiteral("royalblue"), 0x004169e1UL }, + { OUStringLiteral("saddlebrown"), 0x008b4513UL }, + { OUStringLiteral("salmon"), 0x00fa8072UL }, + { OUStringLiteral("sandybrown"), 0x00f4a460UL }, + { OUStringLiteral("seagreen"), 0x002e8b57UL }, + { OUStringLiteral("seashell"), 0x00fff5eeUL }, + { OUStringLiteral("sienna"), 0x00a0522dUL }, + { OUStringLiteral("silver"), 0x00c0c0c0UL }, + { OUStringLiteral("skyblue"), 0x0087ceebUL }, + { OUStringLiteral("slateblue"), 0x006a5acdUL }, + { OUStringLiteral("slategray"), 0x00708090UL }, + { OUStringLiteral("snow"), 0x00fffafaUL }, + { OUStringLiteral("springgreen"), 0x0000ff7fUL }, + { OUStringLiteral("steelblue"), 0x004682b4UL }, + { OUStringLiteral("tan"), 0x00d2b48cUL }, + { OUStringLiteral("teal"), 0x00008080UL }, + { OUStringLiteral("thistle"), 0x00d8bfd8UL }, + { OUStringLiteral("tomato"), 0x00ff6347UL }, + { OUStringLiteral("turquoise"), 0x0040e0d0UL }, + { OUStringLiteral("violet"), 0x00ee82eeUL }, + { OUStringLiteral("wheat"), 0x00f5deb3UL }, + { OUStringLiteral("white"), 0x00ffffffUL }, + { OUStringLiteral("whitesmoke"), 0x00f5f5f5UL }, + { OUStringLiteral("yellow"), 0x00ffff00UL }, + { OUStringLiteral("yellowgreen"), 0x009acd32UL } +}; + +sal_uInt32 GetHTMLColor( const OUString& rName ) +{ + if( !bSortColorKeyWords ) + { + assert( std::is_sorted( std::begin(aHTMLColorNameTab), std::end(aHTMLColorNameTab), + sortCompare<sal_uInt32> ) ); + bSortColorKeyWords = true; + } + + OUString aLowerCase(rName.toAsciiLowerCase()); + + return search<sal_uInt32>( aHTMLColorNameTab, aLowerCase, HTML_NO_COLOR); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/svhtml/htmlout.cxx b/svtools/source/svhtml/htmlout.cxx new file mode 100644 index 000000000..ce43e2dd9 --- /dev/null +++ b/svtools/source/svhtml/htmlout.cxx @@ -0,0 +1,1045 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <svl/zformat.hxx> +#include <svl/macitem.hxx> +#include <vcl/svapp.hxx> +#include <vcl/settings.hxx> +#include <svl/zforlist.hxx> + +#include <svtools/HtmlWriter.hxx> +#include <svtools/htmlout.hxx> +#include <svtools/htmlkywd.hxx> +#include <vcl/imap.hxx> +#include <vcl/imaprect.hxx> +#include <vcl/imapcirc.hxx> +#include <vcl/imappoly.hxx> +#include <svl/urihelper.hxx> +#include <rtl/character.hxx> +#include <tools/debug.hxx> + +#include <sstream> + +#define TXTCONV_BUFFER_SIZE 20 + +HTMLOutContext::HTMLOutContext( rtl_TextEncoding eDestEnc ) +{ + m_eDestEnc = RTL_TEXTENCODING_DONTKNOW == eDestEnc + ? osl_getThreadTextEncoding() + : eDestEnc; + + m_hConv = rtl_createUnicodeToTextConverter( eDestEnc ); + DBG_ASSERT( m_hConv, + "HTMLOutContext::HTMLOutContext: no converter for source encoding" ); + m_hContext = m_hConv ? rtl_createUnicodeToTextContext( m_hConv ) + : reinterpret_cast<rtl_TextToUnicodeContext>(1); +} + +HTMLOutContext::~HTMLOutContext() +{ + rtl_destroyUnicodeToTextContext( m_hConv, m_hContext ); + rtl_destroyUnicodeToTextConverter( m_hConv ); +} + +static const char *lcl_svhtml_GetEntityForChar( sal_uInt32 c, + rtl_TextEncoding eDestEnc ) +{ + const char* pStr = nullptr; + + // Note: We currently handle special cases for ISO-8859-2 here simply because + // the code was already submitted. But we should also handle other code pages + // as well as the code becomes available. + + if( eDestEnc == RTL_TEXTENCODING_ISO_8859_2 || eDestEnc == RTL_TEXTENCODING_MS_1250 ) + { + // Don't handle the following characters for Easter European (ISO-8859-2). + switch ( c ) + { + case 164: // curren + case 184: // ccedil + case 193: // Aacute + case 194: // Acirc + case 196: // Auml + case 199: // Ccedil + case 201: // Eacute + case 203: // Euml + case 205: // Iacute + case 206: // Icirc + case 211: // Oacute + case 212: // Ocirc + case 214: // Ouml + case 215: // times + case 218: // Uacute + case 220: // Uuml + case 221: // Yacute + case 225: // aacute + case 226: // acirc + case 228: // auml + case 233: // eacute + case 235: // euml + case 237: // iacute + case 238: // icirc + case 243: // oacute + case 244: // ocirc + case 246: // ouml + case 247: // divide + case 250: // uacute + case 252: // uuml + case 253: // yacute + case 352: // Scaron + case 353: // scaron + return pStr; + } + } + + // TODO: handle more special cases for other code pages. + + switch( c ) + { +// case '\x0a': return HTMLOutFuncs::Out_Tag( rStream, OOO_STRING_SVTOOLS_HTML_linebreak ); + + case '<': pStr = OOO_STRING_SVTOOLS_HTML_C_lt; break; + case '>': pStr = OOO_STRING_SVTOOLS_HTML_C_gt; break; + case '&': pStr = OOO_STRING_SVTOOLS_HTML_C_amp; break; + case '"': pStr = OOO_STRING_SVTOOLS_HTML_C_quot; break; + + case 161: pStr = OOO_STRING_SVTOOLS_HTML_S_iexcl; break; + case 162: pStr = OOO_STRING_SVTOOLS_HTML_S_cent; break; + case 163: pStr = OOO_STRING_SVTOOLS_HTML_S_pound; break; + case 164: pStr = OOO_STRING_SVTOOLS_HTML_S_curren; break; + case 165: pStr = OOO_STRING_SVTOOLS_HTML_S_yen; break; + case 166: pStr = OOO_STRING_SVTOOLS_HTML_S_brvbar; break; + case 167: pStr = OOO_STRING_SVTOOLS_HTML_S_sect; break; + case 168: pStr = OOO_STRING_SVTOOLS_HTML_S_uml; break; + case 169: pStr = OOO_STRING_SVTOOLS_HTML_S_copy; break; + case 170: pStr = OOO_STRING_SVTOOLS_HTML_S_ordf; break; + case 171: pStr = OOO_STRING_SVTOOLS_HTML_S_laquo; break; + case 172: pStr = OOO_STRING_SVTOOLS_HTML_S_not; break; + case 174: pStr = OOO_STRING_SVTOOLS_HTML_S_reg; break; + case 175: pStr = OOO_STRING_SVTOOLS_HTML_S_macr; break; + case 176: pStr = OOO_STRING_SVTOOLS_HTML_S_deg; break; + case 177: pStr = OOO_STRING_SVTOOLS_HTML_S_plusmn; break; + case 178: pStr = OOO_STRING_SVTOOLS_HTML_S_sup2; break; + case 179: pStr = OOO_STRING_SVTOOLS_HTML_S_sup3; break; + case 180: pStr = OOO_STRING_SVTOOLS_HTML_S_acute; break; + case 181: pStr = OOO_STRING_SVTOOLS_HTML_S_micro; break; + case 182: pStr = OOO_STRING_SVTOOLS_HTML_S_para; break; + case 183: pStr = OOO_STRING_SVTOOLS_HTML_S_middot; break; + case 184: pStr = OOO_STRING_SVTOOLS_HTML_S_cedil; break; + case 185: pStr = OOO_STRING_SVTOOLS_HTML_S_sup1; break; + case 186: pStr = OOO_STRING_SVTOOLS_HTML_S_ordm; break; + case 187: pStr = OOO_STRING_SVTOOLS_HTML_S_raquo; break; + case 188: pStr = OOO_STRING_SVTOOLS_HTML_S_frac14; break; + case 189: pStr = OOO_STRING_SVTOOLS_HTML_S_frac12; break; + case 190: pStr = OOO_STRING_SVTOOLS_HTML_S_frac34; break; + case 191: pStr = OOO_STRING_SVTOOLS_HTML_S_iquest; break; + + case 192: pStr = OOO_STRING_SVTOOLS_HTML_C_Agrave; break; + case 193: pStr = OOO_STRING_SVTOOLS_HTML_C_Aacute; break; + case 194: pStr = OOO_STRING_SVTOOLS_HTML_C_Acirc; break; + case 195: pStr = OOO_STRING_SVTOOLS_HTML_C_Atilde; break; + case 196: pStr = OOO_STRING_SVTOOLS_HTML_C_Auml; break; + case 197: pStr = OOO_STRING_SVTOOLS_HTML_C_Aring; break; + case 198: pStr = OOO_STRING_SVTOOLS_HTML_C_AElig; break; + case 199: pStr = OOO_STRING_SVTOOLS_HTML_C_Ccedil; break; + case 200: pStr = OOO_STRING_SVTOOLS_HTML_C_Egrave; break; + case 201: pStr = OOO_STRING_SVTOOLS_HTML_C_Eacute; break; + case 202: pStr = OOO_STRING_SVTOOLS_HTML_C_Ecirc; break; + case 203: pStr = OOO_STRING_SVTOOLS_HTML_C_Euml; break; + case 204: pStr = OOO_STRING_SVTOOLS_HTML_C_Igrave; break; + case 205: pStr = OOO_STRING_SVTOOLS_HTML_C_Iacute; break; + case 206: pStr = OOO_STRING_SVTOOLS_HTML_C_Icirc; break; + case 207: pStr = OOO_STRING_SVTOOLS_HTML_C_Iuml; break; + case 208: pStr = OOO_STRING_SVTOOLS_HTML_C_ETH; break; + case 209: pStr = OOO_STRING_SVTOOLS_HTML_C_Ntilde; break; + case 210: pStr = OOO_STRING_SVTOOLS_HTML_C_Ograve; break; + case 211: pStr = OOO_STRING_SVTOOLS_HTML_C_Oacute; break; + case 212: pStr = OOO_STRING_SVTOOLS_HTML_C_Ocirc; break; + case 213: pStr = OOO_STRING_SVTOOLS_HTML_C_Otilde; break; + case 214: pStr = OOO_STRING_SVTOOLS_HTML_C_Ouml; break; + case 215: pStr = OOO_STRING_SVTOOLS_HTML_S_times; break; + case 216: pStr = OOO_STRING_SVTOOLS_HTML_C_Oslash; break; + case 217: pStr = OOO_STRING_SVTOOLS_HTML_C_Ugrave; break; + case 218: pStr = OOO_STRING_SVTOOLS_HTML_C_Uacute; break; + case 219: pStr = OOO_STRING_SVTOOLS_HTML_C_Ucirc; break; + case 220: pStr = OOO_STRING_SVTOOLS_HTML_C_Uuml; break; + case 221: pStr = OOO_STRING_SVTOOLS_HTML_C_Yacute; break; + + case 222: pStr = OOO_STRING_SVTOOLS_HTML_C_THORN; break; + case 223: pStr = OOO_STRING_SVTOOLS_HTML_C_szlig; break; + + case 224: pStr = OOO_STRING_SVTOOLS_HTML_S_agrave; break; + case 225: pStr = OOO_STRING_SVTOOLS_HTML_S_aacute; break; + case 226: pStr = OOO_STRING_SVTOOLS_HTML_S_acirc; break; + case 227: pStr = OOO_STRING_SVTOOLS_HTML_S_atilde; break; + case 228: pStr = OOO_STRING_SVTOOLS_HTML_S_auml; break; + case 229: pStr = OOO_STRING_SVTOOLS_HTML_S_aring; break; + case 230: pStr = OOO_STRING_SVTOOLS_HTML_S_aelig; break; + case 231: pStr = OOO_STRING_SVTOOLS_HTML_S_ccedil; break; + case 232: pStr = OOO_STRING_SVTOOLS_HTML_S_egrave; break; + case 233: pStr = OOO_STRING_SVTOOLS_HTML_S_eacute; break; + case 234: pStr = OOO_STRING_SVTOOLS_HTML_S_ecirc; break; + case 235: pStr = OOO_STRING_SVTOOLS_HTML_S_euml; break; + case 236: pStr = OOO_STRING_SVTOOLS_HTML_S_igrave; break; + case 237: pStr = OOO_STRING_SVTOOLS_HTML_S_iacute; break; + case 238: pStr = OOO_STRING_SVTOOLS_HTML_S_icirc; break; + case 239: pStr = OOO_STRING_SVTOOLS_HTML_S_iuml; break; + case 240: pStr = OOO_STRING_SVTOOLS_HTML_S_eth; break; + case 241: pStr = OOO_STRING_SVTOOLS_HTML_S_ntilde; break; + case 242: pStr = OOO_STRING_SVTOOLS_HTML_S_ograve; break; + case 243: pStr = OOO_STRING_SVTOOLS_HTML_S_oacute; break; + case 244: pStr = OOO_STRING_SVTOOLS_HTML_S_ocirc; break; + case 245: pStr = OOO_STRING_SVTOOLS_HTML_S_otilde; break; + case 246: pStr = OOO_STRING_SVTOOLS_HTML_S_ouml; break; + case 247: pStr = OOO_STRING_SVTOOLS_HTML_S_divide; break; + case 248: pStr = OOO_STRING_SVTOOLS_HTML_S_oslash; break; + case 249: pStr = OOO_STRING_SVTOOLS_HTML_S_ugrave; break; + case 250: pStr = OOO_STRING_SVTOOLS_HTML_S_uacute; break; + case 251: pStr = OOO_STRING_SVTOOLS_HTML_S_ucirc; break; + case 252: pStr = OOO_STRING_SVTOOLS_HTML_S_uuml; break; + case 253: pStr = OOO_STRING_SVTOOLS_HTML_S_yacute; break; + case 254: pStr = OOO_STRING_SVTOOLS_HTML_S_thorn; break; + case 255: pStr = OOO_STRING_SVTOOLS_HTML_S_yuml; break; + + case 338: pStr = OOO_STRING_SVTOOLS_HTML_S_OElig; break; + case 339: pStr = OOO_STRING_SVTOOLS_HTML_S_oelig; break; + case 352: pStr = OOO_STRING_SVTOOLS_HTML_S_Scaron; break; + case 353: pStr = OOO_STRING_SVTOOLS_HTML_S_scaron; break; + case 376: pStr = OOO_STRING_SVTOOLS_HTML_S_Yuml; break; + case 402: pStr = OOO_STRING_SVTOOLS_HTML_S_fnof; break; + case 710: pStr = OOO_STRING_SVTOOLS_HTML_S_circ; break; + case 732: pStr = OOO_STRING_SVTOOLS_HTML_S_tilde; break; + + // Greek chars are handled later, + // since they should *not* be transformed to entities + // when generating Greek text (== using Greek encoding) + + case 8194: pStr = OOO_STRING_SVTOOLS_HTML_S_ensp; break; + case 8195: pStr = OOO_STRING_SVTOOLS_HTML_S_emsp; break; + case 8201: pStr = OOO_STRING_SVTOOLS_HTML_S_thinsp; break; + case 8204: pStr = OOO_STRING_SVTOOLS_HTML_S_zwnj; break; + case 8205: pStr = OOO_STRING_SVTOOLS_HTML_S_zwj; break; + case 8206: pStr = OOO_STRING_SVTOOLS_HTML_S_lrm; break; + case 8207: pStr = OOO_STRING_SVTOOLS_HTML_S_rlm; break; + case 8211: pStr = OOO_STRING_SVTOOLS_HTML_S_ndash; break; + case 8212: pStr = OOO_STRING_SVTOOLS_HTML_S_mdash; break; + case 8216: pStr = OOO_STRING_SVTOOLS_HTML_S_lsquo; break; + case 8217: pStr = OOO_STRING_SVTOOLS_HTML_S_rsquo; break; + case 8218: pStr = OOO_STRING_SVTOOLS_HTML_S_sbquo; break; + case 8220: pStr = OOO_STRING_SVTOOLS_HTML_S_ldquo; break; + case 8221: pStr = OOO_STRING_SVTOOLS_HTML_S_rdquo; break; + case 8222: pStr = OOO_STRING_SVTOOLS_HTML_S_bdquo; break; + case 8224: pStr = OOO_STRING_SVTOOLS_HTML_S_dagger; break; + case 8225: pStr = OOO_STRING_SVTOOLS_HTML_S_Dagger; break; + case 8226: pStr = OOO_STRING_SVTOOLS_HTML_S_bull; break; + case 8230: pStr = OOO_STRING_SVTOOLS_HTML_S_hellip; break; + case 8240: pStr = OOO_STRING_SVTOOLS_HTML_S_permil; break; + case 8242: pStr = OOO_STRING_SVTOOLS_HTML_S_prime; break; + case 8243: pStr = OOO_STRING_SVTOOLS_HTML_S_Prime; break; + case 8249: pStr = OOO_STRING_SVTOOLS_HTML_S_lsaquo; break; + case 8250: pStr = OOO_STRING_SVTOOLS_HTML_S_rsaquo; break; + case 8254: pStr = OOO_STRING_SVTOOLS_HTML_S_oline; break; + case 8260: pStr = OOO_STRING_SVTOOLS_HTML_S_frasl; break; + case 8364: pStr = OOO_STRING_SVTOOLS_HTML_S_euro; break; + case 8465: pStr = OOO_STRING_SVTOOLS_HTML_S_image; break; + case 8472: pStr = OOO_STRING_SVTOOLS_HTML_S_weierp; break; + case 8476: pStr = OOO_STRING_SVTOOLS_HTML_S_real; break; + case 8482: pStr = OOO_STRING_SVTOOLS_HTML_S_trade; break; + case 8501: pStr = OOO_STRING_SVTOOLS_HTML_S_alefsym; break; + case 8592: pStr = OOO_STRING_SVTOOLS_HTML_S_larr; break; + case 8593: pStr = OOO_STRING_SVTOOLS_HTML_S_uarr; break; + case 8594: pStr = OOO_STRING_SVTOOLS_HTML_S_rarr; break; + case 8595: pStr = OOO_STRING_SVTOOLS_HTML_S_darr; break; + case 8596: pStr = OOO_STRING_SVTOOLS_HTML_S_harr; break; + case 8629: pStr = OOO_STRING_SVTOOLS_HTML_S_crarr; break; + case 8656: pStr = OOO_STRING_SVTOOLS_HTML_S_lArr; break; + case 8657: pStr = OOO_STRING_SVTOOLS_HTML_S_uArr; break; + case 8658: pStr = OOO_STRING_SVTOOLS_HTML_S_rArr; break; + case 8659: pStr = OOO_STRING_SVTOOLS_HTML_S_dArr; break; + case 8660: pStr = OOO_STRING_SVTOOLS_HTML_S_hArr; break; + case 8704: pStr = OOO_STRING_SVTOOLS_HTML_S_forall; break; + case 8706: pStr = OOO_STRING_SVTOOLS_HTML_S_part; break; + case 8707: pStr = OOO_STRING_SVTOOLS_HTML_S_exist; break; + case 8709: pStr = OOO_STRING_SVTOOLS_HTML_S_empty; break; + case 8711: pStr = OOO_STRING_SVTOOLS_HTML_S_nabla; break; + case 8712: pStr = OOO_STRING_SVTOOLS_HTML_S_isin; break; + case 8713: pStr = OOO_STRING_SVTOOLS_HTML_S_notin; break; + case 8715: pStr = OOO_STRING_SVTOOLS_HTML_S_ni; break; + case 8719: pStr = OOO_STRING_SVTOOLS_HTML_S_prod; break; + case 8721: pStr = OOO_STRING_SVTOOLS_HTML_S_sum; break; + case 8722: pStr = OOO_STRING_SVTOOLS_HTML_S_minus; break; + case 8727: pStr = OOO_STRING_SVTOOLS_HTML_S_lowast; break; + case 8730: pStr = OOO_STRING_SVTOOLS_HTML_S_radic; break; + case 8733: pStr = OOO_STRING_SVTOOLS_HTML_S_prop; break; + case 8734: pStr = OOO_STRING_SVTOOLS_HTML_S_infin; break; + case 8736: pStr = OOO_STRING_SVTOOLS_HTML_S_ang; break; + case 8743: pStr = OOO_STRING_SVTOOLS_HTML_S_and; break; + case 8744: pStr = OOO_STRING_SVTOOLS_HTML_S_or; break; + case 8745: pStr = OOO_STRING_SVTOOLS_HTML_S_cap; break; + case 8746: pStr = OOO_STRING_SVTOOLS_HTML_S_cup; break; + case 8747: pStr = OOO_STRING_SVTOOLS_HTML_S_int; break; + case 8756: pStr = OOO_STRING_SVTOOLS_HTML_S_there4; break; + case 8764: pStr = OOO_STRING_SVTOOLS_HTML_S_sim; break; + case 8773: pStr = OOO_STRING_SVTOOLS_HTML_S_cong; break; + case 8776: pStr = OOO_STRING_SVTOOLS_HTML_S_asymp; break; + case 8800: pStr = OOO_STRING_SVTOOLS_HTML_S_ne; break; + case 8801: pStr = OOO_STRING_SVTOOLS_HTML_S_equiv; break; + case 8804: pStr = OOO_STRING_SVTOOLS_HTML_S_le; break; + case 8805: pStr = OOO_STRING_SVTOOLS_HTML_S_ge; break; + case 8834: pStr = OOO_STRING_SVTOOLS_HTML_S_sub; break; + case 8835: pStr = OOO_STRING_SVTOOLS_HTML_S_sup; break; + case 8836: pStr = OOO_STRING_SVTOOLS_HTML_S_nsub; break; + case 8838: pStr = OOO_STRING_SVTOOLS_HTML_S_sube; break; + case 8839: pStr = OOO_STRING_SVTOOLS_HTML_S_supe; break; + case 8853: pStr = OOO_STRING_SVTOOLS_HTML_S_oplus; break; + case 8855: pStr = OOO_STRING_SVTOOLS_HTML_S_otimes; break; + case 8869: pStr = OOO_STRING_SVTOOLS_HTML_S_perp; break; + case 8901: pStr = OOO_STRING_SVTOOLS_HTML_S_sdot; break; + case 8968: pStr = OOO_STRING_SVTOOLS_HTML_S_lceil; break; + case 8969: pStr = OOO_STRING_SVTOOLS_HTML_S_rceil; break; + case 8970: pStr = OOO_STRING_SVTOOLS_HTML_S_lfloor; break; + case 8971: pStr = OOO_STRING_SVTOOLS_HTML_S_rfloor; break; + case 9001: pStr = OOO_STRING_SVTOOLS_HTML_S_lang; break; + case 9002: pStr = OOO_STRING_SVTOOLS_HTML_S_rang; break; + case 9674: pStr = OOO_STRING_SVTOOLS_HTML_S_loz; break; + case 9824: pStr = OOO_STRING_SVTOOLS_HTML_S_spades; break; + case 9827: pStr = OOO_STRING_SVTOOLS_HTML_S_clubs; break; + case 9829: pStr = OOO_STRING_SVTOOLS_HTML_S_hearts; break; + case 9830: pStr = OOO_STRING_SVTOOLS_HTML_S_diams; break; + } + + // Greek chars: if we do not produce a Greek encoding, + // transform them into entities + if( !pStr && + ( eDestEnc != RTL_TEXTENCODING_ISO_8859_7 ) && + ( eDestEnc != RTL_TEXTENCODING_MS_1253 ) ) + { + switch( c ) + { + case 913: pStr = OOO_STRING_SVTOOLS_HTML_S_Alpha; break; + case 914: pStr = OOO_STRING_SVTOOLS_HTML_S_Beta; break; + case 915: pStr = OOO_STRING_SVTOOLS_HTML_S_Gamma; break; + case 916: pStr = OOO_STRING_SVTOOLS_HTML_S_Delta; break; + case 917: pStr = OOO_STRING_SVTOOLS_HTML_S_Epsilon; break; + case 918: pStr = OOO_STRING_SVTOOLS_HTML_S_Zeta; break; + case 919: pStr = OOO_STRING_SVTOOLS_HTML_S_Eta; break; + case 920: pStr = OOO_STRING_SVTOOLS_HTML_S_Theta; break; + case 921: pStr = OOO_STRING_SVTOOLS_HTML_S_Iota; break; + case 922: pStr = OOO_STRING_SVTOOLS_HTML_S_Kappa; break; + case 923: pStr = OOO_STRING_SVTOOLS_HTML_S_Lambda; break; + case 924: pStr = OOO_STRING_SVTOOLS_HTML_S_Mu; break; + case 925: pStr = OOO_STRING_SVTOOLS_HTML_S_Nu; break; + case 926: pStr = OOO_STRING_SVTOOLS_HTML_S_Xi; break; + case 927: pStr = OOO_STRING_SVTOOLS_HTML_S_Omicron; break; + case 928: pStr = OOO_STRING_SVTOOLS_HTML_S_Pi; break; + case 929: pStr = OOO_STRING_SVTOOLS_HTML_S_Rho; break; + case 931: pStr = OOO_STRING_SVTOOLS_HTML_S_Sigma; break; + case 932: pStr = OOO_STRING_SVTOOLS_HTML_S_Tau; break; + case 933: pStr = OOO_STRING_SVTOOLS_HTML_S_Upsilon; break; + case 934: pStr = OOO_STRING_SVTOOLS_HTML_S_Phi; break; + case 935: pStr = OOO_STRING_SVTOOLS_HTML_S_Chi; break; + case 936: pStr = OOO_STRING_SVTOOLS_HTML_S_Psi; break; + case 937: pStr = OOO_STRING_SVTOOLS_HTML_S_Omega; break; + case 945: pStr = OOO_STRING_SVTOOLS_HTML_S_alpha; break; + case 946: pStr = OOO_STRING_SVTOOLS_HTML_S_beta; break; + case 947: pStr = OOO_STRING_SVTOOLS_HTML_S_gamma; break; + case 948: pStr = OOO_STRING_SVTOOLS_HTML_S_delta; break; + case 949: pStr = OOO_STRING_SVTOOLS_HTML_S_epsilon; break; + case 950: pStr = OOO_STRING_SVTOOLS_HTML_S_zeta; break; + case 951: pStr = OOO_STRING_SVTOOLS_HTML_S_eta; break; + case 952: pStr = OOO_STRING_SVTOOLS_HTML_S_theta; break; + case 953: pStr = OOO_STRING_SVTOOLS_HTML_S_iota; break; + case 954: pStr = OOO_STRING_SVTOOLS_HTML_S_kappa; break; + case 955: pStr = OOO_STRING_SVTOOLS_HTML_S_lambda; break; + case 956: pStr = OOO_STRING_SVTOOLS_HTML_S_mu; break; + case 957: pStr = OOO_STRING_SVTOOLS_HTML_S_nu; break; + case 958: pStr = OOO_STRING_SVTOOLS_HTML_S_xi; break; + case 959: pStr = OOO_STRING_SVTOOLS_HTML_S_omicron; break; + case 960: pStr = OOO_STRING_SVTOOLS_HTML_S_pi; break; + case 961: pStr = OOO_STRING_SVTOOLS_HTML_S_rho; break; + case 962: pStr = OOO_STRING_SVTOOLS_HTML_S_sigmaf; break; + case 963: pStr = OOO_STRING_SVTOOLS_HTML_S_sigma; break; + case 964: pStr = OOO_STRING_SVTOOLS_HTML_S_tau; break; + case 965: pStr = OOO_STRING_SVTOOLS_HTML_S_upsilon; break; + case 966: pStr = OOO_STRING_SVTOOLS_HTML_S_phi; break; + case 967: pStr = OOO_STRING_SVTOOLS_HTML_S_chi; break; + case 968: pStr = OOO_STRING_SVTOOLS_HTML_S_psi; break; + case 969: pStr = OOO_STRING_SVTOOLS_HTML_S_omega; break; + case 977: pStr = OOO_STRING_SVTOOLS_HTML_S_thetasym;break; + case 978: pStr = OOO_STRING_SVTOOLS_HTML_S_upsih; break; + case 982: pStr = OOO_STRING_SVTOOLS_HTML_S_piv; break; + } + } + + return pStr; +} + +static sal_Size lcl_FlushContext(HTMLOutContext& rContext, char* pBuffer, sal_uInt32 nFlags) +{ + sal_uInt32 nInfo = 0; + sal_Size nSrcChars; + sal_Size nLen = rtl_convertUnicodeToText(rContext.m_hConv, rContext.m_hContext, nullptr, 0, + pBuffer, TXTCONV_BUFFER_SIZE, nFlags|RTL_UNICODETOTEXT_FLAGS_FLUSH, + &nInfo, &nSrcChars); + DBG_ASSERT((nInfo & (RTL_UNICODETOTEXT_INFO_ERROR|RTL_UNICODETOTEXT_INFO_DESTBUFFERTOSMALL)) == 0, "HTMLOut: error while flushing"); + return nLen; +} + +static OString lcl_ConvertCharToHTML( sal_uInt32 c, + HTMLOutContext& rContext, + OUString *pNonConvertableChars ) +{ + assert(rtl::isUnicodeCodePoint(c)); + + OStringBuffer aDest; + DBG_ASSERT( RTL_TEXTENCODING_DONTKNOW != rContext.m_eDestEnc, + "wrong destination encoding" ); + const char *pStr = nullptr; + switch( c ) + { + case 0xA0: // is a hard blank + pStr = OOO_STRING_SVTOOLS_HTML_S_nbsp; + break; + case 0x2011: // is a hard hyphen + pStr = "#8209"; + break; + case 0xAD: // is a soft hyphen + pStr = OOO_STRING_SVTOOLS_HTML_S_shy; + break; + default: + // There may be an entity for the character. + // The new HTML4 entities above 255 are not used for UTF-8, + // because Netscape 4 does support UTF-8 but does not support + // these entities. + if( c < 128 || RTL_TEXTENCODING_UTF8 != rContext.m_eDestEnc ) + pStr = lcl_svhtml_GetEntityForChar( c, rContext.m_eDestEnc ); + break; + } + + char cBuffer[TXTCONV_BUFFER_SIZE]; + const sal_uInt32 nFlags = RTL_UNICODETOTEXT_FLAGS_NONSPACING_IGNORE| + RTL_UNICODETOTEXT_FLAGS_CONTROL_IGNORE| + RTL_UNICODETOTEXT_FLAGS_UNDEFINED_ERROR| + RTL_UNICODETOTEXT_FLAGS_INVALID_ERROR; + if( pStr ) + { + sal_Size nLen = lcl_FlushContext(rContext, cBuffer, nFlags); + char *pBuffer = cBuffer; + while( nLen-- ) + aDest.append(*pBuffer++); + aDest.append('&').append(pStr).append(';'); + } + else + { + sal_uInt32 nInfo = 0; + sal_Size nSrcChars; + + sal_Unicode utf16[2]; + auto n = rtl::splitSurrogates(c, utf16); + sal_Size nLen = rtl_convertUnicodeToText(rContext.m_hConv, + rContext.m_hContext, utf16, n, + cBuffer, TXTCONV_BUFFER_SIZE, + nFlags, &nInfo, &nSrcChars); + if( nLen > 0 && (nInfo & (RTL_UNICODETOTEXT_INFO_ERROR|RTL_UNICODETOTEXT_INFO_DESTBUFFERTOSMALL)) == 0 ) + { + char *pBuffer = cBuffer; + while( nLen-- ) + aDest.append(*pBuffer++); + } + else + { + // If the character could not be converted to the destination + // character set, the UNICODE character is exported as character + // entity. + // coverity[callee_ptr_arith] - its ok + nLen = lcl_FlushContext(rContext, cBuffer, nFlags); + char *pBuffer = cBuffer; + while( nLen-- ) + aDest.append(*pBuffer++); + + aDest.append('&').append('#').append(static_cast<sal_Int32>(c)) + // Unicode code points guaranteed to fit into sal_Int32 + .append(';'); + if( pNonConvertableChars ) + { + OUString cs(&c, 1); + if( -1 == pNonConvertableChars->indexOf( cs ) ) + (*pNonConvertableChars) += cs; + } + } + } + return aDest.makeStringAndClear(); +} + +static OString lcl_FlushToAscii( HTMLOutContext& rContext ) +{ + OStringBuffer aDest; + + char cBuffer[TXTCONV_BUFFER_SIZE]; + const sal_uInt32 nFlags = RTL_UNICODETOTEXT_FLAGS_NONSPACING_IGNORE| + RTL_UNICODETOTEXT_FLAGS_CONTROL_IGNORE| + RTL_UNICODETOTEXT_FLAGS_UNDEFINED_ERROR| + RTL_UNICODETOTEXT_FLAGS_INVALID_ERROR; + sal_Size nLen = lcl_FlushContext(rContext, cBuffer, nFlags); + char *pBuffer = cBuffer; + while( nLen-- ) + aDest.append(*pBuffer++); + return aDest.makeStringAndClear(); +} + +OString HTMLOutFuncs::ConvertStringToHTML( const OUString& rSrc, + rtl_TextEncoding eDestEnc, OUString *pNonConvertableChars ) +{ + HTMLOutContext aContext( eDestEnc ); + OStringBuffer aDest; + for( sal_Int32 i=0, nLen = rSrc.getLength(); i < nLen; ) + aDest.append(lcl_ConvertCharToHTML( + rSrc.iterateCodePoints(&i), aContext, pNonConvertableChars)); + aDest.append(lcl_FlushToAscii(aContext)); + return aDest.makeStringAndClear(); +} + +SvStream& HTMLOutFuncs::Out_AsciiTag( SvStream& rStream, const OString& rStr, + bool bOn ) +{ + if(bOn) + rStream.WriteCharPtr("<"); + else + rStream.WriteCharPtr("</"); + + rStream.WriteOString(rStr).WriteChar('>'); + + return rStream; +} + +SvStream& HTMLOutFuncs::Out_Char( SvStream& rStream, sal_uInt32 c, + HTMLOutContext& rContext, + OUString *pNonConvertableChars ) +{ + OString sOut = lcl_ConvertCharToHTML( c, rContext, pNonConvertableChars ); + rStream.WriteOString( sOut ); + return rStream; +} + +SvStream& HTMLOutFuncs::Out_String( SvStream& rStream, const OUString& rOUStr, + rtl_TextEncoding eDestEnc, + OUString *pNonConvertableChars ) +{ + HTMLOutContext aContext( eDestEnc ); + sal_Int32 nLen = rOUStr.getLength(); + for( sal_Int32 n = 0; n < nLen; ) + HTMLOutFuncs::Out_Char( rStream, rOUStr.iterateCodePoints(&n), + aContext, pNonConvertableChars ); + HTMLOutFuncs::FlushToAscii( rStream, aContext ); + return rStream; +} + +SvStream& HTMLOutFuncs::FlushToAscii( SvStream& rStream, + HTMLOutContext& rContext ) +{ + OString sOut = lcl_FlushToAscii( rContext ); + + if (!sOut.isEmpty()) + rStream.WriteOString( sOut ); + + return rStream; +} + +SvStream& HTMLOutFuncs::Out_Hex( SvStream& rStream, sal_uLong nHex, sal_uInt8 nLen ) +{ // out into a stream + char aNToABuf[] = "0000000000000000"; + + DBG_ASSERT( nLen < sizeof(aNToABuf), "too many places" ); + if( nLen>=sizeof(aNToABuf) ) + nLen = (sizeof(aNToABuf)-1); + + // set pointer to end of buffer + char *pStr = aNToABuf + (sizeof(aNToABuf)-1); + for( sal_uInt8 n = 0; n < nLen; ++n ) + { + *(--pStr) = static_cast<char>(nHex & 0xf ) + 48; + if( *pStr > '9' ) + *pStr += 39; + nHex >>= 4; + } + return rStream.WriteCharPtr( pStr ); +} + + +SvStream& HTMLOutFuncs::Out_Color( SvStream& rStream, const Color& rColor, bool bXHTML ) +{ + rStream.WriteCharPtr( "\"" ); + if (bXHTML) + rStream.WriteCharPtr( "color: " ); + rStream.WriteCharPtr( "#" ); + if( rColor == COL_AUTO ) + { + rStream.WriteCharPtr( "000000" ); + } + else + { + Out_Hex( rStream, rColor.GetRed(), 2 ); + Out_Hex( rStream, rColor.GetGreen(), 2 ); + Out_Hex( rStream, rColor.GetBlue(), 2 ); + } + rStream.WriteChar( '\"' ); + + return rStream; +} + +SvStream& HTMLOutFuncs::Out_ImageMap( SvStream& rStream, + const OUString& rBaseURL, + const ImageMap& rIMap, + const OUString& rName, + const HTMLOutEvent *pEventTable, + bool bOutStarBasic, + const char *pDelim, + const char *pIndentArea, + const char *pIndentMap, + rtl_TextEncoding eDestEnc, + OUString *pNonConvertableChars ) +{ + if( RTL_TEXTENCODING_DONTKNOW == eDestEnc ) + eDestEnc = osl_getThreadTextEncoding(); + + const OUString& rOutName = !rName.isEmpty() ? rName : rIMap.GetName(); + DBG_ASSERT( !rOutName.isEmpty(), "No ImageMap-Name" ); + if( rOutName.isEmpty() ) + return rStream; + + OStringBuffer sOut; + sOut.append('<') + .append(OOO_STRING_SVTOOLS_HTML_map) + .append(' ') + .append(OOO_STRING_SVTOOLS_HTML_O_name) + .append("=\""); + rStream.WriteOString( sOut.makeStringAndClear() ); + Out_String( rStream, rOutName, eDestEnc, pNonConvertableChars ); + rStream.WriteCharPtr( "\">" ); + + for( size_t i=0; i<rIMap.GetIMapObjectCount(); i++ ) + { + const IMapObject* pObj = rIMap.GetIMapObject( i ); + DBG_ASSERT( pObj, "Where is the ImageMap-Object?" ); + + if( pObj ) + { + const char *pShape = nullptr; + OString aCoords; + switch( pObj->GetType() ) + { + case IMAP_OBJ_RECTANGLE: + { + const IMapRectangleObject* pRectObj = + static_cast<const IMapRectangleObject *>(pObj); + pShape = OOO_STRING_SVTOOLS_HTML_SH_rect; + tools::Rectangle aRect( pRectObj->GetRectangle() ); + + aCoords = OStringBuffer() + .append(static_cast<sal_Int32>(aRect.Left())) + .append(',') + .append(static_cast<sal_Int32>(aRect.Top())) + .append(',') + .append(static_cast<sal_Int32>(aRect.Right())) + .append(',') + .append(static_cast<sal_Int32>(aRect.Bottom())) + .makeStringAndClear(); + } + break; + case IMAP_OBJ_CIRCLE: + { + const IMapCircleObject* pCirc = + static_cast<const IMapCircleObject *>(pObj); + pShape= OOO_STRING_SVTOOLS_HTML_SH_circ; + Point aCenter( pCirc->GetCenter() ); + long nOff = pCirc->GetRadius(); + + aCoords = OStringBuffer() + .append(static_cast<sal_Int32>(aCenter.X())) + .append(',') + .append(static_cast<sal_Int32>(aCenter.Y())) + .append(',') + .append(static_cast<sal_Int32>(nOff)) + .makeStringAndClear(); + } + break; + case IMAP_OBJ_POLYGON: + { + const IMapPolygonObject* pPolyObj = + static_cast<const IMapPolygonObject *>(pObj); + pShape= OOO_STRING_SVTOOLS_HTML_SH_poly; + tools::Polygon aPoly( pPolyObj->GetPolygon() ); + sal_uInt16 nCount = aPoly.GetSize(); + OStringBuffer aTmpBuf; + if( nCount>0 ) + { + const Point& rPoint = aPoly[0]; + aTmpBuf.append(static_cast<sal_Int32>(rPoint.X())) + .append(',') + .append(static_cast<sal_Int32>(rPoint.Y())); + } + for( sal_uInt16 j=1; j<nCount; j++ ) + { + const Point& rPoint = aPoly[j]; + aTmpBuf.append(',') + .append(static_cast<sal_Int32>(rPoint.X())) + .append(',') + .append(static_cast<sal_Int32>(rPoint.Y())); + } + aCoords = aTmpBuf.makeStringAndClear(); + } + break; + default: + DBG_ASSERT( pShape, "unknown IMapObject" ); + break; + } + + if( pShape ) + { + if( pDelim ) + rStream.WriteCharPtr( pDelim ); + if( pIndentArea ) + rStream.WriteCharPtr( pIndentArea ); + + sOut.append('<').append(OOO_STRING_SVTOOLS_HTML_area) + .append(' ').append(OOO_STRING_SVTOOLS_HTML_O_shape) + .append('=').append(pShape).append(' ') + .append(OOO_STRING_SVTOOLS_HTML_O_coords).append("=\"") + .append(aCoords).append("\" "); + rStream.WriteOString( sOut.makeStringAndClear() ); + + OUString aURL( pObj->GetURL() ); + if( !aURL.isEmpty() && pObj->IsActive() ) + { + aURL = URIHelper::simpleNormalizedMakeRelative( + rBaseURL, aURL ); + sOut.append(OOO_STRING_SVTOOLS_HTML_O_href).append("=\""); + rStream.WriteOString( sOut.makeStringAndClear() ); + Out_String( rStream, aURL, eDestEnc, pNonConvertableChars ).WriteChar( '\"' ); + } + else + rStream.WriteCharPtr( OOO_STRING_SVTOOLS_HTML_O_nohref ); + + const OUString& rObjName = pObj->GetName(); + if( !rObjName.isEmpty() ) + { + sOut.append(' ').append(OOO_STRING_SVTOOLS_HTML_O_name) + .append("=\""); + rStream.WriteOString( sOut.makeStringAndClear() ); + Out_String( rStream, rObjName, eDestEnc, pNonConvertableChars ).WriteChar( '\"' ); + } + + const OUString& rTarget = pObj->GetTarget(); + if( !rTarget.isEmpty() && pObj->IsActive() ) + { + sOut.append(' ').append(OOO_STRING_SVTOOLS_HTML_O_target) + .append("=\""); + rStream.WriteOString( sOut.makeStringAndClear() ); + Out_String( rStream, rTarget, eDestEnc, pNonConvertableChars ).WriteChar( '\"' ); + } + + OUString rDesc( pObj->GetAltText() ); + if( rDesc.isEmpty() ) + rDesc = pObj->GetDesc(); + + if( !rDesc.isEmpty() ) + { + sOut.append(' ').append(OOO_STRING_SVTOOLS_HTML_O_alt) + .append("=\""); + rStream.WriteOString( sOut.makeStringAndClear() ); + Out_String( rStream, rDesc, eDestEnc, pNonConvertableChars ).WriteChar( '\"' ); + } + + const SvxMacroTableDtor& rMacroTab = pObj->GetMacroTable(); + if( pEventTable && !rMacroTab.empty() ) + Out_Events( rStream, rMacroTab, pEventTable, + bOutStarBasic, eDestEnc, pNonConvertableChars ); + + rStream.WriteChar( '>' ); + } + } + + } + + if( pDelim ) + rStream.WriteCharPtr( pDelim ); + if( pIndentMap ) + rStream.WriteCharPtr( pIndentMap ); + Out_AsciiTag( rStream, OOO_STRING_SVTOOLS_HTML_map, false ); + + return rStream; +} + +SvStream& HTMLOutFuncs::OutScript( SvStream& rStrm, + const OUString& rBaseURL, + const OUString& rSource, + const OUString& rLanguage, + ScriptType eScriptType, + const OUString& rSrc, + const OUString *pSBLibrary, + const OUString *pSBModule, + rtl_TextEncoding eDestEnc, + OUString *pNonConvertableChars ) +{ + if( RTL_TEXTENCODING_DONTKNOW == eDestEnc ) + eDestEnc = osl_getThreadTextEncoding(); + + // script is not indented! + OStringBuffer sOut; + sOut.append('<') + .append(OOO_STRING_SVTOOLS_HTML_script); + + if( !rLanguage.isEmpty() ) + { + sOut.append(' ') + .append(OOO_STRING_SVTOOLS_HTML_O_language) + .append("=\""); + rStrm.WriteOString( sOut.makeStringAndClear() ); + Out_String( rStrm, rLanguage, eDestEnc, pNonConvertableChars ); + sOut.append('\"'); + } + + if( !rSrc.isEmpty() ) + { + sOut.append(' ').append(OOO_STRING_SVTOOLS_HTML_O_src).append("=\""); + rStrm.WriteOString( sOut.makeStringAndClear() ); + Out_String( rStrm, URIHelper::simpleNormalizedMakeRelative(rBaseURL, rSrc), eDestEnc, pNonConvertableChars ); + sOut.append('\"'); + } + + if( STARBASIC != eScriptType && pSBLibrary ) + { + sOut.append(' ').append(OOO_STRING_SVTOOLS_HTML_O_sdlibrary) + .append("=\""); + rStrm.WriteOString( sOut.makeStringAndClear() ); + Out_String( rStrm, *pSBLibrary, eDestEnc, pNonConvertableChars ); + sOut.append('\"'); + } + + if( STARBASIC != eScriptType && pSBModule ) + { + sOut.append(' ').append(OOO_STRING_SVTOOLS_HTML_O_sdmodule) + .append("=\""); + rStrm.WriteOString( sOut.makeStringAndClear() ); + Out_String( rStrm, *pSBModule, eDestEnc, pNonConvertableChars ); + sOut.append('\"'); + } + + sOut.append('>'); + + rStrm.WriteOString( sOut.makeStringAndClear() ); + + if( !rSource.isEmpty() || pSBLibrary || pSBModule ) + { + rStrm.WriteCharPtr( SAL_NEWLINE_STRING ); + + if( JAVASCRIPT != eScriptType ) + { + rStrm.WriteCharPtr( "<!--" ) + .WriteCharPtr( SAL_NEWLINE_STRING ); + } + + if( STARBASIC == eScriptType ) + { + if( pSBLibrary ) + { + sOut.append("' ") + .append(OOO_STRING_SVTOOLS_HTML_SB_library) + .append(' ') + .append(OUStringToOString(*pSBLibrary, eDestEnc)); + rStrm.WriteOString( sOut.makeStringAndClear() ).WriteCharPtr( SAL_NEWLINE_STRING ); + } + + if( pSBModule ) + { + sOut.append("' ") + .append(OOO_STRING_SVTOOLS_HTML_SB_module) + .append(' ') + .append(OUStringToOString(*pSBModule, eDestEnc)); + rStrm.WriteOString( sOut.makeStringAndClear() ).WriteCharPtr( SAL_NEWLINE_STRING ); + } + } + + if( !rSource.isEmpty() ) + { + // we write the module in ANSI-charset, but with + // the system new line. + const OString sSource(OUStringToOString(rSource, eDestEnc)); + rStrm.WriteOString( sSource ).WriteCharPtr( SAL_NEWLINE_STRING ); + } + rStrm.WriteCharPtr( SAL_NEWLINE_STRING ); + + if( JAVASCRIPT != eScriptType ) + { + // MIB/MM: if it is not StarBasic, a // could be wrong. + // As the comment is removed during reading, it is not helping us... + rStrm.WriteCharPtr( STARBASIC == eScriptType ? "' -->" : "// -->" ) + .WriteCharPtr( SAL_NEWLINE_STRING ); + } + } + + HTMLOutFuncs::Out_AsciiTag( rStrm, OOO_STRING_SVTOOLS_HTML_script, false ); + + return rStrm; +} + + +SvStream& HTMLOutFuncs::Out_Events( SvStream& rStrm, + const SvxMacroTableDtor& rMacroTable, + const HTMLOutEvent *pEventTable, + bool bOutStarBasic, + rtl_TextEncoding eDestEnc, + OUString *pNonConvertableChars ) +{ + sal_uInt16 i=0; + while( pEventTable[i].pBasicName || pEventTable[i].pJavaName ) + { + const SvxMacro *pMacro = + rMacroTable.Get( pEventTable[i].nEvent ); + + if( pMacro && pMacro->HasMacro() && + ( JAVASCRIPT == pMacro->GetScriptType() || bOutStarBasic )) + { + const char *pStr = STARBASIC == pMacro->GetScriptType() + ? pEventTable[i].pBasicName + : pEventTable[i].pJavaName; + + if( pStr ) + { + OString sOut = " " + rtl::OStringView(pStr) + "=\""; + rStrm.WriteOString( sOut ); + + Out_String( rStrm, pMacro->GetMacName(), eDestEnc, pNonConvertableChars ).WriteChar( '\"' ); + } + } + i++; + } + + return rStrm; +} + +OString HTMLOutFuncs::CreateTableDataOptionsValNum( + bool bValue, + double fVal, sal_uLong nFormat, SvNumberFormatter& rFormatter, + rtl_TextEncoding eDestEnc, OUString* pNonConvertableChars) +{ + OStringBuffer aStrTD; + + if ( bValue ) + { + // printf / scanf is not precise enough + OUString aValStr; + rFormatter.GetInputLineString( fVal, 0, aValStr ); + OString sTmp(OUStringToOString(aValStr, eDestEnc)); + aStrTD.append(' '). + append(OOO_STRING_SVTOOLS_HTML_O_SDval). + append("=\""). + append(sTmp).append('\"'); + } + if ( bValue || nFormat ) + { + aStrTD.append(' '). + append(OOO_STRING_SVTOOLS_HTML_O_SDnum). + append("=\""). + append(static_cast<sal_Int32>(static_cast<sal_uInt16>( + Application::GetSettings().GetLanguageTag().getLanguageType()))). + append(';'); // Language for Format 0 + if ( nFormat ) + { + OString aNumStr; + LanguageType nLang; + const SvNumberformat* pFormatEntry = rFormatter.GetEntry( nFormat ); + if ( pFormatEntry ) + { + aNumStr = ConvertStringToHTML( pFormatEntry->GetFormatstring(), + eDestEnc, pNonConvertableChars ); + nLang = pFormatEntry->GetLanguage(); + } + else + nLang = LANGUAGE_SYSTEM; + aStrTD.append(static_cast<sal_Int32>(static_cast<sal_uInt16>(nLang))).append(';'). + append(aNumStr); + } + aStrTD.append('\"'); + } + return aStrTD.makeStringAndClear(); +} + +bool HTMLOutFuncs::PrivateURLToInternalImg( OUString& rURL ) +{ + if( rURL.startsWith(OOO_STRING_SVTOOLS_HTML_private_image) ) + { + rURL = rURL.copy( strlen(OOO_STRING_SVTOOLS_HTML_private_image) ); + return true; + } + + return false; +} + +void HtmlWriterHelper::applyColor(HtmlWriter& rHtmlWriter, const OString &aAttributeName, const Color& rColor) +{ + OStringBuffer sBuffer; + + if( rColor == COL_AUTO ) + { + sBuffer.append("#000000"); + } + else + { + sBuffer.append('#'); + std::ostringstream sStringStream; + sStringStream + << std::right + << std::setfill('0') + << std::setw(6) + << std::hex + << sal_uInt32(rColor.GetRGBColor()); + sBuffer.append(sStringStream.str().c_str()); + } + + rHtmlWriter.attribute(aAttributeName, sBuffer.makeStringAndClear()); +} + + +void HtmlWriterHelper::applyEvents(HtmlWriter& rHtmlWriter, const SvxMacroTableDtor& rMacroTable, const HTMLOutEvent* pEventTable, bool bOutStarBasic) +{ + sal_uInt16 i = 0; + while (pEventTable[i].pBasicName || pEventTable[i].pJavaName) + { + const SvxMacro* pMacro = rMacroTable.Get(pEventTable[i].nEvent); + + if (pMacro && pMacro->HasMacro() && (JAVASCRIPT == pMacro->GetScriptType() || bOutStarBasic)) + { + const char* pAttributeName = nullptr; + if (STARBASIC == pMacro->GetScriptType()) + pAttributeName = pEventTable[i].pBasicName; + else + pAttributeName = pEventTable[i].pJavaName; + + if (pAttributeName) + { + rHtmlWriter.attribute(pAttributeName, OUStringToOString(pMacro->GetMacName(), RTL_TEXTENCODING_UTF8)); + } + } + i++; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/svhtml/htmlsupp.cxx b/svtools/source/svhtml/htmlsupp.cxx new file mode 100644 index 000000000..cdff0f352 --- /dev/null +++ b/svtools/source/svhtml/htmlsupp.cxx @@ -0,0 +1,159 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <comphelper/string.hxx> +#include <svtools/parhtml.hxx> +#include <svtools/htmltokn.h> +#include <svtools/htmlkywd.hxx> +#include <tools/urlobj.hxx> + +// Table for converting option values into strings +static HTMLOptionEnum<HTMLScriptLanguage> const aScriptLangOptEnums[] = +{ + { OOO_STRING_SVTOOLS_HTML_LG_starbasic, HTMLScriptLanguage::StarBasic }, + { OOO_STRING_SVTOOLS_HTML_LG_javascript, HTMLScriptLanguage::JavaScript }, + { OOO_STRING_SVTOOLS_HTML_LG_javascript11, HTMLScriptLanguage::JavaScript }, + { OOO_STRING_SVTOOLS_HTML_LG_livescript, HTMLScriptLanguage::JavaScript }, + { nullptr, HTMLScriptLanguage(0) } +}; + +void HTMLParser::ParseScriptOptions( OUString& rLangString, const OUString& rBaseURL, + HTMLScriptLanguage& rLang, + OUString& rSrc, + OUString& rLibrary, + OUString& rModule ) +{ + const HTMLOptions& aScriptOptions = GetOptions(); + + rLangString.clear(); + rLang = HTMLScriptLanguage::JavaScript; + rSrc.clear(); + rLibrary.clear(); + rModule.clear(); + + for( size_t i = aScriptOptions.size(); i; ) + { + const HTMLOption& aOption = aScriptOptions[--i]; + switch( aOption.GetToken() ) + { + case HtmlOptionId::LANGUAGE: + { + rLangString = aOption.GetString(); + HTMLScriptLanguage nLang; + if( aOption.GetEnum( nLang, aScriptLangOptEnums ) ) + rLang = nLang; + else + rLang = HTMLScriptLanguage::Unknown; + } + break; + + case HtmlOptionId::SRC: + rSrc = INetURLObject::GetAbsURL( rBaseURL, aOption.GetString() ); + break; + case HtmlOptionId::SDLIBRARY: + rLibrary = aOption.GetString(); + break; + + case HtmlOptionId::SDMODULE: + rModule = aOption.GetString(); + break; + default: break; + } + } +} + +void HTMLParser::RemoveSGMLComment( OUString &rString ) +{ + sal_Unicode c = 0; + sal_Int32 idx = 0; + while (idx < rString.getLength()) + { + c = rString[idx]; + if (!( c==' ' || c=='\t' || c=='\r' || c=='\n' ) ) + break; + idx++; + } + if (idx) + rString = rString.copy( idx ); + + idx = rString.getLength() - 1; + while (idx > 0) + // Can never get to 0 because that would mean the string contains only whitespace, and the first + // loop would already have removed all of those. + { + c = rString[idx]; + if (!( c==' ' || c=='\t' || c=='\r' || c=='\n' ) ) + break; + idx--; + } + if (idx != rString.getLength() - 1) + rString = rString.copy( 0, idx + 1 ); + + // remove SGML comments + if( rString.startsWith( "<!--" ) ) + { + // the whole line + sal_Int32 nPos = 4; + while( nPos < rString.getLength() ) + { + c = rString[nPos]; + if (c == '\r' || c == '\n') + break; + ++nPos; + } + if( c == '\r' && nPos+1 < rString.getLength() && + '\n' == rString[nPos+1] ) + ++nPos; + else if( c != '\n' ) + nPos = 3; + ++nPos; + rString = rString.copy( nPos ); + } + + if( !rString.endsWith("-->") ) + return; + + rString = rString.copy( 0, rString.getLength()-3 ); + // "//" or "'", maybe preceding CR/LF + rString = comphelper::string::stripEnd(rString, ' '); + sal_Int32 nDel = 0, nLen = rString.getLength(); + if( nLen >= 2 && + rString.endsWith("//") ) + { + nDel = 2; + } + else if( nLen && '\'' == rString[nLen-1] ) + { + nDel = 1; + } + if( nDel && nLen >= nDel+1 ) + { + c = rString[nLen-(nDel+1)]; + if( '\r'==c || '\n'==c ) + { + nDel++; + if( '\n'==c && nLen >= nDel+1 && + '\r'==rString[nLen-(nDel+1)] ) + nDel++; + } + } + rString = rString.copy( 0, nLen-nDel ); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/svhtml/parhtml.cxx b/svtools/source/svhtml/parhtml.cxx new file mode 100644 index 000000000..b3664713a --- /dev/null +++ b/svtools/source/svhtml/parhtml.cxx @@ -0,0 +1,2161 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <comphelper/string.hxx> +#include <o3tl/safeint.hxx> +#include <tools/stream.hxx> +#include <tools/debug.hxx> +#include <tools/color.hxx> +#include <rtl/ustrbuf.hxx> +#include <rtl/character.hxx> +#include <rtl/tencinfo.h> +#include <sal/log.hxx> +#include <tools/tenccvt.hxx> +#include <tools/datetime.hxx> +#include <unotools/datetime.hxx> +#include <svl/inettype.hxx> +#include <svl/lngmisc.hxx> +#include <com/sun/star/beans/PropertyAttribute.hpp> +#include <com/sun/star/document/XDocumentProperties.hpp> + +#include <svtools/parhtml.hxx> +#include <svtools/htmltokn.h> +#include <svtools/htmlkywd.hxx> + +#include <utility> + +using namespace ::com::sun::star; + + +const sal_Int32 MAX_LEN( 1024 ); + +const sal_Int32 MAX_ENTITY_LEN( 8 ); + + +// Tables to convert option values into strings + +// <INPUT TYPE=xxx> +static HTMLOptionEnum<HTMLInputType> const aInputTypeOptEnums[] = +{ + { OOO_STRING_SVTOOLS_HTML_IT_text, HTMLInputType::Text }, + { OOO_STRING_SVTOOLS_HTML_IT_password, HTMLInputType::Password }, + { OOO_STRING_SVTOOLS_HTML_IT_checkbox, HTMLInputType::Checkbox }, + { OOO_STRING_SVTOOLS_HTML_IT_radio, HTMLInputType::Radio }, + { OOO_STRING_SVTOOLS_HTML_IT_range, HTMLInputType::Range }, + { OOO_STRING_SVTOOLS_HTML_IT_scribble, HTMLInputType::Scribble }, + { OOO_STRING_SVTOOLS_HTML_IT_file, HTMLInputType::File }, + { OOO_STRING_SVTOOLS_HTML_IT_hidden, HTMLInputType::Hidden }, + { OOO_STRING_SVTOOLS_HTML_IT_submit, HTMLInputType::Submit }, + { OOO_STRING_SVTOOLS_HTML_IT_image, HTMLInputType::Image }, + { OOO_STRING_SVTOOLS_HTML_IT_reset, HTMLInputType::Reset }, + { OOO_STRING_SVTOOLS_HTML_IT_button, HTMLInputType::Button }, + { nullptr, HTMLInputType(0) } +}; + +// <TABLE FRAME=xxx> +static HTMLOptionEnum<HTMLTableFrame> const aTableFrameOptEnums[] = +{ + { OOO_STRING_SVTOOLS_HTML_TF_void, HTMLTableFrame::Void }, + { OOO_STRING_SVTOOLS_HTML_TF_above, HTMLTableFrame::Above }, + { OOO_STRING_SVTOOLS_HTML_TF_below, HTMLTableFrame::Below }, + { OOO_STRING_SVTOOLS_HTML_TF_hsides, HTMLTableFrame::HSides }, + { OOO_STRING_SVTOOLS_HTML_TF_lhs, HTMLTableFrame::LHS }, + { OOO_STRING_SVTOOLS_HTML_TF_rhs, HTMLTableFrame::RHS }, + { OOO_STRING_SVTOOLS_HTML_TF_vsides, HTMLTableFrame::VSides }, + { OOO_STRING_SVTOOLS_HTML_TF_box, HTMLTableFrame::Box }, + { OOO_STRING_SVTOOLS_HTML_TF_border, HTMLTableFrame::Box }, + { nullptr, HTMLTableFrame(0) } +}; + +// <TABLE RULES=xxx> +static HTMLOptionEnum<HTMLTableRules> const aTableRulesOptEnums[] = +{ + { OOO_STRING_SVTOOLS_HTML_TR_none, HTMLTableRules::NONE }, + { OOO_STRING_SVTOOLS_HTML_TR_groups, HTMLTableRules::Groups }, + { OOO_STRING_SVTOOLS_HTML_TR_rows, HTMLTableRules::Rows }, + { OOO_STRING_SVTOOLS_HTML_TR_cols, HTMLTableRules::Cols }, + { OOO_STRING_SVTOOLS_HTML_TR_all, HTMLTableRules::All }, + { nullptr, HTMLTableRules(0) } +}; + + +HTMLOption::HTMLOption( HtmlOptionId nTok, const OUString& rToken, + const OUString& rValue ) + : aValue(rValue) + , aToken(rToken) + , nToken( nTok ) +{ + DBG_ASSERT( nToken>=HtmlOptionId::BOOL_START && nToken<HtmlOptionId::END, + "HTMLOption: unknown token" ); +} + +sal_uInt32 HTMLOption::GetNumber() const +{ + DBG_ASSERT( (nToken>=HtmlOptionId::NUMBER_START && + nToken<HtmlOptionId::NUMBER_END) || + (nToken>=HtmlOptionId::CONTEXT_START && + nToken<HtmlOptionId::CONTEXT_END) || + nToken==HtmlOptionId::VALUE, + "GetNumber: Option not numerical" ); + OUString aTmp(comphelper::string::stripStart(aValue, ' ')); + sal_Int32 nTmp = aTmp.toInt32(); + return nTmp >= 0 ? static_cast<sal_uInt32>(nTmp) : 0; +} + +sal_Int32 HTMLOption::GetSNumber() const +{ + DBG_ASSERT( (nToken>=HtmlOptionId::NUMBER_START && nToken<HtmlOptionId::NUMBER_END) || + (nToken>=HtmlOptionId::CONTEXT_START && nToken<HtmlOptionId::CONTEXT_END), + "GetSNumber: Option not numerical" ); + OUString aTmp(comphelper::string::stripStart(aValue, ' ')); + return aTmp.toInt32(); +} + +void HTMLOption::GetNumbers( std::vector<sal_uInt32> &rNumbers ) const +{ + rNumbers.clear(); + + // This is a very simplified scanner: it only searches all + // numerals in the string. + bool bInNum = false; + sal_uLong nNum = 0; + for( sal_Int32 i=0; i<aValue.getLength(); i++ ) + { + sal_Unicode c = aValue[ i ]; + if( c>='0' && c<='9' ) + { + nNum *= 10; + nNum += (c - '0'); + bInNum = true; + } + else if( bInNum ) + { + rNumbers.push_back( nNum ); + bInNum = false; + nNum = 0; + } + } + if( bInNum ) + { + rNumbers.push_back( nNum ); + } +} + +void HTMLOption::GetColor( Color& rColor ) const +{ + DBG_ASSERT( (nToken>=HtmlOptionId::COLOR_START && nToken<HtmlOptionId::COLOR_END) || nToken==HtmlOptionId::SIZE, + "GetColor: Option is not a color." ); + + OUString aTmp(aValue.toAsciiLowerCase()); + sal_uInt32 nColor = SAL_MAX_UINT32; + if (!aTmp.isEmpty() && aTmp[0] != '#') + nColor = GetHTMLColor(aTmp); + + if( SAL_MAX_UINT32 == nColor ) + { + nColor = 0; + sal_Int32 nPos = 0; + for (sal_uInt32 i=0; i<6; ++i) + { + // Whatever Netscape does to get color values, + // at maximum three characters < '0' are ignored. + sal_Unicode c = nPos<aTmp.getLength() ? aTmp[ nPos++ ] : '0'; + if( c < '0' ) + { + c = nPos<aTmp.getLength() ? aTmp[nPos++] : '0'; + if( c < '0' ) + c = nPos<aTmp.getLength() ? aTmp[nPos++] : '0'; + } + nColor *= 16; + if( c >= '0' && c <= '9' ) + nColor += (c - '0'); + else if( c >= 'a' && c <= 'f' ) + nColor += (c + 0xa - 'a'); + } + } + + rColor.SetRed( static_cast<sal_uInt8>((nColor & 0x00ff0000) >> 16) ); + rColor.SetGreen( static_cast<sal_uInt8>((nColor & 0x0000ff00) >> 8)); + rColor.SetBlue( static_cast<sal_uInt8>(nColor & 0x000000ff) ); +} + +HTMLInputType HTMLOption::GetInputType() const +{ + DBG_ASSERT( nToken==HtmlOptionId::TYPE, "GetInputType: Option not TYPE" ); + return GetEnum( aInputTypeOptEnums, HTMLInputType::Text ); +} + +HTMLTableFrame HTMLOption::GetTableFrame() const +{ + DBG_ASSERT( nToken==HtmlOptionId::FRAME, "GetTableFrame: Option not FRAME" ); + return GetEnum( aTableFrameOptEnums ); +} + +HTMLTableRules HTMLOption::GetTableRules() const +{ + DBG_ASSERT( nToken==HtmlOptionId::RULES, "GetTableRules: Option not RULES" ); + return GetEnum( aTableRulesOptEnums ); +} + +HTMLParser::HTMLParser( SvStream& rIn, bool bReadNewDoc ) : + SvParser<HtmlTokenId>( rIn ), + bNewDoc(bReadNewDoc), + bIsInHeader(true), + bReadListing(false), + bReadXMP(false), + bReadPRE(false), + bReadTextArea(false), + bReadScript(false), + bReadStyle(false), + bEndTokenFound(false), + bPre_IgnoreNewPara(false), + bReadNextChar(false), + bReadComment(false), + nPre_LinePos(0), + mnPendingOffToken(HtmlTokenId::NONE) +{ + //#i76649, default to UTF-8 for HTML unless we know differently + SetSrcEncoding(RTL_TEXTENCODING_UTF8); +} + +HTMLParser::~HTMLParser() +{ +} + +void HTMLParser::SetNamespace(const OUString& rNamespace) +{ + // Convert namespace alias to a prefix. + maNamespace = rNamespace + ":"; +} + +namespace +{ + class RefGuard + { + private: + HTMLParser& m_rParser; + public: + RefGuard(HTMLParser& rParser) + : m_rParser(rParser) + { + m_rParser.AddFirstRef(); + } + + ~RefGuard() + { + if (m_rParser.GetStatus() != SvParserState::Pending) + m_rParser.ReleaseRef(); // Parser not needed anymore + } + }; +} + +SvParserState HTMLParser::CallParser() +{ + eState = SvParserState::Working; + nNextCh = GetNextChar(); + SaveState( HtmlTokenId::NONE ); + + nPre_LinePos = 0; + bPre_IgnoreNewPara = false; + + RefGuard aRefGuard(*this); + + Continue( HtmlTokenId::NONE ); + + return eState; +} + +void HTMLParser::Continue( HtmlTokenId nToken ) +{ + if( nToken == HtmlTokenId::NONE ) + nToken = GetNextToken(); + + while( IsParserWorking() ) + { + SaveState( nToken ); + nToken = FilterToken( nToken ); + + if( nToken != HtmlTokenId::NONE ) + NextToken( nToken ); + + if( IsParserWorking() ) + SaveState( HtmlTokenId::NONE ); // continue with new token + + nToken = GetNextToken(); + } +} + +HtmlTokenId HTMLParser::FilterToken( HtmlTokenId nToken ) +{ + switch( nToken ) + { + case HtmlTokenId(EOF): + nToken = HtmlTokenId::NONE; + break; // don't pass + + case HtmlTokenId::HEAD_OFF: + bIsInHeader = false; + break; + + case HtmlTokenId::HEAD_ON: + bIsInHeader = true; + break; + + case HtmlTokenId::BODY_ON: + bIsInHeader = false; + break; + + case HtmlTokenId::FRAMESET_ON: + bIsInHeader = false; + break; + + case HtmlTokenId::BODY_OFF: + bReadPRE = bReadListing = bReadXMP = false; + break; + + case HtmlTokenId::HTML_OFF: + nToken = HtmlTokenId::NONE; + bReadPRE = bReadListing = bReadXMP = false; + break; // HtmlTokenId::ON hasn't been passed either ! + + case HtmlTokenId::PREFORMTXT_ON: + StartPRE(); + break; + + case HtmlTokenId::PREFORMTXT_OFF: + FinishPRE(); + break; + + case HtmlTokenId::LISTING_ON: + StartListing(); + break; + + case HtmlTokenId::LISTING_OFF: + FinishListing(); + break; + + case HtmlTokenId::XMP_ON: + StartXMP(); + break; + + case HtmlTokenId::XMP_OFF: + FinishXMP(); + break; + + default: + if( bReadPRE ) + nToken = FilterPRE( nToken ); + else if( bReadListing ) + nToken = FilterListing( nToken ); + else if( bReadXMP ) + nToken = FilterXMP( nToken ); + + break; + } + + return nToken; +} + +namespace { + +constexpr bool HTML_ISPRINTABLE(sal_Unicode c) { return c >= 32 && c != 127; } + +} + +HtmlTokenId HTMLParser::ScanText( const sal_Unicode cBreak ) +{ + OUStringBuffer sTmpBuffer( MAX_LEN ); + bool bContinue = true; + bool bEqSignFound = false; + sal_uInt32 cQuote = 0U; + + while( bContinue && IsParserWorking() ) + { + bool bNextCh = true; + switch( nNextCh ) + { + case '&': + bEqSignFound = false; + if( bReadXMP ) + sTmpBuffer.append( '&' ); + else + { + sal_uInt64 nStreamPos = rInput.Tell(); + sal_uLong nLinePos = GetLinePos(); + + sal_uInt32 cChar = 0U; + if( '#' == (nNextCh = GetNextChar()) ) + { + nNextCh = GetNextChar(); + const bool bIsHex( 'x' == nNextCh ); + const bool bIsDecOrHex( bIsHex || rtl::isAsciiDigit(nNextCh) ); + if ( bIsDecOrHex ) + { + if ( bIsHex ) + { + nNextCh = GetNextChar(); + while ( rtl::isAsciiHexDigit(nNextCh) ) + { + cChar = cChar * 16U + + ( nNextCh <= '9' + ? sal_uInt32( nNextCh - '0' ) + : ( nNextCh <= 'F' + ? sal_uInt32( nNextCh - 'A' + 10 ) + : sal_uInt32( nNextCh - 'a' + 10 ) ) ); + nNextCh = GetNextChar(); + } + } + else + { + do + { + cChar = cChar * 10U + sal_uInt32( nNextCh - '0'); + nNextCh = GetNextChar(); + } + while( rtl::isAsciiDigit(nNextCh) ); + } + + if( RTL_TEXTENCODING_DONTKNOW != eSrcEnc && + RTL_TEXTENCODING_UCS2 != eSrcEnc && + RTL_TEXTENCODING_UTF8 != eSrcEnc && + cChar < 256 ) + { + const sal_uInt32 convertFlags = + RTL_TEXTTOUNICODE_FLAGS_UNDEFINED_DEFAULT | + RTL_TEXTTOUNICODE_FLAGS_MBUNDEFINED_DEFAULT | + RTL_TEXTTOUNICODE_FLAGS_INVALID_DEFAULT; + + char cEncodedChar = static_cast<char>(cChar); + cChar = OUString(&cEncodedChar, 1, eSrcEnc, convertFlags).toChar(); + if( 0U == cChar ) + { + // If the character could not be + // converted, because a conversion is not + // available, do no conversion at all. + cChar = cEncodedChar; + } + } + } + else + nNextCh = 0U; + + if (!rtl::isUnicodeCodePoint(cChar) + || (linguistic::IsControlChar(cChar) + && cChar != '\r' && cChar != '\n' && cChar != '\t')) + { + cChar = '?'; + } + } + else if( rtl::isAsciiAlpha( nNextCh ) ) + { + OUStringBuffer sEntityBuffer( MAX_ENTITY_LEN ); + sal_Int32 nPos = 0; + do + { + sEntityBuffer.appendUtf32( nNextCh ); + nPos++; + nNextCh = GetNextChar(); + } + while( nPos < MAX_ENTITY_LEN && rtl::isAsciiAlphanumeric( nNextCh ) && + !rInput.eof() ); + + if( IsParserWorking() && !rInput.eof() ) + { + OUString sEntity(sEntityBuffer.getStr(), nPos); + cChar = GetHTMLCharName( sEntity ); + + // not found ( == 0 ): plain text + // or a character which is inserted as attribute + if( 0U == cChar && ';' != nNextCh ) + { + DBG_ASSERT( rInput.Tell() - nStreamPos == + static_cast<sal_uInt64>(nPos+1)*GetCharSize(), + "UTF-8 is failing here" ); + for( sal_Int32 i = nPos-1; i>1; i-- ) + { + nNextCh = sEntityBuffer[i]; + sEntityBuffer.setLength( i ); + sEntity = OUString(sEntityBuffer.getStr(), i); + cChar = GetHTMLCharName( sEntity ); + if( cChar ) + { + rInput.SeekRel( -static_cast<sal_Int64> + (nPos-i)*GetCharSize() ); + nlLinePos -= sal_uInt32(nPos-i); + nPos = i; + ClearTxtConvContext(); + break; + } + } + } + + if( !cChar ) // unknown character? + { + // back in stream, insert '&' + // and restart with next character + sTmpBuffer.append( '&' ); + + DBG_ASSERT( rInput.Tell()-nStreamPos == + static_cast<sal_uInt64>(nPos+1)*GetCharSize(), + "Wrong stream position" ); + DBG_ASSERT( nlLinePos-nLinePos == + static_cast<sal_uLong>(nPos+1), + "Wrong line position" ); + rInput.Seek( nStreamPos ); + nlLinePos = nLinePos; + ClearTxtConvContext(); + break; + } + + assert(cChar != 0); + + // 1 == Non Breaking Space + // 2 == SoftHyphen + + if (cChar == 1 || cChar == 2) + { + if( '>' == cBreak ) + { + // When reading the content of a tag we have + // to change it to ' ' or '-' + if( 1U == cChar ) + cChar = ' '; + else //2U + cChar = '-'; + } + else + { + // If not scanning a tag return token + aToken += sTmpBuffer; + sTmpBuffer.setLength(0); + + if( !aToken.isEmpty() ) + { + // restart with character + nNextCh = '&'; + DBG_ASSERT( rInput.Tell()-nStreamPos == + static_cast<sal_uInt64>(nPos+1)*GetCharSize(), + "Wrong stream position" ); + DBG_ASSERT( nlLinePos-nLinePos == + static_cast<sal_uLong>(nPos+1), + "Wrong line position" ); + rInput.Seek( nStreamPos ); + nlLinePos = nLinePos; + ClearTxtConvContext(); + return HtmlTokenId::TEXTTOKEN; + } + + // Hack: _GetNextChar shall not read the + // next character + if( ';' != nNextCh ) + aToken += " "; + if( 1U == cChar ) + return HtmlTokenId::NONBREAKSPACE; + else //2U + return HtmlTokenId::SOFTHYPH; + } + } + } + else + nNextCh = 0U; + } + // &{...};-JavaScript-Macros are not supported any longer. + else if( IsParserWorking() ) + { + sTmpBuffer.append( '&' ); + bNextCh = false; + break; + } + + bNextCh = (';' == nNextCh); + if( cBreak=='>' && (cChar=='\\' || cChar=='\'' || + cChar=='\"' || cChar==' ') ) + { + // ' and " have to be escaped within tags to separate + // them from ' and " enclosing options. + // \ has to be escaped as well. + // Space is protected because it's not a delimiter between + // options. + sTmpBuffer.append( '\\' ); + } + if( IsParserWorking() ) + { + if( cChar ) + sTmpBuffer.appendUtf32( cChar ); + } + else if( SvParserState::Pending==eState && '>'!=cBreak ) + { + // Restart with '&', the remainder is returned as + // text token. + if( !aToken.isEmpty() || !sTmpBuffer.isEmpty() ) + { + // _GetNextChar() returns the previous text and + // during the next execution a new character is read. + // Thus we have to position in front of the '&'. + nNextCh = 0U; + rInput.Seek( nStreamPos - GetCharSize() ); + nlLinePos = nLinePos-1; + ClearTxtConvContext(); + bReadNextChar = true; + } + bNextCh = false; + } + } + break; + case '=': + if( '>'==cBreak && !cQuote ) + bEqSignFound = true; + sTmpBuffer.appendUtf32( nNextCh ); + break; + + case '\\': + if( '>'==cBreak ) + { + // mark within tags + sTmpBuffer.append( '\\' ); + } + sTmpBuffer.append( '\\' ); + break; + + case '\"': + case '\'': + if( '>'==cBreak ) + { + if( bEqSignFound ) + cQuote = nNextCh; + else if( cQuote && (cQuote==nNextCh ) ) + cQuote = 0U; + } + sTmpBuffer.appendUtf32( nNextCh ); + bEqSignFound = false; + break; + + case sal_Unicode(EOF): + if( rInput.eof() ) + { + bContinue = false; + } + else + { + sTmpBuffer.appendUtf32( nNextCh ); + } + + break; + + case '<': + bEqSignFound = false; + if( '>'==cBreak ) + sTmpBuffer.appendUtf32( nNextCh ); + else + bContinue = false; // break, string is together + break; + + case '\f': + if( '>' == cBreak ) + { + // If scanning options treat it like a space, ... + sTmpBuffer.append( ' ' ); + } + else + { + // otherwise it's a separate token. + bContinue = false; + } + break; + + case '\r': + case '\n': + if( '>'==cBreak ) + { + // cr/lf in tag is handled in GetNextToken_() + sTmpBuffer.appendUtf32( nNextCh ); + break; + } + else if( bReadListing || bReadXMP || bReadPRE || bReadTextArea ) + { + bContinue = false; + break; + } + // Reduce sequence of CR/LF/BLANK/TAB to a single blank + [[fallthrough]]; + case '\t': + if( '\t'==nNextCh && bReadPRE && '>'!=cBreak ) + { + // Pass Tabs up in <PRE> + bContinue = false; + break; + } + [[fallthrough]]; + case '\x0b': + if( '\x0b'==nNextCh && (bReadPRE || bReadXMP ||bReadListing) && + '>'!=cBreak ) + { + break; + } + nNextCh = ' '; + [[fallthrough]]; + case ' ': + sTmpBuffer.appendUtf32( nNextCh ); + if( '>'!=cBreak && (!bReadListing && !bReadXMP && + !bReadPRE && !bReadTextArea) ) + { + // Reduce sequences of Blanks/Tabs/CR/LF to a single blank + do { + nNextCh = GetNextChar(); + if( sal_Unicode(EOF) == nNextCh && rInput.eof() ) + { + if( !aToken.isEmpty() || sTmpBuffer.getLength() > 1 ) + { + // Have seen s.th. aside from blanks? + aToken += sTmpBuffer; + sTmpBuffer.setLength(0); + return HtmlTokenId::TEXTTOKEN; + } + else + // Only read blanks: no text must be returned + // and GetNextToken_ has to read until EOF + return HtmlTokenId::NONE; + } + } while ( ' ' == nNextCh || '\t' == nNextCh || + '\r' == nNextCh || '\n' == nNextCh || + '\x0b' == nNextCh ); + bNextCh = false; + } + break; + + default: + bEqSignFound = false; + if (nNextCh == cBreak && !cQuote) + bContinue = false; + else + { + do { + if (!linguistic::IsControlChar(nNextCh)) + { + // All remaining characters make their way into the text. + sTmpBuffer.appendUtf32( nNextCh ); + } + + nNextCh = GetNextChar(); + if( ( sal_Unicode(EOF) == nNextCh && rInput.eof() ) || + !IsParserWorking() ) + { + if( !sTmpBuffer.isEmpty() ) + aToken += sTmpBuffer; + return HtmlTokenId::TEXTTOKEN; + } + } while( rtl::isAsciiAlpha( nNextCh ) || rtl::isAsciiDigit( nNextCh ) ); + bNextCh = false; + } + } + + if( bContinue && bNextCh ) + nNextCh = GetNextChar(); + } + + if( !sTmpBuffer.isEmpty() ) + aToken += sTmpBuffer; + + return HtmlTokenId::TEXTTOKEN; +} + +HtmlTokenId HTMLParser::GetNextRawToken() +{ + OUStringBuffer sTmpBuffer( MAX_LEN ); + + if( bEndTokenFound ) + { + // During the last execution we already found the end token, + // thus we don't have to search it again. + bReadScript = false; + bReadStyle = false; + aEndToken.clear(); + bEndTokenFound = false; + + return HtmlTokenId::NONE; + } + + // Default return value: HtmlTokenId::RAWDATA + bool bContinue = true; + HtmlTokenId nToken = HtmlTokenId::RAWDATA; + SaveState( HtmlTokenId::NONE ); + while( bContinue && IsParserWorking() ) + { + bool bNextCh = true; + switch( nNextCh ) + { + case '<': + { + // Maybe we've reached the end. + + // Save what we have read previously... + aToken += sTmpBuffer; + sTmpBuffer.setLength(0); + + // and remember position in stream. + sal_uInt64 nStreamPos = rInput.Tell(); + sal_uLong nLineNr = GetLineNr(); + sal_uLong nLinePos = GetLinePos(); + + // Start of an end token? + bool bOffState = false; + if( '/' == (nNextCh = GetNextChar()) ) + { + bOffState = true; + nNextCh = GetNextChar(); + } + else if( '!' == nNextCh ) + { + sTmpBuffer.appendUtf32( nNextCh ); + nNextCh = GetNextChar(); + } + + // Read following letters + while( (rtl::isAsciiAlpha(nNextCh) || '-'==nNextCh) && + IsParserWorking() && sTmpBuffer.getLength() < MAX_LEN ) + { + sTmpBuffer.appendUtf32( nNextCh ); + nNextCh = GetNextChar(); + } + + OUString aTok( sTmpBuffer.toString() ); + aTok = aTok.toAsciiLowerCase(); + bool bDone = false; + if( bReadScript || !aEndToken.isEmpty() ) + { + if( !bReadComment ) + { + if( aTok.startsWith( OOO_STRING_SVTOOLS_HTML_comment ) ) + { + bReadComment = true; + } + else + { + // A script has to end with "</SCRIPT>". But + // ">" is optional for security reasons + bDone = bOffState && + ( bReadScript + ? aTok == OOO_STRING_SVTOOLS_HTML_script + : aTok == aEndToken ); + } + } + if( bReadComment && '>'==nNextCh && aTok.endsWith( "--" ) ) + { + // End of comment of style <!-----> + bReadComment = false; + } + } + else + { + // Style sheets can be closed by </STYLE>, </HEAD> or <BODY> + if( bOffState ) + bDone = aTok == OOO_STRING_SVTOOLS_HTML_style || + aTok == OOO_STRING_SVTOOLS_HTML_head; + else + bDone = aTok == OOO_STRING_SVTOOLS_HTML_body; + } + + if( bDone ) + { + // Done! Return the previously read string (if requested) + // and continue. + + bContinue = false; + + // nToken==0 means, GetNextToken_ continues to read + if( aToken.isEmpty() && (bReadStyle || bReadScript) ) + { + // Immediately close environment (or context?) + // and parse the end token + bReadScript = false; + bReadStyle = false; + aEndToken.clear(); + nToken = HtmlTokenId::NONE; + } + else + { + // Keep bReadScript/bReadStyle alive + // and parse end token during next execution + bEndTokenFound = true; + } + + // Move backwards in stream to '<' + rInput.Seek( nStreamPos ); + SetLineNr( nLineNr ); + SetLinePos( nLinePos ); + ClearTxtConvContext(); + nNextCh = '<'; + + // Don't append string to token. + sTmpBuffer.setLength( 0 ); + } + else + { + // remember "</" , everything else we find in the buffer + aToken += "<"; + if( bOffState ) + aToken += "/"; + + bNextCh = false; + } + } + break; + case '-': + sTmpBuffer.appendUtf32( nNextCh ); + if( bReadComment ) + { + bool bTwoMinus = false; + nNextCh = GetNextChar(); + while( '-' == nNextCh && IsParserWorking() ) + { + bTwoMinus = true; + sTmpBuffer.appendUtf32( nNextCh ); + nNextCh = GetNextChar(); + } + + if( '>' == nNextCh && IsParserWorking() && bTwoMinus ) + bReadComment = false; + + bNextCh = false; + } + break; + + case '\r': + // \r\n? closes the current text token (even if it's empty) + nNextCh = GetNextChar(); + if( nNextCh=='\n' ) + nNextCh = GetNextChar(); + bContinue = false; + break; + case '\n': + // \n closes the current text token (even if it's empty) + nNextCh = GetNextChar(); + bContinue = false; + break; + case sal_Unicode(EOF): + // eof closes the current text token and behaves like having read + // an end token + if( rInput.eof() ) + { + bContinue = false; + if( !aToken.isEmpty() || !sTmpBuffer.isEmpty() ) + { + bEndTokenFound = true; + } + else + { + bReadScript = false; + bReadStyle = false; + aEndToken.clear(); + nToken = HtmlTokenId::NONE; + } + break; + } + [[fallthrough]]; + default: + if (!linguistic::IsControlChar(nNextCh) || nNextCh == '\t') + { + // all remaining characters are appended to the buffer + sTmpBuffer.appendUtf32( nNextCh ); + } + break; + } + + if( !bContinue && !sTmpBuffer.isEmpty() ) + { + aToken += sTmpBuffer; + sTmpBuffer.setLength(0); + } + + if( bContinue && bNextCh ) + nNextCh = GetNextChar(); + } + + if( IsParserWorking() ) + SaveState( HtmlTokenId::NONE ); + else + nToken = HtmlTokenId::NONE; + + return nToken; +} + +// Scan next token +HtmlTokenId HTMLParser::GetNextToken_() +{ + HtmlTokenId nRet = HtmlTokenId::NONE; + sSaveToken.clear(); + + if (mnPendingOffToken != HtmlTokenId::NONE) + { + // HtmlTokenId::<TOKEN>_OFF generated for HtmlTokenId::<TOKEN>_ON + nRet = mnPendingOffToken; + mnPendingOffToken = HtmlTokenId::NONE; + aToken.clear(); + return nRet; + } + + // Delete options + maOptions.clear(); + + if( !IsParserWorking() ) // Don't continue if already an error occurred + return HtmlTokenId::NONE; + + bool bReadNextCharSave = bReadNextChar; + if( bReadNextChar ) + { + DBG_ASSERT( !bEndTokenFound, + "Read a character despite </SCRIPT> was read?" ); + nNextCh = GetNextChar(); + if( !IsParserWorking() ) // Don't continue if already an error occurred + return HtmlTokenId::NONE; + bReadNextChar = false; + } + + if( bReadScript || bReadStyle || !aEndToken.isEmpty() ) + { + nRet = GetNextRawToken(); + if( nRet != HtmlTokenId::NONE || !IsParserWorking() ) + return nRet; + } + + do { + bool bNextCh = true; + switch( nNextCh ) + { + case '<': + { + sal_uInt64 nStreamPos = rInput.Tell(); + sal_uLong nLineNr = GetLineNr(); + sal_uLong nLinePos = GetLinePos(); + + bool bOffState = false; + if( '/' == (nNextCh = GetNextChar()) ) + { + bOffState = true; + nNextCh = GetNextChar(); + } + // Assume '<?' is a start of an XML declaration, ignore it. + if (rtl::isAsciiAlpha(nNextCh) || nNextCh == '!' || nNextCh == '?') + { + OUStringBuffer sTmpBuffer; + do { + sTmpBuffer.appendUtf32( nNextCh ); + nNextCh = GetNextChar(); + } while( '>' != nNextCh && '/' != nNextCh && !rtl::isAsciiWhiteSpace( nNextCh ) && + IsParserWorking() && !rInput.eof() ); + + if( !sTmpBuffer.isEmpty() ) + { + aToken += sTmpBuffer; + sTmpBuffer.setLength(0); + } + + // Skip blanks + while( rtl::isAsciiWhiteSpace( nNextCh ) && IsParserWorking() ) + nNextCh = GetNextChar(); + + if( !IsParserWorking() ) + { + if( SvParserState::Pending == eState ) + bReadNextChar = bReadNextCharSave; + break; + } + + // Search token in table: + sSaveToken = aToken; + aToken = aToken.toAsciiLowerCase(); + + if (!maNamespace.isEmpty() && aToken.startsWith(maNamespace)) + aToken = aToken.copy(maNamespace.getLength()); + + if( HtmlTokenId::NONE == (nRet = GetHTMLToken( aToken )) ) + // Unknown control + nRet = HtmlTokenId::UNKNOWNCONTROL_ON; + + // If it's a token which can be switched off... + if( bOffState ) + { + if( nRet >= HtmlTokenId::ONOFF_START ) + { + // and there is an off token, return off token instead + nRet = static_cast<HtmlTokenId>(static_cast<int>(nRet) + 1); + } + else if( HtmlTokenId::LINEBREAK!=nRet || !maNamespace.isEmpty()) + { + // and there is no off token, return unknown token. + // (except for </BR>, that is treated like <BR>) + // No exception for XHTML, though. + nRet = HtmlTokenId::UNKNOWNCONTROL_OFF; + } + } + + if( nRet == HtmlTokenId::COMMENT ) + { + // fix: due to being case sensitive use sSaveToken as start of comment + // and append a blank. + aToken = sSaveToken; + if( '>'!=nNextCh ) + aToken += " "; + sal_uInt64 nCStreamPos = 0; + sal_uLong nCLineNr = 0; + sal_uLong nCLinePos = 0; + sal_Int32 nCStrLen = 0; + + bool bDone = false; + // Read until closing -->. If not found restart at first > + sTmpBuffer = aToken; + while( !bDone && !rInput.eof() && IsParserWorking() ) + { + if( '>'==nNextCh ) + { + if( !nCStreamPos ) + { + nCStreamPos = rInput.Tell(); + nCStrLen = sTmpBuffer.getLength(); + nCLineNr = GetLineNr(); + nCLinePos = GetLinePos(); + } + bDone = sTmpBuffer.getLength() >= 2 && sTmpBuffer[sTmpBuffer.getLength() - 2] == '-' && sTmpBuffer[sTmpBuffer.getLength() - 1] == '-'; + if( !bDone ) + sTmpBuffer.appendUtf32(nNextCh); + } + else + sTmpBuffer.appendUtf32(nNextCh); + if( !bDone ) + nNextCh = GetNextChar(); + } + aToken = sTmpBuffer.makeStringAndClear(); + if( !bDone && IsParserWorking() && nCStreamPos ) + { + rInput.Seek( nCStreamPos ); + SetLineNr( nCLineNr ); + SetLinePos( nCLinePos ); + ClearTxtConvContext(); + aToken = aToken.copy(0, nCStrLen); + nNextCh = '>'; + } + } + else + { + // TokenString not needed anymore + aToken.clear(); + } + + // Read until closing '>' + if( '>' != nNextCh && IsParserWorking() ) + { + ScanText( '>' ); + + // fdo#34666 fdo#36080 fdo#36390: closing "/>"?: + // generate pending HtmlTokenId::<TOKEN>_OFF for HtmlTokenId::<TOKEN>_ON + // Do not convert this to a single HtmlTokenId::<TOKEN>_OFF + // which lead to fdo#56772. + if ((nRet >= HtmlTokenId::ONOFF_START) && aToken.endsWith("/")) + { + mnPendingOffToken = static_cast<HtmlTokenId>(static_cast<int>(nRet) + 1); // HtmlTokenId::<TOKEN>_ON -> HtmlTokenId::<TOKEN>_OFF + aToken = aToken.replaceAt( aToken.getLength()-1, 1, ""); // remove trailing '/' + } + if( sal_Unicode(EOF) == nNextCh && rInput.eof() ) + { + // Move back in front of < and restart there. + // Return < as text. + rInput.Seek( nStreamPos ); + SetLineNr( nLineNr ); + SetLinePos( nLinePos ); + ClearTxtConvContext(); + + aToken = "<"; + nRet = HtmlTokenId::TEXTTOKEN; + nNextCh = GetNextChar(); + bNextCh = false; + break; + } + } + if( SvParserState::Pending == eState ) + bReadNextChar = bReadNextCharSave; + } + else + { + if( bOffState ) + { + // simply throw away everything + ScanText( '>' ); + if( sal_Unicode(EOF) == nNextCh && rInput.eof() ) + { + // Move back in front of < and restart there. + // Return < as text. + rInput.Seek( nStreamPos ); + SetLineNr( nLineNr ); + SetLinePos( nLinePos ); + ClearTxtConvContext(); + + aToken = "<"; + nRet = HtmlTokenId::TEXTTOKEN; + nNextCh = GetNextChar(); + bNextCh = false; + break; + } + if( SvParserState::Pending == eState ) + bReadNextChar = bReadNextCharSave; + aToken.clear(); + } + else if( '%' == nNextCh ) + { + nRet = HtmlTokenId::UNKNOWNCONTROL_ON; + + sal_uInt64 nCStreamPos = rInput.Tell(); + sal_uLong nCLineNr = GetLineNr(), nCLinePos = GetLinePos(); + + bool bDone = false; + // Read until closing %>. If not found restart at first >. + sal_Unicode nLastTokenChar = !aToken.isEmpty() ? aToken[aToken.getLength() - 1] : 0; + OUStringBuffer aTmpBuffer(aToken); + while( !bDone && !rInput.eof() && IsParserWorking() ) + { + bDone = '>'==nNextCh && nLastTokenChar == '%'; + if( !bDone ) + { + aTmpBuffer.appendUtf32(nNextCh); + nLastTokenChar = aTmpBuffer[aTmpBuffer.getLength() - 1]; + nNextCh = GetNextChar(); + } + } + if( !bDone && IsParserWorking() ) + { + rInput.Seek( nCStreamPos ); + SetLineNr( nCLineNr ); + SetLinePos( nCLinePos ); + ClearTxtConvContext(); + aToken = "<%"; + nRet = HtmlTokenId::TEXTTOKEN; + break; + } + aToken = aTmpBuffer.makeStringAndClear(); + if( IsParserWorking() ) + { + sSaveToken = aToken; + aToken.clear(); + } + } + else + { + aToken = "<"; + nRet = HtmlTokenId::TEXTTOKEN; + bNextCh = false; + break; + } + } + + if( IsParserWorking() ) + { + bNextCh = '>' == nNextCh; + switch( nRet ) + { + case HtmlTokenId::TEXTAREA_ON: + bReadTextArea = true; + break; + case HtmlTokenId::TEXTAREA_OFF: + bReadTextArea = false; + break; + case HtmlTokenId::SCRIPT_ON: + if( !bReadTextArea ) + bReadScript = true; + break; + case HtmlTokenId::SCRIPT_OFF: + if( !bReadTextArea ) + { + bReadScript = false; + // JavaScript might modify the stream, + // thus the last character has to be read again. + bReadNextChar = true; + bNextCh = false; + } + break; + + case HtmlTokenId::STYLE_ON: + bReadStyle = true; + break; + case HtmlTokenId::STYLE_OFF: + bReadStyle = false; + break; + default: break; + } + } + } + break; + + case sal_Unicode(EOF): + if( rInput.eof() ) + { + eState = SvParserState::Accepted; + nRet = HtmlTokenId(nNextCh); + } + else + { + // Read normal text. + goto scan_text; + } + break; + + case '\f': + // form feeds are passed upwards separately + nRet = HtmlTokenId::LINEFEEDCHAR; // !!! should be FORMFEEDCHAR + break; + + case '\n': + case '\r': + if( bReadListing || bReadXMP || bReadPRE || bReadTextArea ) + { + sal_Unicode c = GetNextChar(); + if( ( '\n' != nNextCh || '\r' != c ) && + ( '\r' != nNextCh || '\n' != c ) ) + { + bNextCh = false; + nNextCh = c; + } + nRet = HtmlTokenId::NEWPARA; + break; + } + [[fallthrough]]; + case '\t': + if( bReadPRE ) + { + nRet = HtmlTokenId::TABCHAR; + break; + } + [[fallthrough]]; + case ' ': + [[fallthrough]]; + default: + +scan_text: + // "normal" text to come + nRet = ScanText(); + bNextCh = 0 == aToken.getLength(); + + // the text should be processed + if( !bNextCh && eState == SvParserState::Pending ) + { + eState = SvParserState::Working; + bReadNextChar = true; + } + + break; + } + + if( bNextCh && SvParserState::Working == eState ) + { + nNextCh = GetNextChar(); + if( SvParserState::Pending == eState && nRet != HtmlTokenId::NONE && HtmlTokenId::TEXTTOKEN != nRet ) + { + bReadNextChar = true; + eState = SvParserState::Working; + } + } + + } while( nRet == HtmlTokenId::NONE && SvParserState::Working == eState ); + + if( SvParserState::Pending == eState ) + nRet = HtmlTokenId::INVALID; // s.th. invalid + + return nRet; +} + +void HTMLParser::UnescapeToken() +{ + sal_Int32 nPos=0; + + bool bEscape = false; + while( nPos < aToken.getLength() ) + { + bool bOldEscape = bEscape; + bEscape = false; + if( '\\'==aToken[nPos] && !bOldEscape ) + { + aToken = aToken.replaceAt( nPos, 1, "" ); + bEscape = true; + } + else + { + nPos++; + } + } +} + +const HTMLOptions& HTMLParser::GetOptions( HtmlOptionId const *pNoConvertToken ) +{ + // If the options for the current token have already been returned, + // return them once again. + if (!maOptions.empty()) + return maOptions; + + sal_Int32 nPos = 0; + while( nPos < aToken.getLength() ) + { + // A letter? Option beginning here. + if( rtl::isAsciiAlpha( aToken[nPos] ) ) + { + HtmlOptionId nToken; + OUString aValue; + sal_Int32 nStt = nPos; + sal_Unicode cChar = 0; + + // Actually only certain characters allowed. + // Netscape only looks for "=" and white space (c.f. + // Mozilla: PA_FetchRequestedNameValues in libparse/pa_mdl.c) + while( nPos < aToken.getLength() ) + { + cChar = aToken[nPos]; + if ( '=' == cChar ||!HTML_ISPRINTABLE(cChar) || rtl::isAsciiWhiteSpace(cChar) ) + break; + nPos++; + } + + OUString sName( aToken.copy( nStt, nPos-nStt ) ); + + // PlugIns require original token name. Convert to lower case only for searching. + nToken = GetHTMLOption( sName.toAsciiLowerCase() ); // Name is ready + SAL_WARN_IF( nToken==HtmlOptionId::UNKNOWN, "svtools", + "GetOption: unknown HTML option '" << sName << "'" ); + bool bStripCRLF = (nToken < HtmlOptionId::SCRIPT_START || + nToken >= HtmlOptionId::SCRIPT_END) && + (!pNoConvertToken || nToken != *pNoConvertToken); + + while( nPos < aToken.getLength() ) + { + cChar = aToken[nPos]; + if ( HTML_ISPRINTABLE(cChar) && !rtl::isAsciiWhiteSpace(cChar) ) + break; + nPos++; + } + + // Option with value? + if( nPos!=aToken.getLength() && '='==cChar ) + { + nPos++; + + while( nPos < aToken.getLength() ) + { + cChar = aToken[nPos]; + if ( HTML_ISPRINTABLE(cChar) && ' ' != cChar && '\t' != cChar && '\r' != cChar && '\n' != cChar ) + break; + nPos++; + } + + if( nPos != aToken.getLength() ) + { + sal_Int32 nLen = 0; + nStt = nPos; + if( ('"'==cChar) || '\''==cChar ) + { + sal_Unicode cEnd = cChar; + nPos++; nStt++; + bool bDone = false; + bool bEscape = false; + while( nPos < aToken.getLength() && !bDone ) + { + bool bOldEscape = bEscape; + bEscape = false; + cChar = aToken[nPos]; + switch( cChar ) + { + case '\r': + case '\n': + if( bStripCRLF ) + aToken = aToken.replaceAt( nPos, 1, "" ); + else + { + nPos++; + nLen++; + } + break; + case '\\': + if( bOldEscape ) + { + nPos++; + nLen++; + } + else + { + aToken = aToken.replaceAt( nPos, 1, "" ); + bEscape = true; + } + break; + case '"': + case '\'': + bDone = !bOldEscape && cChar==cEnd; + if( !bDone ) + { + nPos++; + nLen++; + } + break; + default: + nPos++; + nLen++; + break; + } + } + if( nPos!=aToken.getLength() ) + nPos++; + } + else + { + // More liberal than the standard: allow all printable characters + bool bEscape = false; + bool bDone = false; + while( nPos < aToken.getLength() && !bDone ) + { + bool bOldEscape = bEscape; + bEscape = false; + sal_Unicode c = aToken[nPos]; + switch( c ) + { + case ' ': + bDone = !bOldEscape; + if( !bDone ) + { + nPos++; + nLen++; + } + break; + + case '\t': + case '\r': + case '\n': + bDone = true; + break; + + case '\\': + if( bOldEscape ) + { + nPos++; + nLen++; + } + else + { + aToken = aToken.replaceAt( nPos, 1, "" ); + bEscape = true; + } + break; + + default: + if( HTML_ISPRINTABLE( c ) ) + { + nPos++; + nLen++; + } + else + bDone = true; + break; + } + } + } + + if( nLen ) + aValue = aToken.copy( nStt, nLen ); + } + } + + // Token is known and can be saved + maOptions.emplace_back(nToken, sName, aValue); + + } + else + // Ignore white space and unexpected characters + nPos++; + } + + return maOptions; +} + +HtmlTokenId HTMLParser::FilterPRE( HtmlTokenId nToken ) +{ + switch( nToken ) + { + // in Netscape they only have impact in not empty paragraphs + case HtmlTokenId::PARABREAK_ON: + nToken = HtmlTokenId::LINEBREAK; + [[fallthrough]]; + case HtmlTokenId::LINEBREAK: + case HtmlTokenId::NEWPARA: + nPre_LinePos = 0; + if( bPre_IgnoreNewPara ) + nToken = HtmlTokenId::NONE; + break; + + case HtmlTokenId::TABCHAR: + { + sal_Int32 nSpaces = 8 - (nPre_LinePos % 8); + DBG_ASSERT( aToken.isEmpty(), "Why is the token not empty?" ); + if (aToken.getLength() < nSpaces) + { + using comphelper::string::padToLength; + OUStringBuffer aBuf(aToken); + aToken = padToLength(aBuf, nSpaces, ' ').makeStringAndClear(); + } + nPre_LinePos += nSpaces; + nToken = HtmlTokenId::TEXTTOKEN; + } + break; + // Keep those + case HtmlTokenId::TEXTTOKEN: + nPre_LinePos += aToken.getLength(); + break; + + case HtmlTokenId::SELECT_ON: + case HtmlTokenId::SELECT_OFF: + case HtmlTokenId::BODY_ON: + case HtmlTokenId::FORM_ON: + case HtmlTokenId::FORM_OFF: + case HtmlTokenId::INPUT: + case HtmlTokenId::OPTION: + case HtmlTokenId::TEXTAREA_ON: + case HtmlTokenId::TEXTAREA_OFF: + + case HtmlTokenId::IMAGE: + case HtmlTokenId::APPLET_ON: + case HtmlTokenId::APPLET_OFF: + case HtmlTokenId::PARAM: + case HtmlTokenId::EMBED: + + case HtmlTokenId::HEAD1_ON: + case HtmlTokenId::HEAD1_OFF: + case HtmlTokenId::HEAD2_ON: + case HtmlTokenId::HEAD2_OFF: + case HtmlTokenId::HEAD3_ON: + case HtmlTokenId::HEAD3_OFF: + case HtmlTokenId::HEAD4_ON: + case HtmlTokenId::HEAD4_OFF: + case HtmlTokenId::HEAD5_ON: + case HtmlTokenId::HEAD5_OFF: + case HtmlTokenId::HEAD6_ON: + case HtmlTokenId::HEAD6_OFF: + case HtmlTokenId::BLOCKQUOTE_ON: + case HtmlTokenId::BLOCKQUOTE_OFF: + case HtmlTokenId::ADDRESS_ON: + case HtmlTokenId::ADDRESS_OFF: + case HtmlTokenId::HORZRULE: + + case HtmlTokenId::CENTER_ON: + case HtmlTokenId::CENTER_OFF: + case HtmlTokenId::DIVISION_ON: + case HtmlTokenId::DIVISION_OFF: + + case HtmlTokenId::SCRIPT_ON: + case HtmlTokenId::SCRIPT_OFF: + case HtmlTokenId::RAWDATA: + + case HtmlTokenId::TABLE_ON: + case HtmlTokenId::TABLE_OFF: + case HtmlTokenId::CAPTION_ON: + case HtmlTokenId::CAPTION_OFF: + case HtmlTokenId::COLGROUP_ON: + case HtmlTokenId::COLGROUP_OFF: + case HtmlTokenId::COL_ON: + case HtmlTokenId::COL_OFF: + case HtmlTokenId::THEAD_ON: + case HtmlTokenId::THEAD_OFF: + case HtmlTokenId::TFOOT_ON: + case HtmlTokenId::TFOOT_OFF: + case HtmlTokenId::TBODY_ON: + case HtmlTokenId::TBODY_OFF: + case HtmlTokenId::TABLEROW_ON: + case HtmlTokenId::TABLEROW_OFF: + case HtmlTokenId::TABLEDATA_ON: + case HtmlTokenId::TABLEDATA_OFF: + case HtmlTokenId::TABLEHEADER_ON: + case HtmlTokenId::TABLEHEADER_OFF: + + case HtmlTokenId::ANCHOR_ON: + case HtmlTokenId::ANCHOR_OFF: + case HtmlTokenId::BOLD_ON: + case HtmlTokenId::BOLD_OFF: + case HtmlTokenId::ITALIC_ON: + case HtmlTokenId::ITALIC_OFF: + case HtmlTokenId::STRIKE_ON: + case HtmlTokenId::STRIKE_OFF: + case HtmlTokenId::STRIKETHROUGH_ON: + case HtmlTokenId::STRIKETHROUGH_OFF: + case HtmlTokenId::UNDERLINE_ON: + case HtmlTokenId::UNDERLINE_OFF: + case HtmlTokenId::BASEFONT_ON: + case HtmlTokenId::BASEFONT_OFF: + case HtmlTokenId::FONT_ON: + case HtmlTokenId::FONT_OFF: + case HtmlTokenId::BLINK_ON: + case HtmlTokenId::BLINK_OFF: + case HtmlTokenId::SPAN_ON: + case HtmlTokenId::SPAN_OFF: + case HtmlTokenId::SUBSCRIPT_ON: + case HtmlTokenId::SUBSCRIPT_OFF: + case HtmlTokenId::SUPERSCRIPT_ON: + case HtmlTokenId::SUPERSCRIPT_OFF: + case HtmlTokenId::BIGPRINT_ON: + case HtmlTokenId::BIGPRINT_OFF: + case HtmlTokenId::SMALLPRINT_OFF: + case HtmlTokenId::SMALLPRINT_ON: + + case HtmlTokenId::EMPHASIS_ON: + case HtmlTokenId::EMPHASIS_OFF: + case HtmlTokenId::CITIATION_ON: + case HtmlTokenId::CITIATION_OFF: + case HtmlTokenId::STRONG_ON: + case HtmlTokenId::STRONG_OFF: + case HtmlTokenId::CODE_ON: + case HtmlTokenId::CODE_OFF: + case HtmlTokenId::SAMPLE_ON: + case HtmlTokenId::SAMPLE_OFF: + case HtmlTokenId::KEYBOARD_ON: + case HtmlTokenId::KEYBOARD_OFF: + case HtmlTokenId::VARIABLE_ON: + case HtmlTokenId::VARIABLE_OFF: + case HtmlTokenId::DEFINSTANCE_ON: + case HtmlTokenId::DEFINSTANCE_OFF: + case HtmlTokenId::SHORTQUOTE_ON: + case HtmlTokenId::SHORTQUOTE_OFF: + case HtmlTokenId::LANGUAGE_ON: + case HtmlTokenId::LANGUAGE_OFF: + case HtmlTokenId::AUTHOR_ON: + case HtmlTokenId::AUTHOR_OFF: + case HtmlTokenId::PERSON_ON: + case HtmlTokenId::PERSON_OFF: + case HtmlTokenId::ACRONYM_ON: + case HtmlTokenId::ACRONYM_OFF: + case HtmlTokenId::ABBREVIATION_ON: + case HtmlTokenId::ABBREVIATION_OFF: + case HtmlTokenId::INSERTEDTEXT_ON: + case HtmlTokenId::INSERTEDTEXT_OFF: + case HtmlTokenId::DELETEDTEXT_ON: + case HtmlTokenId::DELETEDTEXT_OFF: + case HtmlTokenId::TELETYPE_ON: + case HtmlTokenId::TELETYPE_OFF: + + break; + + // The remainder is treated as an unknown token. + default: + if( nToken != HtmlTokenId::NONE ) + { + nToken = + ( ((nToken >= HtmlTokenId::ONOFF_START) && isOffToken(nToken)) + ? HtmlTokenId::UNKNOWNCONTROL_OFF + : HtmlTokenId::UNKNOWNCONTROL_ON ); + } + break; + } + + bPre_IgnoreNewPara = false; + + return nToken; +} + +HtmlTokenId HTMLParser::FilterXMP( HtmlTokenId nToken ) +{ + switch( nToken ) + { + case HtmlTokenId::NEWPARA: + if( bPre_IgnoreNewPara ) + nToken = HtmlTokenId::NONE; + [[fallthrough]]; + case HtmlTokenId::TEXTTOKEN: + case HtmlTokenId::NONBREAKSPACE: + case HtmlTokenId::SOFTHYPH: + break; // kept + + default: + if( nToken != HtmlTokenId::NONE ) + { + if( (nToken >= HtmlTokenId::ONOFF_START) && isOffToken(nToken) ) + { + sSaveToken = "</" + sSaveToken; + } + else + sSaveToken = "<" + sSaveToken; + if( !aToken.isEmpty() ) + { + UnescapeToken(); + sSaveToken += " "; + aToken = sSaveToken + aToken; + } + else + aToken = sSaveToken; + aToken += ">"; + nToken = HtmlTokenId::TEXTTOKEN; + } + break; + } + + bPre_IgnoreNewPara = false; + + return nToken; +} + +HtmlTokenId HTMLParser::FilterListing( HtmlTokenId nToken ) +{ + switch( nToken ) + { + case HtmlTokenId::NEWPARA: + if( bPre_IgnoreNewPara ) + nToken = HtmlTokenId::NONE; + [[fallthrough]]; + case HtmlTokenId::TEXTTOKEN: + case HtmlTokenId::NONBREAKSPACE: + case HtmlTokenId::SOFTHYPH: + break; // kept + + default: + if( nToken != HtmlTokenId::NONE ) + { + nToken = + ( ((nToken >= HtmlTokenId::ONOFF_START) && isOffToken(nToken)) + ? HtmlTokenId::UNKNOWNCONTROL_OFF + : HtmlTokenId::UNKNOWNCONTROL_ON ); + } + break; + } + + bPre_IgnoreNewPara = false; + + return nToken; +} + +bool HTMLParser::InternalImgToPrivateURL( OUString& rURL ) +{ + bool bFound = false; + + if( rURL.startsWith( OOO_STRING_SVTOOLS_HTML_internal_icon ) ) + { + OUString aName( rURL.copy(14) ); + switch( aName[0] ) + { + case 'b': + bFound = aName == OOO_STRING_SVTOOLS_HTML_INT_ICON_baddata; + break; + case 'd': + bFound = aName == OOO_STRING_SVTOOLS_HTML_INT_ICON_delayed; + break; + case 'e': + bFound = aName == OOO_STRING_SVTOOLS_HTML_INT_ICON_embed; + break; + case 'i': + bFound = aName == OOO_STRING_SVTOOLS_HTML_INT_ICON_insecure; + break; + case 'n': + bFound = aName == OOO_STRING_SVTOOLS_HTML_INT_ICON_notfound; + break; + } + } + if( bFound ) + { + OUString sTmp ( rURL ); + rURL = OOO_STRING_SVTOOLS_HTML_private_image; + rURL += sTmp; + } + + return bFound; +} + +namespace { + +enum class HtmlMeta { + NONE = 0, + Author, + Description, + Keywords, + Refresh, + Classification, + Created, + ChangedBy, + Changed, + Generator, + SDFootnote, + SDEndnote, + ContentType +}; + +} + +// <META NAME=xxx> +static HTMLOptionEnum<HtmlMeta> const aHTMLMetaNameTable[] = +{ + { OOO_STRING_SVTOOLS_HTML_META_author, HtmlMeta::Author }, + { OOO_STRING_SVTOOLS_HTML_META_changed, HtmlMeta::Changed }, + { OOO_STRING_SVTOOLS_HTML_META_changedby, HtmlMeta::ChangedBy }, + { OOO_STRING_SVTOOLS_HTML_META_classification,HtmlMeta::Classification}, + { OOO_STRING_SVTOOLS_HTML_META_content_type, HtmlMeta::ContentType }, + { OOO_STRING_SVTOOLS_HTML_META_created, HtmlMeta::Created }, + { OOO_STRING_SVTOOLS_HTML_META_description, HtmlMeta::Description }, + { OOO_STRING_SVTOOLS_HTML_META_keywords, HtmlMeta::Keywords }, + { OOO_STRING_SVTOOLS_HTML_META_generator, HtmlMeta::Generator }, + { OOO_STRING_SVTOOLS_HTML_META_refresh, HtmlMeta::Refresh }, + { OOO_STRING_SVTOOLS_HTML_META_sdendnote, HtmlMeta::SDEndnote }, + { OOO_STRING_SVTOOLS_HTML_META_sdfootnote, HtmlMeta::SDFootnote }, + { nullptr, HtmlMeta(0) } +}; + + +void HTMLParser::AddMetaUserDefined( OUString const & ) +{ +} + +bool HTMLParser::ParseMetaOptionsImpl( + const uno::Reference<document::XDocumentProperties> & i_xDocProps, + SvKeyValueIterator *i_pHTTPHeader, + const HTMLOptions& aOptions, + rtl_TextEncoding& o_rEnc ) +{ + OUString aName, aContent; + HtmlMeta nAction = HtmlMeta::NONE; + bool bHTTPEquiv = false, bChanged = false; + + for ( size_t i = aOptions.size(); i; ) + { + const HTMLOption& aOption = aOptions[--i]; + switch ( aOption.GetToken() ) + { + case HtmlOptionId::NAME: + aName = aOption.GetString(); + if ( HtmlMeta::NONE==nAction ) + { + aOption.GetEnum( nAction, aHTMLMetaNameTable ); + } + break; + case HtmlOptionId::HTTPEQUIV: + aName = aOption.GetString(); + aOption.GetEnum( nAction, aHTMLMetaNameTable ); + bHTTPEquiv = true; + break; + case HtmlOptionId::CONTENT: + aContent = aOption.GetString(); + break; + case HtmlOptionId::CHARSET: + { + OString sValue(OUStringToOString(aOption.GetString(), RTL_TEXTENCODING_ASCII_US)); + o_rEnc = GetExtendedCompatibilityTextEncoding(rtl_getTextEncodingFromMimeCharset(sValue.getStr())); + break; + } + default: break; + } + } + + if ( bHTTPEquiv || HtmlMeta::Description != nAction ) + { + // if it is not a Description, remove CRs and LFs from CONTENT + aContent = aContent.replaceAll("\r", "").replaceAll("\n", ""); + } + else + { + // convert line endings for Description + aContent = convertLineEnd(aContent, GetSystemLineEnd()); + } + + if ( bHTTPEquiv && i_pHTTPHeader ) + { + // Netscape seems to just ignore a closing ", so we do too + if ( aContent.endsWith("\"") ) + { + aContent = aContent.copy( 0, aContent.getLength() - 1 ); + } + SvKeyValue aKeyValue( aName, aContent ); + i_pHTTPHeader->Append( aKeyValue ); + } + + switch ( nAction ) + { + case HtmlMeta::Author: + if (i_xDocProps.is()) { + i_xDocProps->setAuthor( aContent ); + bChanged = true; + } + break; + case HtmlMeta::Description: + if (i_xDocProps.is()) { + i_xDocProps->setDescription( aContent ); + bChanged = true; + } + break; + case HtmlMeta::Keywords: + if (i_xDocProps.is()) { + i_xDocProps->setKeywords( + ::comphelper::string::convertCommaSeparated(aContent)); + bChanged = true; + } + break; + case HtmlMeta::Classification: + if (i_xDocProps.is()) { + i_xDocProps->setSubject( aContent ); + bChanged = true; + } + break; + + case HtmlMeta::ChangedBy: + if (i_xDocProps.is()) { + i_xDocProps->setModifiedBy( aContent ); + bChanged = true; + } + break; + + case HtmlMeta::Created: + case HtmlMeta::Changed: + if (i_xDocProps.is() && !aContent.isEmpty()) + { + ::util::DateTime uDT; + bool valid = false; + if (comphelper::string::getTokenCount(aContent, ';') == 2) + { + sal_Int32 nIdx{ 0 }; + Date aDate(aContent.getToken(0, ';', nIdx).toInt32()); + auto nTime = aContent.getToken(0, ';', nIdx).toInt64(); + if (nTime < 0) + nTime = o3tl::saturating_toggle_sign(nTime); + tools::Time aTime(nTime); + DateTime aDateTime(aDate, aTime); + uDT = aDateTime.GetUNODateTime(); + valid = true; + } + else if (utl::ISO8601parseDateTime(aContent, uDT)) + valid = true; + + if (valid) + { + bChanged = true; + if (HtmlMeta::Created == nAction) + i_xDocProps->setCreationDate(uDT); + else + i_xDocProps->setModificationDate(uDT); + } + } + break; + + case HtmlMeta::Refresh: + DBG_ASSERT( !bHTTPEquiv || i_pHTTPHeader, "Lost Reload-URL because of omitted MUST change." ); + break; + + case HtmlMeta::ContentType: + if ( !aContent.isEmpty() ) + { + o_rEnc = GetEncodingByMIME( aContent ); + } + break; + + case HtmlMeta::NONE: + if ( !bHTTPEquiv ) + { + if (i_xDocProps.is()) + { + uno::Reference<beans::XPropertyContainer> xUDProps + = i_xDocProps->getUserDefinedProperties(); + try { + xUDProps->addProperty(aName, + beans::PropertyAttribute::REMOVABLE, + uno::makeAny(aContent)); + AddMetaUserDefined(aName); + bChanged = true; + } catch (uno::Exception &) { + // ignore + } + } + } + break; + default: + break; + } + + return bChanged; +} + +bool HTMLParser::ParseMetaOptions( + const uno::Reference<document::XDocumentProperties> & i_xDocProps, + SvKeyValueIterator *i_pHeader ) +{ + HtmlOptionId nContentOption = HtmlOptionId::CONTENT; + rtl_TextEncoding eEnc = RTL_TEXTENCODING_DONTKNOW; + + bool bRet = ParseMetaOptionsImpl( i_xDocProps, i_pHeader, + GetOptions(&nContentOption), + eEnc ); + + // If the encoding is set by a META tag, it may only overwrite the + // current encoding if both, the current and the new encoding, are 1-sal_uInt8 + // encodings. Everything else cannot lead to reasonable results. + if (RTL_TEXTENCODING_DONTKNOW != eEnc && + rtl_isOctetTextEncoding( eEnc ) && + rtl_isOctetTextEncoding( GetSrcEncoding() ) ) + { + eEnc = GetExtendedCompatibilityTextEncoding( eEnc ); + SetSrcEncoding( eEnc ); + } + + return bRet; +} + +rtl_TextEncoding HTMLParser::GetEncodingByMIME( const OUString& rMime ) +{ + OUString sType; + OUString sSubType; + INetContentTypeParameterList aParameters; + if (INetContentTypes::parse(rMime, sType, sSubType, &aParameters)) + { + auto const iter = aParameters.find("charset"); + if (iter != aParameters.end()) + { + const INetContentTypeParameter * pCharset = &iter->second; + OString sValue(OUStringToOString(pCharset->m_sValue, RTL_TEXTENCODING_ASCII_US)); + return GetExtendedCompatibilityTextEncoding( rtl_getTextEncodingFromMimeCharset( sValue.getStr() ) ); + } + } + return RTL_TEXTENCODING_DONTKNOW; +} + +rtl_TextEncoding HTMLParser::GetEncodingByHttpHeader( SvKeyValueIterator *pHTTPHeader ) +{ + rtl_TextEncoding eRet = RTL_TEXTENCODING_DONTKNOW; + if( pHTTPHeader ) + { + SvKeyValue aKV; + for( bool bCont = pHTTPHeader->GetFirst( aKV ); bCont; + bCont = pHTTPHeader->GetNext( aKV ) ) + { + if( aKV.GetKey().equalsIgnoreAsciiCase( OOO_STRING_SVTOOLS_HTML_META_content_type ) ) + { + if( !aKV.GetValue().isEmpty() ) + { + eRet = HTMLParser::GetEncodingByMIME( aKV.GetValue() ); + } + } + } + } + return eRet; +} + +bool HTMLParser::SetEncodingByHTTPHeader( SvKeyValueIterator *pHTTPHeader ) +{ + bool bRet = false; + rtl_TextEncoding eEnc = HTMLParser::GetEncodingByHttpHeader( pHTTPHeader ); + if(RTL_TEXTENCODING_DONTKNOW != eEnc) + { + SetSrcEncoding( eEnc ); + bRet = true; + } + return bRet; +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/svrtf/parrtf.cxx b/svtools/source/svrtf/parrtf.cxx new file mode 100644 index 000000000..8b5ad0a0a --- /dev/null +++ b/svtools/source/svrtf/parrtf.cxx @@ -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 . + */ + +#include <sal/config.h> +#include <sal/log.hxx> + +#include <rtl/character.hxx> +#include <rtl/strbuf.hxx> +#include <rtl/tencinfo.h> +#include <rtl/ustrbuf.hxx> +#include <tools/stream.hxx> +#include <tools/debug.hxx> +#include <svtools/rtftoken.h> +#include <svtools/parrtf.hxx> + +const int MAX_STRING_LEN = 1024; +const int MAX_TOKEN_LEN = 128; + +#define RTF_ISDIGIT( c ) rtl::isAsciiDigit(c) +#define RTF_ISALPHA( c ) rtl::isAsciiAlpha(c) + +SvRTFParser::SvRTFParser( SvStream& rIn, sal_uInt8 nStackSize ) + : SvParser<int>( rIn, nStackSize ) + , nOpenBrakets(0) + , eCodeSet(RTL_TEXTENCODING_MS_1252) + , nUCharOverread(1) +{ + // default is ANSI-CodeSet + SetSrcEncoding( RTL_TEXTENCODING_MS_1252 ); + bRTF_InTextRead = false; +} + +SvRTFParser::~SvRTFParser() +{ +} + + +int SvRTFParser::GetNextToken_() +{ + int nRet = 0; + do { + bool bNextCh = true; + switch( nNextCh ) + { + case '\\': + { + // control characters + nNextCh = GetNextChar(); + switch( nNextCh ) + { + case '{': + case '}': + case '\\': + case '+': // I found it in a RTF-file + case '~': // nonbreaking space + case '-': // optional hyphen + case '_': // nonbreaking hyphen + case '\'': // HexValue + nNextCh = '\\'; + rInput.SeekRel( -1 ); + ScanText(); + nRet = RTF_TEXTTOKEN; + bNextCh = 0 == nNextCh; + break; + + case '*': // ignoreflag + nRet = RTF_IGNOREFLAG; + break; + case ':': // subentry in an index entry + nRet = RTF_SUBENTRYINDEX; + break; + case '|': // formula-character + nRet = RTF_FORMULA; + break; + + case 0x0a: + case 0x0d: + nRet = RTF_PAR; + break; + + default: + if( RTF_ISALPHA( nNextCh ) ) + { + aToken = "\\"; + { + OUStringBuffer aStrBuffer( MAX_TOKEN_LEN ); + do { + aStrBuffer.appendUtf32(nNextCh); + nNextCh = GetNextChar(); + } while( RTF_ISALPHA( nNextCh ) ); + aToken += aStrBuffer; + } + + // minus before numeric parameters + bool bNegValue = false; + if( '-' == nNextCh ) + { + bNegValue = true; + nNextCh = GetNextChar(); + } + + // possible numeric parameter + if( RTF_ISDIGIT( nNextCh ) ) + { + OUStringBuffer aNumber; + do { + aNumber.append(static_cast<sal_Unicode>(nNextCh)); + nNextCh = GetNextChar(); + } while( RTF_ISDIGIT( nNextCh ) ); + nTokenValue = aNumber.toString().toInt32(); + if( bNegValue ) + nTokenValue = -nTokenValue; + bTokenHasValue=true; + } + else if( bNegValue ) // restore minus + { + nNextCh = '-'; + rInput.SeekRel( -1 ); + } + if( ' ' == nNextCh ) // blank is part of token! + nNextCh = GetNextChar(); + + // search for the token in the table: + if( 0 == (nRet = GetRTFToken( aToken )) ) + // Unknown Control + nRet = RTF_UNKNOWNCONTROL; + + // bug 76812 - unicode token handled as normal text + bNextCh = false; + switch( nRet ) + { + case RTF_UC: + if( 0 <= nTokenValue ) + { + nUCharOverread = static_cast<sal_uInt8>(nTokenValue); + if (!aParserStates.empty()) + { + //cmc: other ifdef breaks #i3584 + aParserStates.top().nUCharOverread = nUCharOverread; + } + } + aToken.clear(); // #i47831# erase token to prevent the token from being treated as text + // read next token + nRet = 0; + break; + + case RTF_UPR: + if (!_inSkipGroup) { + // UPR - overread the group with the ansi + // information + int nNextToken; + do + { + nNextToken = GetNextToken_(); + } + while (nNextToken != '{' && nNextToken != sal_Unicode(EOF)); + + SkipGroup(); + GetNextToken_(); // overread the last bracket + nRet = 0; + } + break; + + case RTF_U: + if( !bRTF_InTextRead ) + { + nRet = RTF_TEXTTOKEN; + aToken = OUString( static_cast<sal_Unicode>(nTokenValue) ); + + // overread the next n "RTF" characters. This + // can be also \{, \}, \'88 + for( sal_uInt8 m = 0; m < nUCharOverread; ++m ) + { + sal_uInt32 cAnsi = nNextCh; + while( 0xD == cAnsi ) + cAnsi = GetNextChar(); + while( 0xA == cAnsi ) + cAnsi = GetNextChar(); + + if( '\\' == cAnsi && + '\'' == GetNextChar() ) + // skip HexValue + GetHexValue(); + nNextCh = GetNextChar(); + } + ScanText(); + bNextCh = 0 == nNextCh; + } + break; + } + } + else if( SvParserState::Pending != eState ) + { + // Bug 34631 - "\ " read on - Blank as character + // eState = SvParserState::Error; + bNextCh = false; + } + break; + } + } + break; + + case sal_Unicode(EOF): + eState = SvParserState::Accepted; + nRet = nNextCh; + break; + + case '{': + { + if( 0 <= nOpenBrakets ) + { + RtfParserState_Impl aState( nUCharOverread, GetSrcEncoding() ); + aParserStates.push( aState ); + } + ++nOpenBrakets; + DBG_ASSERT( + static_cast<size_t>(nOpenBrakets) == aParserStates.size(), + "ParserStateStack unequal to bracket count" ); + nRet = nNextCh; + } + break; + + case '}': + --nOpenBrakets; + if( 0 <= nOpenBrakets ) + { + aParserStates.pop(); + if( !aParserStates.empty() ) + { + const RtfParserState_Impl& rRPS = + aParserStates.top(); + nUCharOverread = rRPS.nUCharOverread; + SetSrcEncoding( rRPS.eCodeSet ); + } + else + { + nUCharOverread = 1; + SetSrcEncoding( GetCodeSet() ); + } + } + DBG_ASSERT( + static_cast<size_t>(nOpenBrakets) == aParserStates.size(), + "ParserStateStack unequal to bracket count" ); + nRet = nNextCh; + break; + + case 0x0d: + case 0x0a: + break; + + default: + // now normal text follows + ScanText(); + nRet = RTF_TEXTTOKEN; + bNextCh = 0 == nNextCh; + break; + } + + if( bNextCh ) + nNextCh = GetNextChar(); + + } while( !nRet && SvParserState::Working == eState ); + return nRet; +} + + +sal_Unicode SvRTFParser::GetHexValue() +{ + // collect Hex values + int n; + sal_Unicode nHexVal = 0; + + for( n = 0; n < 2; ++n ) + { + nHexVal *= 16; + nNextCh = GetNextChar(); + if( nNextCh >= '0' && nNextCh <= '9' ) + nHexVal += (nNextCh - 48); + else if( nNextCh >= 'a' && nNextCh <= 'f' ) + nHexVal += (nNextCh - 87); + else if( nNextCh >= 'A' && nNextCh <= 'F' ) + nHexVal += (nNextCh - 55); + } + return nHexVal; +} + +void SvRTFParser::ScanText() +{ + const sal_Unicode cBreak = 0; + OUStringBuffer aStrBuffer; + bool bContinue = true; + while( bContinue && IsParserWorking() && aStrBuffer.getLength() < MAX_STRING_LEN) + { + bool bNextCh = true; + switch( nNextCh ) + { + case '\\': + { + nNextCh = GetNextChar(); + switch (nNextCh) + { + case '\'': + { + + OStringBuffer aByteString; + while (true) + { + char c = static_cast<char>(GetHexValue()); + /* + * Note: \'00 is a valid internal character in a + * string in RTF. OStringBuffer supports + * appending nulls fine + */ + aByteString.append(c); + + bool bBreak = false; + bool bEOF = false; + char nSlash = '\\'; + while (!bBreak) + { + auto next = GetNextChar(); + if (sal_Unicode(EOF) == next) + { + bEOF = true; + break; + } + if (next>0xFF) // fix for #i43933# and #i35653# + { + if (!aByteString.isEmpty()) + aStrBuffer.append( OStringToOUString(aByteString.makeStringAndClear(), GetSrcEncoding()) ); + aStrBuffer.append(static_cast<sal_Unicode>(next)); + + continue; + } + nSlash = static_cast<char>(next); + while (nSlash == 0xD || nSlash == 0xA) + nSlash = static_cast<char>(GetNextChar()); + + switch (nSlash) + { + case '{': + case '}': + case '\\': + bBreak = true; + break; + default: + aByteString.append(nSlash); + break; + } + } + + if (bEOF) + { + bContinue = false; // abort, string together + break; + } + + nNextCh = GetNextChar(); + + if (nSlash != '\\' || nNextCh != '\'') + { + rInput.SeekRel(-1); + nNextCh = static_cast<unsigned char>(nSlash); + break; + } + } + + bNextCh = false; + + if (!aByteString.isEmpty()) + aStrBuffer.append( OStringToOUString(aByteString.makeStringAndClear(), GetSrcEncoding()) ); + } + break; + case '\\': + case '}': + case '{': + case '+': // I found in a RTF file + aStrBuffer.append(sal_Unicode(nNextCh)); + break; + case '~': // nonbreaking space + aStrBuffer.append(u'\x00A0'); + break; + case '-': // optional hyphen + aStrBuffer.append(u'\x00AD'); + break; + case '_': // nonbreaking hyphen + aStrBuffer.append(u'\x2011'); + break; + + case 'u': + // read UNI-Code characters + { + nNextCh = GetNextChar(); + rInput.SeekRel( -2 ); + + if( '-' == nNextCh || RTF_ISDIGIT( nNextCh ) ) + { + bRTF_InTextRead = true; + + OUString sSave( aToken ); + nNextCh = '\\'; + int nToken = GetNextToken_(); + DBG_ASSERT( RTF_U == nToken, "still not a UNI-Code character" ); + // don't convert symbol chars + aStrBuffer.append(static_cast< sal_Unicode >(nTokenValue)); + + // overread the next n "RTF" characters. This + // can be also \{, \}, \'88 + for( sal_uInt8 m = 0; m < nUCharOverread; ++m ) + { + sal_Unicode cAnsi = nNextCh; + while( 0xD == cAnsi ) + cAnsi = GetNextChar(); + while( 0xA == cAnsi ) + cAnsi = GetNextChar(); + + if( '\\' == cAnsi && + '\'' == GetNextChar() ) + // skip HexValue + GetHexValue(); + nNextCh = GetNextChar(); + } + bNextCh = false; + aToken = sSave; + bRTF_InTextRead = false; + } + else if ( 'c' == nNextCh ) + { + // Prevent text breaking into multiple tokens. + rInput.SeekRel( 2 ); + nNextCh = GetNextChar(); + if (RTF_ISDIGIT( nNextCh )) + { + sal_uInt8 nNewOverread = 0 ; + do { + nNewOverread *= 10; + nNewOverread += nNextCh - '0'; + nNextCh = GetNextChar(); + } while ( RTF_ISDIGIT( nNextCh ) ); + nUCharOverread = nNewOverread; + if (!aParserStates.empty()) + aParserStates.top().nUCharOverread = nNewOverread; + } + bNextCh = 0x20 == nNextCh; + } + else + { + nNextCh = '\\'; + bContinue = false; // abort, string together + } + } + break; + + default: + rInput.SeekRel( -1 ); + nNextCh = '\\'; + bContinue = false; // abort, string together + break; + } + } + break; + + case sal_Unicode(EOF): + eState = SvParserState::Error; + [[fallthrough]]; + case '{': + case '}': + bContinue = false; + break; + + case 0x0a: + case 0x0d: + break; + + default: + if( nNextCh == cBreak || aStrBuffer.getLength() >= MAX_STRING_LEN) + bContinue = false; + else + { + do { + // all other characters end up in the text + aStrBuffer.appendUtf32(nNextCh); + + if (sal_Unicode(EOF) == (nNextCh = GetNextChar())) + { + if (!aStrBuffer.isEmpty()) + aToken += aStrBuffer; + return; + } + } while + ( + (RTF_ISALPHA(nNextCh) || RTF_ISDIGIT(nNextCh)) && + (aStrBuffer.getLength() < MAX_STRING_LEN) + ); + bNextCh = false; + } + } + + if( bContinue && bNextCh ) + nNextCh = GetNextChar(); + } + + if (!aStrBuffer.isEmpty()) + aToken += aStrBuffer; +} + + +short SvRTFParser::_inSkipGroup=0; + +void SvRTFParser::SkipGroup() +{ + short nBrackets=1; + if (_inSkipGroup>0) + return; + _inSkipGroup++; +//#i16185# faking \bin keyword + do + { + switch (nNextCh) + { + case '{': + ++nBrackets; + break; + case '}': + if (!--nBrackets) { + _inSkipGroup--; + return; + } + break; + } + int nToken = GetNextToken_(); + if (nToken == RTF_BIN) + { + rInput.SeekRel(-1); + SAL_WARN_IF(nTokenValue < 0, "svtools", "negative value argument for rtf \\bin keyword"); + if (nTokenValue > 0) + rInput.SeekRel(nTokenValue); + nNextCh = GetNextChar(); + } + while (nNextCh==0xa || nNextCh==0xd) + { + nNextCh = GetNextChar(); + } + } while (sal_Unicode(EOF) != nNextCh && IsParserWorking()); + + if( SvParserState::Pending != eState && '}' != nNextCh ) + eState = SvParserState::Error; + _inSkipGroup--; +} + +void SvRTFParser::ReadUnknownData() { SkipGroup(); } +void SvRTFParser::ReadBitmapData() { SkipGroup(); } + + +SvParserState SvRTFParser::CallParser() +{ + char cFirstCh; + nNextChPos = rInput.Tell(); + rInput.ReadChar( cFirstCh ); + nNextCh = static_cast<unsigned char>(cFirstCh); + eState = SvParserState::Working; + nOpenBrakets = 0; + eCodeSet = RTL_TEXTENCODING_MS_1252; + SetSrcEncoding( eCodeSet ); + + // the first two tokens should be '{' and \\rtf !! + if( '{' == GetNextToken() && RTF_RTF == GetNextToken() ) + { + AddFirstRef(); + Continue( 0 ); + if( SvParserState::Pending != eState ) + ReleaseRef(); // now parser is not needed anymore + } + else + eState = SvParserState::Error; + + return eState; +} + +void SvRTFParser::Continue( int nToken ) +{ +// DBG_ASSERT( SVPAR_CS_DONTKNOW == GetCharSet(), +// "Characterset was changed." ); + + if( !nToken ) + nToken = GetNextToken(); + + bool bLooping = false; + + while (IsParserWorking() && !bLooping) + { + auto nCurrentTokenIndex = m_nTokenIndex; + auto nCurrentToken = nToken; + + SaveState( nToken ); + switch( nToken ) + { + case '}': + if( nOpenBrakets ) + goto NEXTTOKEN; + eState = SvParserState::Accepted; + break; + + case '{': + // an unknown group ? + { + if( RTF_IGNOREFLAG != GetNextToken() ) + nToken = SkipToken(); + else if( RTF_UNKNOWNCONTROL != GetNextToken() ) + nToken = SkipToken( -2 ); + else + { + // filter immediately + ReadUnknownData(); + nToken = GetNextToken(); + if( '}' != nToken ) + eState = SvParserState::Error; + break; // move to next token!! + } + } + goto NEXTTOKEN; + + case RTF_UNKNOWNCONTROL: + break; // skip unknown token + case RTF_NEXTTYPE: + case RTF_ANSITYPE: + eCodeSet = RTL_TEXTENCODING_MS_1252; + SetSrcEncoding( eCodeSet ); + break; + case RTF_MACTYPE: + eCodeSet = RTL_TEXTENCODING_APPLE_ROMAN; + SetSrcEncoding( eCodeSet ); + break; + case RTF_PCTYPE: + eCodeSet = RTL_TEXTENCODING_IBM_437; + SetSrcEncoding( eCodeSet ); + break; + case RTF_PCATYPE: + eCodeSet = RTL_TEXTENCODING_IBM_850; + SetSrcEncoding( eCodeSet ); + break; + case RTF_ANSICPG: + eCodeSet = rtl_getTextEncodingFromWindowsCodePage(nTokenValue); + SetSrcEncoding(eCodeSet); + break; + default: +NEXTTOKEN: + NextToken( nToken ); + break; + } + if( IsParserWorking() ) + SaveState( 0 ); // processed till here, + // continue with new token! + nToken = GetNextToken(); + bLooping = nCurrentTokenIndex == m_nTokenIndex && nToken == nCurrentToken; + } + if( SvParserState::Accepted == eState && 0 < nOpenBrakets ) + eState = SvParserState::Error; +} + +void SvRTFParser::SetEncoding( rtl_TextEncoding eEnc ) +{ + if (eEnc == RTL_TEXTENCODING_DONTKNOW) + eEnc = GetCodeSet(); + + if (!aParserStates.empty()) + aParserStates.top().eCodeSet = eEnc; + SetSrcEncoding(eEnc); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/svrtf/rtfkeywd.cxx b/svtools/source/svrtf/rtfkeywd.cxx new file mode 100644 index 000000000..410aa5d37 --- /dev/null +++ b/svtools/source/svrtf/rtfkeywd.cxx @@ -0,0 +1,1201 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <rtl/ustring.hxx> +#include <svtools/rtfkeywd.hxx> +#include <svtools/rtftoken.h> + +#include <algorithm> +#include <string.h> + +namespace { + +// the table is still to be sorted +struct RTF_TokenEntry +{ + OUStringLiteral sToken; + int nToken; +}; + +} + +// Flag: RTF-token table has been sorted +static bool bSortKeyWords = false; + +static RTF_TokenEntry aRTFTokenTab[] = { +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_IGNORE), RTF_IGNOREFLAG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_RTF), RTF_RTF}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ANSI), RTF_ANSITYPE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_MAC), RTF_MACTYPE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PC), RTF_PCTYPE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PCA), RTF_PCATYPE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_NEXTCSET), RTF_NEXTTYPE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_STYLESHEET), RTF_STYLESHEET}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SBASEDON), RTF_SBASEDON}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SNEXT), RTF_SNEXT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FONTTBL), RTF_FONTTBL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DEFF), RTF_DEFF}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FNIL), RTF_FNIL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FROMAN), RTF_FROMAN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FSWISS), RTF_FSWISS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FMODERN), RTF_FMODERN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FSCRIPT), RTF_FSCRIPT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FDECOR), RTF_FDECOR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTECH), RTF_FTECH}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FCHARSET), RTF_FCHARSET}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FALT), RTF_FALT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FPRQ), RTF_FPRQ}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_COLORTBL), RTF_COLORTBL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_RED), RTF_RED}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_GREEN), RTF_GREEN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BLUE), RTF_BLUE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CF), RTF_CF}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CB), RTF_CB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_INFO), RTF_INFO}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TITLE), RTF_TITLE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SUBJECT), RTF_SUBJECT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AUTHOR), RTF_AUTHOR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OPERATOR), RTF_OPERATOR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_KEYWORDS), RTF_KEYWORDS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_COMMENT), RTF_COMMENT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_VERSION), RTF_VERSION}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DOCCOMM), RTF_DOCCOMM}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_VERN), RTF_VERN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CREATIM), RTF_CREATIM}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_REVTIM), RTF_REVTIM}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PRINTIM), RTF_PRINTIM}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BUPTIM), RTF_BUPTIM}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_EDMINS), RTF_EDMINS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_NOFPAGES), RTF_NOFPAGES}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_NOFWORDS), RTF_NOFWORDS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_NOFCHARS), RTF_NOFCHARS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ID), RTF_ID}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_YR), RTF_YR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_MO), RTF_MO}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DY), RTF_DY}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_HR), RTF_HR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_MIN), RTF_MIN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ANNOTATION), RTF_ANNOTATION}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ATNID), RTF_ATNID}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FOOTNOTE), RTF_FOOTNOTE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FOOTER), RTF_FOOTER}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FOOTERL), RTF_FOOTERL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FOOTERR), RTF_FOOTERR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FOOTERF), RTF_FOOTERF}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_HEADER), RTF_HEADER}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_HEADERL), RTF_HEADERL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_HEADERR), RTF_HEADERR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_HEADERF), RTF_HEADERF}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_XE), RTF_XE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BXE), RTF_BXE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_IXE), RTF_IXE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_RXE), RTF_RXE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TXE), RTF_TXE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TC), RTF_TC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TCF), RTF_TCF}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TCL), RTF_TCL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BKMKSTART), RTF_BKMKSTART}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BKMKEND), RTF_BKMKEND}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PICT), RTF_PICT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PICW), RTF_PICW}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PICH), RTF_PICH}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_WBMBITSPIXEL), RTF_WBMBITSPIXEL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_WBMPLANES), RTF_WBMPLANES}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_WBMWIDTHBYTES), RTF_WBMWIDTHBYTES}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PICWGOAL), RTF_PICWGOAL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PICHGOAL), RTF_PICHGOAL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BIN), RTF_BIN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PICSCALEX), RTF_PICSCALEX}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PICSCALEY), RTF_PICSCALEY}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PICSCALED), RTF_PICSCALED}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_WBITMAP), RTF_WBITMAP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_WMETAFILE), RTF_WMETAFILE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_MACPICT), RTF_MACPICT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PICCROPT), RTF_PICCROPT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PICCROPB), RTF_PICCROPB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PICCROPL), RTF_PICCROPL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PICCROPR), RTF_PICCROPR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FIELD), RTF_FIELD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FLDDIRTY), RTF_FLDDIRTY}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FLDEDIT), RTF_FLDEDIT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FLDLOCK), RTF_FLDLOCK}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FLDPRIV), RTF_FLDPRIV}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FLDINST), RTF_FLDINST}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FLDRSLT), RTF_FLDRSLT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PAPERW), RTF_PAPERW}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PAPERH), RTF_PAPERH}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_MARGL), RTF_MARGL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_MARGR), RTF_MARGR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_MARGT), RTF_MARGT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_MARGB), RTF_MARGB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FACINGP), RTF_FACINGP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_GUTTER), RTF_GUTTER}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DEFTAB), RTF_DEFTAB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_WIDOWCTRL), RTF_WIDOWCTRL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_HYPHHOTZ), RTF_HYPHHOTZ}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNSEP), RTF_FTNSEP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNSEPC), RTF_FTNSEPC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNCN), RTF_FTNCN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ENDNOTES), RTF_ENDNOTES}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ENDDOC), RTF_ENDDOC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNTJ), RTF_FTNTJ}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNBJ), RTF_FTNBJ}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNSTART), RTF_FTNSTART}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNRESTART), RTF_FTNRESTART}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGNSTART), RTF_PGNSTART}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LINESTART), RTF_LINESTART}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LANDSCAPE), RTF_LANDSCAPE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FRACWIDTH), RTF_FRACWIDTH}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_NEXTFILE), RTF_NEXTFILE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TEMPLATE), RTF_TEMPLATE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_MAKEBACKUP), RTF_MAKEBACKUP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DEFFORMAT), RTF_DEFFORMAT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_REVISIONS), RTF_REVISIONS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_MARGMIRROR), RTF_MARGMIRROR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_REVPROP), RTF_REVPROP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_REVBAR), RTF_REVBAR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SECTD), RTF_SECTD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SBKNONE), RTF_SBKNONE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SBKCOL), RTF_SBKCOL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SBKPAGE), RTF_SBKPAGE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SBKEVEN), RTF_SBKEVEN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SBKODD), RTF_SBKODD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGNSTARTS), RTF_PGNSTARTS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGNCONT), RTF_PGNCONT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGNRESTART), RTF_PGNRESTART}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGNDEC), RTF_PGNDEC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGNUCRM), RTF_PGNUCRM}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGNLCRM), RTF_PGNLCRM}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGNUCLTR), RTF_PGNUCLTR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGNLCLTR), RTF_PGNLCLTR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGNX), RTF_PGNX}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGNY), RTF_PGNY}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_HEADERY), RTF_HEADERY}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FOOTERY), RTF_FOOTERY}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LINEMOD), RTF_LINEMOD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LINEX), RTF_LINEX}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LINESTARTS), RTF_LINESTARTS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LINERESTART), RTF_LINERESTART}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LINEPPAGE), RTF_LINEPAGE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LINECONT), RTF_LINECONT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_VERTALT), RTF_VERTALT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_VERTALB), RTF_VERTALB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_VERTALC), RTF_VERTALC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_VERTALJ), RTF_VERTALJ}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_COLS), RTF_COLS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_COLSX), RTF_COLSX}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_COLNO), RTF_COLNO}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_COLSR), RTF_COLSR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_COLW), RTF_COLW}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LINEBETCOL), RTF_LINEBETCOL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ENDNHERE), RTF_ENDNHERE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TITLEPG), RTF_TITLEPG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PARD), RTF_PARD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_S), RTF_S}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_QL), RTF_QL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_QR), RTF_QR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_QJ), RTF_QJ}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_QC), RTF_QC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FI), RTF_FI}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LI), RTF_LI}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LIN), RTF_LIN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_RI), RTF_RI}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_RIN), RTF_RIN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SB), RTF_SB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SA), RTF_SA}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SL), RTF_SL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_INTBL), RTF_INTBL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_KEEP), RTF_KEEP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_KEEPN), RTF_KEEPN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LEVEL), RTF_LEVEL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SBYS), RTF_SBYS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PAGEBB), RTF_PAGEBB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_NOLINE), RTF_NOLINE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TX), RTF_TX}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TQL), RTF_TQL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TQR), RTF_TQR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TQC), RTF_TQC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TQDEC), RTF_TQDEC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TB), RTF_TB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRT), RTF_BRDRT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRB), RTF_BRDRB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRL), RTF_BRDRL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRR), RTF_BRDRR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BOX), RTF_BOX}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRS), RTF_BRDRS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRTH), RTF_BRDRTH}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRSH), RTF_BRDRSH}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRDB), RTF_BRDRDB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRDOT), RTF_BRDRDOT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRHAIR), RTF_BRDRHAIR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRSP), RTF_BRSP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TLDOT), RTF_TLDOT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TLHYPH), RTF_TLHYPH}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TLUL), RTF_TLUL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TLTH), RTF_TLTH}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_POSX), RTF_POSX}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_POSXC), RTF_POSXC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_POSXI), RTF_POSXI}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_POSXL), RTF_POSXL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_POSXO), RTF_POSXO}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_POSXR), RTF_POSXR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_POSY), RTF_POSY}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_POSYIL), RTF_POSYIL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_POSYT), RTF_POSYT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_POSYC), RTF_POSYC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_POSYB), RTF_POSYB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ABSW), RTF_ABSW}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DXFRTEXT), RTF_DXFRTEXT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PVMRG), RTF_PVMRG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PVPG), RTF_PVPG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PHMRG), RTF_PHMRG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PHPG), RTF_PHPG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PHCOL), RTF_PHCOL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLBRDRB), RTF_CLBRDRB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLBRDRT), RTF_CLBRDRT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLBRDRL), RTF_CLBRDRL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLBRDRR), RTF_CLBRDRR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLPADL), RTF_CLPADL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLPADT), RTF_CLPADT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLPADB), RTF_CLPADB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLPADR), RTF_CLPADR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLPADFL), RTF_CLPADFL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLPADFT), RTF_CLPADFT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLPADFB), RTF_CLPADFB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLPADFR), RTF_CLPADFR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TROWD), RTF_TROWD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TRQL), RTF_TRQL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TRQR), RTF_TRQR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TRQC), RTF_TRQC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TRGAPH), RTF_TRGAPH}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TRRH), RTF_TRRH}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TRLEFT), RTF_TRLEFT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CELLX), RTF_CELLX}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLMGF), RTF_CLMGF}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLMRG), RTF_CLMRG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PLAIN), RTF_PLAIN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_B), RTF_B}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_I), RTF_I}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_STRIKE), RTF_STRIKE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OUTL), RTF_OUTL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHAD), RTF_SHAD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SCAPS), RTF_SCAPS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CAPS), RTF_CAPS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_V), RTF_V}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_F), RTF_F}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FS), RTF_FS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_EXPND), RTF_EXPND}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_EXPNDTW), RTF_EXPNDTW}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_KERNING), RTF_KERNING}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_UL), RTF_UL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ULW), RTF_ULW}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ULD), RTF_ULD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ULDB), RTF_ULDB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ULNONE), RTF_ULNONE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_UP), RTF_UP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DN), RTF_DN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_REVISED), RTF_REVISED}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SUB), RTF_SUB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_NOSUPERSUB), RTF_NOSUPERSUB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SUPER), RTF_SUPER}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CHDATE), RTF_CHDATE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CHTIME), RTF_CHTIME}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CHPGN), RTF_CHPGN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CHFTN), RTF_CHFTN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CHATN), RTF_CHATN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CHFTNSEP), RTF_CHFTNSEP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CHFTNSEPC), RTF_CHFTNSEPC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FORMULA), RTF_FORMULA}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_NOBREAK), RTF_NONBREAKINGSPACE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OPTHYPH), RTF_OPTIONALHYPHEN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_NOBRKHYPH), RTF_NONBREAKINGHYPHEN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_HEXCHAR), RTF_HEX}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CELL), RTF_CELL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ROW), RTF_ROW}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PAR), RTF_PAR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SECT), RTF_SECT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PAGE), RTF_PAGE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_COLUMN), RTF_COLUM}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LINE), RTF_LINE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TAB), RTF_TAB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SUBENTRY), RTF_SUBENTRYINDEX}, + +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DEFLANG), RTF_DEFLANG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LANG), RTF_LANG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PMMETAFILE), RTF_OSMETAFILE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DIBITMAP), RTF_DIBITMAP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_KEYCODE), RTF_KEYCODE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FN), RTF_FNKEY}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ALT), RTF_ALTKEY}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHIFT), RTF_SHIFTKEY}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CTRL), RTF_CTRLKEY}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CHDPL), RTF_CHDATEL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CHDPA), RTF_CHDATEA}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_EMDASH), RTF_EMDASH}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ENDASH), RTF_ENDASH}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BULLET), RTF_BULLET}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LQUOTE), RTF_LQUOTE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_RQUOTE), RTF_RQUOTE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LDBLQUOTE), RTF_LDBLQUOTE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_RDBLQUOTE), RTF_RDBLQUOTE}, + +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BKMKCOLF), RTF_BKMKCOLF}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BKMKCOLL), RTF_BKMKCOLL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PSOVER), RTF_PSOVER}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DOCTEMP), RTF_DOCTEMP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BINFSXN), RTF_BINFSXN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BINSXN), RTF_BINSXN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGWSXN), RTF_PGWSXN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGHSXN), RTF_PGHSXN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_MARGLSXN), RTF_MARGLSXN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_MARGRSXN), RTF_MARGRSXN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_MARGTSXN), RTF_MARGTSXN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_MARGBSXN), RTF_MARGBSXN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_GUTTERSXN), RTF_GUTTERSXN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LNDSCPSXN), RTF_LNDSCPSXN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FACPGSXN), RTF_FACPGSXN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TLEQ), RTF_TLEQ}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRBTW), RTF_BRDRBTW}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRBAR), RTF_BRDRBAR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRW), RTF_BRDRW}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRCF), RTF_BRDRCF}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ABSH), RTF_ABSH}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PVPARA), RTF_PVPARA}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_NOWRAP), RTF_NOWRAP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DFRMTXTX), RTF_DFRMTXTX}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DFRMTXTY), RTF_DFRMTXTY}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DROPCAPLI), RTF_DROPCAPLI}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DROPCAPT), RTF_DROPCAPT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ABSNOOVRLP), RTF_ABSNOOVRLP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_POSNEGX), RTF_POSNEGX}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_POSNEGY), RTF_POSNEGY}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DELETED), RTF_DELETED}, + +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHADING), RTF_SHADING}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BGHORIZ), RTF_BGHORIZ}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BGVERT), RTF_BGVERT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BGFDIAG), RTF_BGFDIAG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BGBDIAG), RTF_BGBDIAG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BGCROSS), RTF_BGCROSS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BGDCROSS), RTF_BGDCROSS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BGDKHORIZ), RTF_BGDKHORIZ}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BGDKVERT), RTF_BGDKVERT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BGDKFDIAG), RTF_BGDKFDIAG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BGDKBDIAG), RTF_BGDKBDIAG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BGDKCROSS), RTF_BGDKCROSS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BGDKDCROSS), RTF_BGDKDCROSS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CFPAT), RTF_CFPAT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CBPAT), RTF_CBPAT}, + +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLSHDNG), RTF_CLSHDNG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLBGHORIZ), RTF_CLBGHORIZ}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLBGVERT), RTF_CLBGVERT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLBGFDIAG), RTF_CLBGFDIAG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLBGBDIAG), RTF_CLBGBDIAG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLBGCROSS), RTF_CLBGCROSS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLBGDCROSS), RTF_CLBGDCROSS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLBGDKHOR), RTF_CLBGDKHOR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLBGDKVERT), RTF_CLBGDKVERT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLBGDKFDIAG), RTF_CLBGDKFDIAG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLBGDKBDIAG), RTF_CLBGDKBDIAG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLBGDKCROSS), RTF_CLBGDKCROSS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLBGDKDCROSS), RTF_CLBGDKDCROSS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLCFPAT), RTF_CLCFPAT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLCBPAT), RTF_CLCBPAT}, + +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AB), RTF_AB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ACAPS), RTF_ACAPS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ACF), RTF_ACF}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ADDITIVE), RTF_ADDITIVE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ADN), RTF_ADN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AENDDOC), RTF_AENDDOC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AENDNOTES), RTF_AENDNOTES}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AEXPND), RTF_AEXPND}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AF), RTF_AF}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AFS), RTF_AFS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AFTNBJ), RTF_AFTNBJ}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AFTNCN), RTF_AFTNCN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AFTNNALC), RTF_AFTNNALC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AFTNNAR), RTF_AFTNNAR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AFTNNAUC), RTF_AFTNNAUC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AFTNNCHI), RTF_AFTNNCHI}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AFTNNRLC), RTF_AFTNNRLC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AFTNNRUC), RTF_AFTNNRUC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AFTNRESTART), RTF_AFTNRESTART}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AFTNRSTCONT), RTF_AFTNRSTCONT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AFTNSEP), RTF_AFTNSEP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AFTNSEPC), RTF_AFTNSEPC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AFTNSTART), RTF_AFTNSTART}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AFTNTJ), RTF_AFTNTJ}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AI), RTF_AI}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ALANG), RTF_ALANG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ALLPROT), RTF_ALLPROT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ANNOTPROT), RTF_ANNOTPROT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AOUTL), RTF_AOUTL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ASCAPS), RTF_ASCAPS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ASHAD), RTF_ASHAD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ASTRIKE), RTF_ASTRIKE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ATNAUTHOR), RTF_ATNAUTHOR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ATNICN), RTF_ATNICN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ATNREF), RTF_ATNREF}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ATNTIME), RTF_ATNTIME}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ATRFEND), RTF_ATRFEND}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ATRFSTART), RTF_ATRFSTART}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AUL), RTF_AUL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AULD), RTF_AULD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AULDB), RTF_AULDB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AULNONE), RTF_AULNONE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AULW), RTF_AULW}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AUP), RTF_AUP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BKMKPUB), RTF_BKMKPUB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRDASH), RTF_BRDRDASH}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRKFRM), RTF_BRKFRM}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CCHS), RTF_CCHS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CPG), RTF_CPG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CS), RTF_CS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CVMME), RTF_CVMME}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DATAFIELD), RTF_DATAFIELD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DO), RTF_DO}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DOBXCOLUMN), RTF_DOBXCOLUMN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DOBXMARGIN), RTF_DOBXMARGIN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DOBXPAGE), RTF_DOBXPAGE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DOBYMARGIN), RTF_DOBYMARGIN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DOBYPAGE), RTF_DOBYPAGE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DOBYPARA), RTF_DOBYPARA}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DODHGT), RTF_DODHGT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DOLOCK), RTF_DOLOCK}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPAENDHOL), RTF_DPAENDHOL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPAENDL), RTF_DPAENDL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPAENDSOL), RTF_DPAENDSOL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPAENDW), RTF_DPAENDW}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPARC), RTF_DPARC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPARCFLIPX), RTF_DPARCFLIPX}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPARCFLIPY), RTF_DPARCFLIPY}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPASTARTHOL), RTF_DPASTARTHOL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPASTARTL), RTF_DPASTARTL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPASTARTSOL), RTF_DPASTARTSOL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPASTARTW), RTF_DPASTARTW}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPCALLOUT), RTF_DPCALLOUT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPCOA), RTF_DPCOA}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPCOACCENT), RTF_DPCOACCENT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPCOBESTFIT), RTF_DPCOBESTFIT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPCOBORDER), RTF_DPCOBORDER}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPCODABS), RTF_DPCODABS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPCODBOTTOM), RTF_DPCODBOTTOM}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPCODCENTER), RTF_DPCODCENTER}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPCODTOP), RTF_DPCODTOP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPCOLENGTH), RTF_DPCOLENGTH}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPCOMINUSX), RTF_DPCOMINUSX}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPCOMINUSY), RTF_DPCOMINUSY}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPCOOFFSET), RTF_DPCOOFFSET}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPCOSMARTA), RTF_DPCOSMARTA}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPCOTDOUBLE), RTF_DPCOTDOUBLE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPCOTRIGHT), RTF_DPCOTRIGHT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPCOTSINGLE), RTF_DPCOTSINGLE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPCOTTRIPLE), RTF_DPCOTTRIPLE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPCOUNT), RTF_DPCOUNT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPELLIPSE), RTF_DPELLIPSE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPENDGROUP), RTF_DPENDGROUP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPFILLBGCB), RTF_DPFILLBGCB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPFILLBGCG), RTF_DPFILLBGCG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPFILLBGCR), RTF_DPFILLBGCR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPFILLBGGRAY), RTF_DPFILLBGGRAY}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPFILLBGPAL), RTF_DPFILLBGPAL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPFILLFGCB), RTF_DPFILLFGCB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPFILLFGCG), RTF_DPFILLFGCG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPFILLFGCR), RTF_DPFILLFGCR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPFILLFGGRAY), RTF_DPFILLFGGRAY}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPFILLFGPAL), RTF_DPFILLFGPAL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPFILLPAT), RTF_DPFILLPAT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPGROUP), RTF_DPGROUP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPLINE), RTF_DPLINE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPLINECOB), RTF_DPLINECOB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPLINECOG), RTF_DPLINECOG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPLINECOR), RTF_DPLINECOR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPLINEDADO), RTF_DPLINEDADO}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPLINEDADODO), RTF_DPLINEDADODO}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPLINEDASH), RTF_DPLINEDASH}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPLINEDOT), RTF_DPLINEDOT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPLINEGRAY), RTF_DPLINEGRAY}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPLINEHOLLOW), RTF_DPLINEHOLLOW}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPLINEPAL), RTF_DPLINEPAL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPLINESOLID), RTF_DPLINESOLID}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPLINEW), RTF_DPLINEW}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPPOLYCOUNT), RTF_DPPOLYCOUNT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPPOLYGON), RTF_DPPOLYGON}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPPOLYLINE), RTF_DPPOLYLINE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPPTX), RTF_DPPTX}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPPTY), RTF_DPPTY}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPRECT), RTF_DPRECT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPROUNDR), RTF_DPROUNDR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPSHADOW), RTF_DPSHADOW}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPSHADX), RTF_DPSHADX}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPSHADY), RTF_DPSHADY}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPTXBX), RTF_DPTXBX}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPTXBXMAR), RTF_DPTXBXMAR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPTXBXTEXT), RTF_DPTXBXTEXT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPX), RTF_DPX}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPXSIZE), RTF_DPXSIZE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPY), RTF_DPY}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPYSIZE), RTF_DPYSIZE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DS), RTF_DS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_EMSPACE), RTF_EMSPACE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ENSPACE), RTF_ENSPACE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FBIDI), RTF_FBIDI}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FET), RTF_FET}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FID), RTF_FID}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FILE), RTF_FILE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FILETBL), RTF_FILETBL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FLDALT), RTF_FLDALT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FNETWORK), RTF_FNETWORK}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FONTEMB), RTF_FONTEMB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FONTFILE), RTF_FONTFILE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FORMDISP), RTF_FORMDISP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FORMPROT), RTF_FORMPROT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FORMSHADE), RTF_FORMSHADE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FOSNUM), RTF_FOSNUM}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FRELATIVE), RTF_FRELATIVE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNALT), RTF_FTNALT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNIL), RTF_FTNIL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNNALC), RTF_FTNNALC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNNAR), RTF_FTNNAR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNNAUC), RTF_FTNNAUC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNNCHI), RTF_FTNNCHI}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNNRLC), RTF_FTNNRLC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNNRUC), RTF_FTNNRUC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNRSTCONT), RTF_FTNRSTCONT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNRSTPG), RTF_FTNRSTPG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTTRUETYPE), RTF_FTTRUETYPE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FVALIDDOS), RTF_FVALIDDOS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FVALIDHPFS), RTF_FVALIDHPFS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FVALIDMAC), RTF_FVALIDMAC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FVALIDNTFS), RTF_FVALIDNTFS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_HYPHAUTO), RTF_HYPHAUTO}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_HYPHCAPS), RTF_HYPHCAPS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_HYPHCONSEC), RTF_HYPHCONSEC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_HYPHPAR), RTF_HYPHPAR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LINKSELF), RTF_LINKSELF}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LINKSTYLES), RTF_LINKSTYLES}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LTRCH), RTF_LTRCH}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LTRDOC), RTF_LTRDOC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LTRMARK), RTF_LTRMARK}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LTRPAR), RTF_LTRPAR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LTRROW), RTF_LTRROW}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LTRSECT), RTF_LTRSECT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_NOCOLBAL), RTF_NOCOLBAL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_NOEXTRASPRL), RTF_NOEXTRASPRL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_NOTABIND), RTF_NOTABIND}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_NOWIDCTLPAR), RTF_NOWIDCTLPAR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OBJALIAS), RTF_OBJALIAS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OBJALIGN), RTF_OBJALIGN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OBJAUTLINK), RTF_OBJAUTLINK}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OBJCLASS), RTF_OBJCLASS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OBJCROPB), RTF_OBJCROPB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OBJCROPL), RTF_OBJCROPL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OBJCROPR), RTF_OBJCROPR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OBJCROPT), RTF_OBJCROPT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OBJDATA), RTF_OBJDATA}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OBJECT), RTF_OBJECT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OBJEMB), RTF_OBJEMB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OBJH), RTF_OBJH}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OBJICEMB), RTF_OBJICEMB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OBJLINK), RTF_OBJLINK}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OBJLOCK), RTF_OBJLOCK}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OBJNAME), RTF_OBJNAME}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OBJPUB), RTF_OBJPUB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OBJSCALEX), RTF_OBJSCALEX}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OBJSCALEY), RTF_OBJSCALEY}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OBJSECT), RTF_OBJSECT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OBJSETSIZE), RTF_OBJSETSIZE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OBJSUB), RTF_OBJSUB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OBJTIME), RTF_OBJTIME}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OBJTRANSY), RTF_OBJTRANSY}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OBJUPDATE), RTF_OBJUPDATE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OBJW), RTF_OBJW}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OTBLRUL), RTF_OTBLRUL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGNHN), RTF_PGNHN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGNHNSC), RTF_PGNHNSC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGNHNSH), RTF_PGNHNSH}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGNHNSM), RTF_PGNHNSM}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGNHNSN), RTF_PGNHNSN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGNHNSP), RTF_PGNHNSP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PICBMP), RTF_PICBMP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PICBPP), RTF_PICBPP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PN), RTF_PN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNACROSS), RTF_PNACROSS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNB), RTF_PNB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNCAPS), RTF_PNCAPS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNCARD), RTF_PNCARD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNCF), RTF_PNCF}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNDEC), RTF_PNDEC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNF), RTF_PNF}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNFS), RTF_PNFS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNHANG), RTF_PNHANG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNI), RTF_PNI}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNINDENT), RTF_PNINDENT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNLCLTR), RTF_PNLCLTR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNLCRM), RTF_PNLCRM}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNLVL), RTF_PNLVL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNLVLBLT), RTF_PNLVLBLT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNLVLBODY), RTF_PNLVLBODY}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNLVLCONT), RTF_PNLVLCONT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNNUMONCE), RTF_PNNUMONCE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNORD), RTF_PNORD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNORDT), RTF_PNORDT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNPREV), RTF_PNPREV}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNQC), RTF_PNQC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNQL), RTF_PNQL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNQR), RTF_PNQR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNRESTART), RTF_PNRESTART}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNSCAPS), RTF_PNSCAPS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNSECLVL), RTF_PNSECLVL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNSP), RTF_PNSP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNSTART), RTF_PNSTART}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNSTRIKE), RTF_PNSTRIKE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNTEXT), RTF_PNTEXT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNTXTA), RTF_PNTXTA}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNTXTB), RTF_PNTXTB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNUCLTR), RTF_PNUCLTR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNUCRM), RTF_PNUCRM}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNUL), RTF_PNUL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNULD), RTF_PNULD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNULDB), RTF_PNULDB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNULNONE), RTF_PNULNONE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNULW), RTF_PNULW}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PRCOLBL), RTF_PRCOLBL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PRINTDATA), RTF_PRINTDATA}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PSZ), RTF_PSZ}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PUBAUTO), RTF_PUBAUTO}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_RESULT), RTF_RESULT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_REVAUTH), RTF_REVAUTH}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_REVDTTM), RTF_REVDTTM}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_REVPROT), RTF_REVPROT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_REVTBL), RTF_REVTBL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_RSLTBMP), RTF_RSLTBMP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_RSLTMERGE), RTF_RSLTMERGE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_RSLTPICT), RTF_RSLTPICT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_RSLTRTF), RTF_RSLTRTF}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_RSLTTXT), RTF_RSLTTXT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_RTLCH), RTF_RTLCH}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_RTLDOC), RTF_RTLDOC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_RTLMARK), RTF_RTLMARK}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_RTLPAR), RTF_RTLPAR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_RTLROW), RTF_RTLROW}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_RTLSECT), RTF_RTLSECT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SEC), RTF_SEC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SECTNUM), RTF_SECTNUM}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SECTUNLOCKED), RTF_SECTUNLOCKED}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SLMULT), RTF_SLMULT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SOFTCOL), RTF_SOFTCOL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SOFTLHEIGHT), RTF_SOFTLHEIGHT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SOFTLINE), RTF_SOFTLINE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SOFTPAGE), RTF_SOFTPAGE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SPRSSPBF), RTF_SPRSSPBF}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SPRSTSP), RTF_SPRSTSP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SUBDOCUMENT), RTF_SUBDOCUMENT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SWPBDR), RTF_SWPBDR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TCN), RTF_TCN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TRANSMF), RTF_TRANSMF}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TRBRDRB), RTF_TRBRDRB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TRBRDRH), RTF_TRBRDRH}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TRBRDRL), RTF_TRBRDRL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TRBRDRR), RTF_TRBRDRR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TRBRDRT), RTF_TRBRDRT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TRBRDRV), RTF_TRBRDRV}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TRHDR), RTF_TRHDR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TRKEEP), RTF_TRKEEP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TRPADDB), RTF_TRPADDB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TRPADDL), RTF_TRPADDL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TRPADDR), RTF_TRPADDR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TRPADDT), RTF_TRPADDT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TRPADDFB), RTF_TRPADDFB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TRPADDFL), RTF_TRPADDFL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TRPADDFR), RTF_TRPADDFR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TRPADDFT), RTF_TRPADDFT}, + + +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_WRAPTRSP), RTF_WRAPTRSP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_XEF), RTF_XEF}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ZWJ), RTF_ZWJ}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ZWNJ), RTF_ZWNJ}, + + +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ABSLOCK), RTF_ABSLOCK}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ADJUSTRIGHT), RTF_ADJUSTRIGHT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AFTNNCHOSUNG), RTF_AFTNNCHOSUNG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AFTNNCNUM), RTF_AFTNNCNUM}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AFTNNDBAR), RTF_AFTNNDBAR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AFTNNDBNUM), RTF_AFTNNDBNUM}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AFTNNDBNUMD), RTF_AFTNNDBNUMD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AFTNNDBNUMK), RTF_AFTNNDBNUMK}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AFTNNDBNUMT), RTF_AFTNNDBNUMT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AFTNNGANADA), RTF_AFTNNGANADA}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AFTNNGBNUM), RTF_AFTNNGBNUM}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AFTNNGBNUMD), RTF_AFTNNGBNUMD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AFTNNGBNUMK), RTF_AFTNNGBNUMK}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AFTNNGBNUML), RTF_AFTNNGBNUML}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AFTNNZODIAC), RTF_AFTNNZODIAC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AFTNNZODIACD), RTF_AFTNNZODIACD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_AFTNNZODIACL), RTF_AFTNNZODIACL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ANIMTEXT), RTF_ANIMTEXT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ANSICPG), RTF_ANSICPG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BACKGROUND), RTF_BACKGROUND}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BDBFHDR), RTF_BDBFHDR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BLIPTAG), RTF_BLIPTAG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BLIPUID), RTF_BLIPUID}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BLIPUPI), RTF_BLIPUPI}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRART), RTF_BRDRART}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRDASHD), RTF_BRDRDASHD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRDASHDD), RTF_BRDRDASHDD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRDASHDOTSTR),RTF_BRDRDASHDOTSTR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRDASHSM), RTF_BRDRDASHSM}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRINSET), RTF_BRDRINSET}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDROUTSET), RTF_BRDROUTSET}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDREMBOSS), RTF_BRDREMBOSS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRENGRAVE), RTF_BRDRENGRAVE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRFRAME), RTF_BRDRFRAME}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRTHTNLG), RTF_BRDRTHTNLG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRTHTNMG), RTF_BRDRTHTNMG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRTHTNSG), RTF_BRDRTHTNSG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRTNTHLG), RTF_BRDRTNTHLG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRTNTHMG), RTF_BRDRTNTHMG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRTNTHSG), RTF_BRDRTNTHSG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRTNTHTNLG), RTF_BRDRTNTHTNLG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRTNTHTNMG), RTF_BRDRTNTHTNMG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRTNTHTNSG), RTF_BRDRTNTHTNSG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRTRIPLE), RTF_BRDRTRIPLE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRWAVY), RTF_BRDRWAVY}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDRWAVYDB), RTF_BRDRWAVYDB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CATEGORY), RTF_CATEGORY}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CGRID), RTF_CGRID}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CHARSCALEX), RTF_CHARSCALEX}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CHBGBDIAG), RTF_CHBGBDIAG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CHBGCROSS), RTF_CHBGCROSS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CHBGDCROSS), RTF_CHBGDCROSS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CHBGDKBDIAG), RTF_CHBGDKBDIAG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CHBGDKCROSS), RTF_CHBGDKCROSS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CHBGDKDCROSS), RTF_CHBGDKDCROSS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CHBGDKFDIAG), RTF_CHBGDKFDIAG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CHBGDKHORIZ), RTF_CHBGDKHORIZ}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CHBGDKVERT), RTF_CHBGDKVERT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CHBGFDIAG), RTF_CHBGFDIAG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CHBGHORIZ), RTF_CHBGHORIZ}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CHBGVERT), RTF_CHBGVERT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CHBRDR), RTF_CHBRDR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CHCBPAT), RTF_CHCBPAT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CHCFPAT), RTF_CHCFPAT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CHSHDNG), RTF_CHSHDNG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLTXLRTB), RTF_CLTXLRTB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLTXTBRL), RTF_CLTXTBRL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLVERTALB), RTF_CLVERTALB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLVERTALC), RTF_CLVERTALC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLVERTALT), RTF_CLVERTALT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLVMGF), RTF_CLVMGF}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLVMRG), RTF_CLVMRG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLTXTBRLV), RTF_CLTXTBRLV}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLTXBTLR), RTF_CLTXBTLR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CLTXLRTBV), RTF_CLTXLRTBV}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_COMPANY), RTF_COMPANY}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CRAUTH), RTF_CRAUTH}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_CRDATE), RTF_CRDATE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DATE), RTF_DATE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DEFLANGFE), RTF_DEFLANGFE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DFRAUTH), RTF_DFRAUTH}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DFRDATE), RTF_DFRDATE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DFRSTART), RTF_DFRSTART}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DFRSTOP), RTF_DFRSTOP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DFRXST), RTF_DFRXST}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DGMARGIN), RTF_DGMARGIN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DNTBLNSBDB), RTF_DNTBLNSBDB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DOCTYPE), RTF_DOCTYPE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DOCVAR), RTF_DOCVAR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DPCODESCENT), RTF_DPCODESCENT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_EMBO), RTF_EMBO}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_EMFBLIP), RTF_EMFBLIP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_EXPSHRTN), RTF_EXPSHRTN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FAAUTO), RTF_FAAUTO}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FBIAS), RTF_FBIAS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FFDEFRES), RTF_FFDEFRES}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FFDEFTEXT), RTF_FFDEFTEXT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FFENTRYMCR), RTF_FFENTRYMCR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FFEXITMCR), RTF_FFEXITMCR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FFFORMAT), RTF_FFFORMAT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FFHASLISTBOX), RTF_FFHASLISTBOX}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FFHELPTEXT), RTF_FFHELPTEXT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FFHPS), RTF_FFHPS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FFL), RTF_FFL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FFMAXLEN), RTF_FFMAXLEN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FFNAME), RTF_FFNAME}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FFOWNHELP), RTF_FFOWNHELP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FFOWNSTAT), RTF_FFOWNSTAT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FFPROT), RTF_FFPROT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FFRECALC), RTF_FFRECALC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FFRES), RTF_FFRES}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FFSIZE), RTF_FFSIZE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FFSTATTEXT), RTF_FFSTATTEXT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FFTYPE), RTF_FFTYPE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FFTYPETXT), RTF_FFTYPETXT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FLDTYPE), RTF_FLDTYPE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FNAME), RTF_FNAME}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FORMFIELD), RTF_FORMFIELD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FROMTEXT), RTF_FROMTEXT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNNCHOSUNG), RTF_FTNNCHOSUNG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNNCNUM), RTF_FTNNCNUM}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNNDBAR), RTF_FTNNDBAR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNNDBNUM), RTF_FTNNDBNUM}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNNDBNUMD), RTF_FTNNDBNUMD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNNDBNUMK), RTF_FTNNDBNUMK}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNNDBNUMT), RTF_FTNNDBNUMT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNNGANADA), RTF_FTNNGANADA}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNNGBNUM), RTF_FTNNGBNUM}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNNGBNUMD), RTF_FTNNGBNUMD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNNGBNUMK), RTF_FTNNGBNUMK}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNNGBNUML), RTF_FTNNGBNUML}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNNZODIAC), RTF_FTNNZODIAC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNNZODIACD), RTF_FTNNZODIACD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FTNNZODIACL), RTF_FTNNZODIACL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_G), RTF_G}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_GCW), RTF_GCW}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_GRIDTBL), RTF_GRIDTBL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_HIGHLIGHT), RTF_HIGHLIGHT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_HLFR), RTF_HLFR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_HLINKBASE), RTF_HLINKBASE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_HLLOC), RTF_HLLOC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_HLSRC), RTF_HLSRC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ILVL), RTF_ILVL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_IMPR), RTF_IMPR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_JPEGBLIP), RTF_JPEGBLIP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LEVELFOLLOW), RTF_LEVELFOLLOW}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LEVELINDENT), RTF_LEVELINDENT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LEVELJC), RTF_LEVELJC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LEVELLEGAL), RTF_LEVELLEGAL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LEVELNFC), RTF_LEVELNFC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LEVELNORESTART),RTF_LEVELNORESTART}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LEVELNUMBERS), RTF_LEVELNUMBERS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LEVELOLD), RTF_LEVELOLD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LEVELPREV), RTF_LEVELPREV}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LEVELPREVSPACE),RTF_LEVELPREVSPACE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LEVELSPACE), RTF_LEVELSPACE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LEVELSTARTAT), RTF_LEVELSTARTAT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LEVELTEXT), RTF_LEVELTEXT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LINKVAL), RTF_LINKVAL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LIST), RTF_LIST}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LISTID), RTF_LISTID}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LISTLEVEL), RTF_LISTLEVEL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LISTNAME), RTF_LISTNAME}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LISTOVERRIDE), RTF_LISTOVERRIDE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LISTOVERRIDECOUNT), RTF_LISTOVERRIDECOUNT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LISTOVERRIDEFORMAT), RTF_LISTOVERRIDEFORMAT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LISTOVERRIDESTART), RTF_LISTOVERRIDESTART}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LISTOVERRIDETABLE), RTF_LISTOVERRIDETABLE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LISTRESTARTHDN),RTF_LISTRESTARTHDN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LISTSIMPLE), RTF_LISTSIMPLE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LISTTABLE), RTF_LISTTABLE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LISTTEMPLATEID),RTF_LISTTEMPLATEID}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LISTTEXT), RTF_LISTTEXT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LS), RTF_LS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LYTEXCTTP), RTF_LYTEXCTTP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LYTPRTMET), RTF_LYTPRTMET}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_MANAGER), RTF_MANAGER}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_MSMCAP), RTF_MSMCAP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_NOFCHARSWS), RTF_NOFCHARSWS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_NOLEAD), RTF_NOLEAD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_NONSHPPICT), RTF_NONSHPPICT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_NOSECTEXPAND), RTF_NOSECTEXPAND}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_NOSNAPLINEGRID),RTF_NOSNAPLINEGRID}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_NOSPACEFORUL), RTF_NOSPACEFORUL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_NOULTRLSPC), RTF_NOULTRLSPC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_NOXLATTOYEN), RTF_NOXLATTOYEN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OBJATTPH), RTF_OBJATTPH}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OBJHTML), RTF_OBJHTML}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OBJOCX), RTF_OBJOCX}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OLDLINEWRAP), RTF_OLDLINEWRAP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OUTLINELEVEL), RTF_OUTLINELEVEL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OVERLAY), RTF_OVERLAY}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PANOSE), RTF_PANOSE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGBRDRB), RTF_PGBRDRB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGBRDRFOOT), RTF_PGBRDRFOOT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGBRDRHEAD), RTF_PGBRDRHEAD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGBRDRL), RTF_PGBRDRL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGBRDROPT), RTF_PGBRDROPT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGBRDRR), RTF_PGBRDRR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGBRDRSNAP), RTF_PGBRDRSNAP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGBRDRT), RTF_PGBRDRT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGNCHOSUNG), RTF_PGNCHOSUNG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGNCNUM), RTF_PGNCNUM}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGNDBNUMK), RTF_PGNDBNUMK}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGNDBNUMT), RTF_PGNDBNUMT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGNGANADA), RTF_PGNGANADA}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGNGBNUM), RTF_PGNGBNUM}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGNGBNUMD), RTF_PGNGBNUMD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGNGBNUMK), RTF_PGNGBNUMK}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGNGBNUML), RTF_PGNGBNUML}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGNZODIAC), RTF_PGNZODIAC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGNZODIACD), RTF_PGNZODIACD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGNZODIACL), RTF_PGNZODIACL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PICPROP), RTF_PICPROP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNAIUEO), RTF_PNAIUEO}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNAIUEOD), RTF_PNAIUEOD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNCHOSUNG), RTF_PNCHOSUNG}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNDBNUMD), RTF_PNDBNUMD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNDBNUMK), RTF_PNDBNUMK}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNDBNUML), RTF_PNDBNUML}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNDBNUMT), RTF_PNDBNUMT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNGANADA), RTF_PNGANADA}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNGBLIP), RTF_PNGBLIP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNGBNUM), RTF_PNGBNUM}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNGBNUMD), RTF_PNGBNUMD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNGBNUMK), RTF_PNGBNUMK}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNGBNUML), RTF_PNGBNUML}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNRAUTH), RTF_PNRAUTH}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNRDATE), RTF_PNRDATE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNRNFC), RTF_PNRNFC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNRNOT), RTF_PNRNOT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNRPNBR), RTF_PNRPNBR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNRRGB), RTF_PNRRGB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNRSTART), RTF_PNRSTART}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNRSTOP), RTF_PNRSTOP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNRXST), RTF_PNRXST}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNZODIAC), RTF_PNZODIAC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNZODIACD), RTF_PNZODIACD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PNZODIACL), RTF_PNZODIACL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LFOLEVEL), RTF_LFOLEVEL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_POSYIN), RTF_POSYIN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_POSYOUT), RTF_POSYOUT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PRIVATE), RTF_PRIVATE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PROPNAME), RTF_PROPNAME}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PROPTYPE), RTF_PROPTYPE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_REVAUTHDEL), RTF_REVAUTHDEL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_REVDTTMDEL), RTF_REVDTTMDEL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SAUTOUPD), RTF_SAUTOUPD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SECTDEFAULTCL), RTF_SECTDEFAULTCL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SECTEXPAND), RTF_SECTEXPAND}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SECTLINEGRID), RTF_SECTLINEGRID}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SECTSPECIFYCL), RTF_SECTSPECIFYCL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SECTSPECIFYL), RTF_SECTSPECIFYL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHIDDEN), RTF_SHIDDEN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHPBOTTOM), RTF_SHPBOTTOM}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHPBXCOLUMN), RTF_SHPBXCOLUMN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHPBXMARGIN), RTF_SHPBXMARGIN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHPBXPAGE), RTF_SHPBXPAGE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHPBYMARGIN), RTF_SHPBYMARGIN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHPBYPAGE), RTF_SHPBYPAGE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHPBYPARA), RTF_SHPBYPARA}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHPFBLWTXT), RTF_SHPFBLWTXT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHPFHDR), RTF_SHPFHDR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHPGRP), RTF_SHPGRP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHPINST), RTF_SHPINST}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHPLEFT), RTF_SHPLEFT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHPLID), RTF_SHPLID}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHPLOCKANCHOR), RTF_SHPLOCKANCHOR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHPPICT), RTF_SHPPICT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHPRIGHT), RTF_SHPRIGHT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHPRSLT), RTF_SHPRSLT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHPTOP), RTF_SHPTOP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHPTXT), RTF_SHPTXT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHPWRK), RTF_SHPWRK}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHPWR), RTF_SHPWR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHPZ), RTF_SHPZ}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SPRSBSP), RTF_SPRSBSP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SPRSLNSP), RTF_SPRSLNSP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SPRSTSM), RTF_SPRSTSM}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_STATICVAL), RTF_STATICVAL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_STEXTFLOW), RTF_STEXTFLOW}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_STRIKED), RTF_STRIKED}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SUBFONTBYSIZE), RTF_SUBFONTBYSIZE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TCELLD), RTF_TCELLD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TIME), RTF_TIME}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TRUNCATEFONTHEIGHT), RTF_TRUNCATEFONTHEIGHT}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_UC), RTF_UC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_UD), RTF_UD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ULDASH), RTF_ULDASH}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ULDASHD), RTF_ULDASHD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ULDASHDD), RTF_ULDASHDD}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ULTH), RTF_ULTH}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ULWAVE), RTF_ULWAVE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ULC), RTF_ULC}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_U), RTF_U}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_UPR), RTF_UPR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_USERPROPS), RTF_USERPROPS}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_VIEWKIND), RTF_VIEWKIND}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_VIEWSCALE), RTF_VIEWSCALE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_VIEWZK), RTF_VIEWZK}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_WIDCTLPAR), RTF_WIDCTLPAR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_WINDOWCAPTION), RTF_WINDOWCAPTION}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_WPEQN), RTF_WPEQN}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_WPJST), RTF_WPJST}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_WPSP), RTF_WPSP}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_YXE), RTF_YXE}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FRMTXLRTB), RTF_FRMTXLRTB}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FRMTXTBRL), RTF_FRMTXTBRL}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FRMTXBTLR), RTF_FRMTXBTLR}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FRMTXLRTBV), RTF_FRMTXLRTBV}, +{OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FRMTXTBRLV), RTF_FRMTXTBRLV}, + +// MS-2000 Tokens + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ULTHD), RTF_ULTHD}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ULTHDASH), RTF_ULTHDASH}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ULLDASH), RTF_ULLDASH}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ULTHLDASH), RTF_ULTHLDASH}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ULTHDASHD), RTF_ULTHDASHD}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ULTHDASHDD), RTF_ULTHDASHDD}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ULHWAVE), RTF_ULHWAVE}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ULULDBWAVE), RTF_ULULDBWAVE}, + + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LOCH), RTF_LOCH}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_HICH), RTF_HICH}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DBCH), RTF_DBCH}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_LANGFE), RTF_LANGFE}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ADEFLANG), RTF_ADEFLANG}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ADEFF), RTF_ADEFF}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ACCNONE), RTF_ACCNONE}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ACCDOT), RTF_ACCDOT}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ACCCOMMA), RTF_ACCCOMMA}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TWOINONE), RTF_TWOINONE}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_HORZVERT), RTF_HORZVERT}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FAHANG), RTF_FAHANG}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FAVAR), RTF_FAVAR}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FACENTER), RTF_FACENTER}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FAROMAN), RTF_FAROMAN}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FAFIXED), RTF_FAFIXED}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_NOCWRAP), RTF_NOCWRAP}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_NOOVERFLOW), RTF_NOOVERFLOW}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_ASPALPHA), RTF_ASPALPHA}, + +// SWG specific attributes + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_GRFALIGNV), RTF_GRF_ALIGNV}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_GRFALIGNH), RTF_GRF_ALIGNH}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_GRFMIRROR), RTF_GRF_MIRROR}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_HEADERYB), RTF_HEADER_YB}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_HEADERXL), RTF_HEADER_XL}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_HEADERXR), RTF_HEADER_XR}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FOOTERYT), RTF_FOOTER_YT}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FOOTERXL), RTF_FOOTER_XL}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FOOTERXR), RTF_FOOTER_XR}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_HEADERYH), RTF_HEADER_YH}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FOOTERYH), RTF_FOOTER_YH}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BALANCEDCOLUMN),RTF_BALANCED_COLUMN}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_UPDNPROP), RTF_SWG_ESCPROP}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PRTDATA), RTF_SWG_PRTDATA}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BKMKKEY), RTF_BKMK_KEY}, + +// Attributes for fly frames + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FLYPRINT), RTF_FLYPRINT}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FLYOPAQUE), RTF_FLYOPAQUE}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FLYPRTCTD), RTF_FLYPRTCTD}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FLYMAINCNT), RTF_FLYMAINCNT}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FLYVERT), RTF_FLYVERT}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FLYHORZ), RTF_FLYHORZ}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DFRMTXTL), RTF_FLYOUTLEFT}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DFRMTXTR), RTF_FLYOUTRIGHT}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DFRMTXTU), RTF_FLYOUTUPPER}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_DFRMTXTW), RTF_FLYOUTLOWER}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FLYANCHOR), RTF_FLYANCHOR}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FLYCNTNT), RTF_FLY_CNTNT}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FLYCOLUMN), RTF_FLY_COLUMN}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FLYPAGE), RTF_FLY_PAGE}, + + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDBOX), RTF_BRDBOX}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDLNCOL), RTF_BRDLINE_COL}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDLNIN), RTF_BRDLINE_IN}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDLNOUT), RTF_BRDLINE_OUT}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_BRDLNDIST), RTF_BRDLINE_DIST}, + + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHADOW), RTF_SHADOW}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHDWDIST), RTF_SHDW_DIST}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHDWSTYLE), RTF_SHDW_STYLE}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHDWCOL), RTF_SHDW_COL}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHDWFCOL), RTF_SHDW_FCOL}, + + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_FLYINPARA), RTF_FLY_INPARA}, + + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGDSCTBL), RTF_PGDSCTBL}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGDSC), RTF_PGDSC}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGDSCUSE), RTF_PGDSCUSE}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGDSCNXT), RTF_PGDSCNXT}, + + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_HYPHEN), RTF_HYPHEN}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_HYPHLEAD), RTF_HYPHLEAD}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_HYPHTRAIL), RTF_HYPHTRAIL}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_HYPHMAX), RTF_HYPHMAX}, + + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_TLSWG), RTF_TLSWG}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGBRK), RTF_PGBRK}, + + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_PGDSCNO), RTF_PGDSCNO}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SOUTLVL), RTF_SOUTLVL}, + + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHP), RTF_SHP}, + /* + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHPLEFT), RTF_SHPLEFT} + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHPTOP), RTF_SHPTOP} + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHPBOTTOM), RTF_SHPBOTTOM} + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SHPRIGHT), RTF_SHPRIGHT} + */ + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SN), RTF_SN}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SV), RTF_SV}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_SP), RTF_SP}, + +// Support for overline attributes + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OL), RTF_OL}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OLW), RTF_OLW}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OLD), RTF_OLD}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OLDB), RTF_OLDB}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OLNONE), RTF_OLNONE}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OLDASH), RTF_OLDASH}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OLDASHD), RTF_OLDASHD}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OLDASHDD), RTF_OLDASHDD}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OLTH), RTF_OLTH}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OLWAVE), RTF_OLWAVE}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OLC), RTF_OLC}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OLTHD), RTF_OLTHD}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OLTHDASH), RTF_OLTHDASH}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OLLDASH), RTF_OLLDASH}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OLTHLDASH), RTF_OLTHLDASH}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OLTHDASHD), RTF_OLTHDASHD}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OLTHDASHDD), RTF_OLTHDASHDD}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OLHWAVE), RTF_OLHWAVE}, + {OUStringLiteral(OOO_STRING_SVTOOLS_RTF_OLOLDBWAVE), RTF_OLOLDBWAVE} +}; + + +int GetRTFToken( const OUString& rSearch ) +{ + if( !bSortKeyWords ) + { + std::sort( std::begin(aRTFTokenTab), std::end(aRTFTokenTab), + [](const RTF_TokenEntry & lhs, const RTF_TokenEntry & rhs) + { + return strcmp(lhs.sToken.data, rhs.sToken.data) < 0; + } ); + bSortKeyWords = true; + } + + auto findCompare = [](const RTF_TokenEntry & lhs, const OUString & s) + { + return s.compareToIgnoreAsciiCaseAscii(lhs.sToken.data) > 0; + }; + auto findIt = std::lower_bound( std::begin(aRTFTokenTab), std::end(aRTFTokenTab), rSearch, findCompare); + if (findIt != std::end(aRTFTokenTab) && rSearch.compareToIgnoreAsciiCaseAscii(findIt->sToken.data)==0) + return findIt->nToken; + + return 0; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/svrtf/rtfout.cxx b/svtools/source/svrtf/rtfout.cxx new file mode 100644 index 000000000..b06a04eed --- /dev/null +++ b/svtools/source/svrtf/rtfout.cxx @@ -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 . + */ + +#include <tools/debug.hxx> +#include <tools/stream.hxx> +#include <tools/solar.h> +#include <rtl/string.hxx> +#include <svtools/rtfkeywd.hxx> +#include <svtools/rtfout.hxx> + +namespace { + +SvStream& Out_Hex( SvStream& rStream, sal_uLong nHex, sal_uInt8 nLen ) +{ + char aNToABuf[] = "0000000000000000"; + + DBG_ASSERT( nLen < sizeof(aNToABuf), "too many places" ); + if( nLen >= sizeof(aNToABuf) ) + nLen = (sizeof(aNToABuf)-1); + + // set pointer to end of buffer + char* pStr = aNToABuf + (sizeof(aNToABuf)-1); + for( sal_uInt8 n = 0; n < nLen; ++n ) + { + *(--pStr) = static_cast<char>(nHex & 0xf ) + 48; + if( *pStr > '9' ) + *pStr += 39; + nHex >>= 4; + } + return rStream.WriteCharPtr( pStr ); +} + +// Ideally, this function should work on (sal_uInt32) Unicode scalar values +// instead of (sal_Unicode) UTF-16 code units. However, at least "Rich Text +// Format (RTF) Specification Version 1.9.1" available at +// <https://www.microsoft.com/en-us/download/details.aspx?id=10725> does not +// look like it allows non-BMP Unicode characters >= 0x10000 in the \uN notation +// (it only talks about "Unicode character", but then explains how values of N +// greater than 32767 will be expressed as negative signed 16-bit numbers, so +// that smells like \uN is limited to BMP). +// However the "Mathematics" section has an example that shows the code point +// U+1D44E being encoded as UTF-16 surrogate pair "\u-10187?\u-9138?", so +// sal_Unicode actually works fine here. +SvStream& Out_Char(SvStream& rStream, sal_Unicode c, + int *pUCMode, rtl_TextEncoding eDestEnc) +{ + const char* pStr = nullptr; + switch (c) + { + case 0x1: + case 0x2: + // this are control character of our textattributes and will never be + // written + break; + case 0xA0: + rStream.WriteCharPtr( "\\~" ); + break; + case 0xAD: + rStream.WriteCharPtr( "\\-" ); + break; + case 0x2011: + rStream.WriteCharPtr( "\\_" ); + break; + case '\n': + pStr = OOO_STRING_SVTOOLS_RTF_LINE; + break; + case '\t': + pStr = OOO_STRING_SVTOOLS_RTF_TAB; + break; + default: + switch(c) + { + case 149: + pStr = OOO_STRING_SVTOOLS_RTF_BULLET; + break; + case 150: + pStr = OOO_STRING_SVTOOLS_RTF_ENDASH; + break; + case 151: + pStr = OOO_STRING_SVTOOLS_RTF_EMDASH; + break; + case 145: + pStr = OOO_STRING_SVTOOLS_RTF_LQUOTE; + break; + case 146: + pStr = OOO_STRING_SVTOOLS_RTF_RQUOTE; + break; + case 147: + pStr = OOO_STRING_SVTOOLS_RTF_LDBLQUOTE; + break; + case 148: + pStr = OOO_STRING_SVTOOLS_RTF_RDBLQUOTE; + break; + } + + if (pStr) + break; + + switch (c) + { + case '\\': + case '}': + case '{': + rStream.WriteChar( '\\' ).WriteChar( char(c) ); + break; + default: + if (c >= ' ' && c <= '~') + rStream.WriteChar( char(c) ); + else + { + //If we can't convert to the dest encoding, or if + //it's an uncommon multibyte sequence which most + //readers won't be able to handle correctly, then + //export as unicode + OUString sBuf(&c, 1); + OString sConverted; + sal_uInt32 const nFlags = + RTL_UNICODETOTEXT_FLAGS_UNDEFINED_ERROR | + RTL_UNICODETOTEXT_FLAGS_INVALID_ERROR; + bool bWriteAsUnicode = !(sBuf.convertToString(&sConverted, + eDestEnc, nFlags)) + || (RTL_TEXTENCODING_UTF8==eDestEnc); // #i43933# do not export UTF-8 chars in RTF; + if (bWriteAsUnicode) + { + (void)sBuf.convertToString(&sConverted, + eDestEnc, OUSTRING_TO_OSTRING_CVTFLAGS); + } + const sal_Int32 nLen = sConverted.getLength(); + + if (bWriteAsUnicode && pUCMode) + { + // then write as unicode - character + if (*pUCMode != nLen) + { + // #i47831# add an additional whitespace, so that + // "document whitespaces" are not ignored.; + rStream.WriteCharPtr( "\\uc" ) + .WriteOString( OString::number(nLen) ).WriteCharPtr( " " ); + *pUCMode = nLen; + } + rStream.WriteCharPtr( "\\u" ) + .WriteCharPtr( OString::number( + static_cast<sal_Int32>(c)).getStr() ); + } + + for (sal_Int32 nI = 0; nI < nLen; ++nI) + { + rStream.WriteCharPtr( "\\'" ); + Out_Hex(rStream, sConverted[nI], 2); + } + } + break; + } + break; + } + + if (pStr) + rStream.WriteCharPtr( pStr ).WriteChar( ' ' ); + + return rStream; +} + +} + +SvStream& RTFOutFuncs::Out_String( SvStream& rStream, const OUString& rStr, + rtl_TextEncoding eDestEnc) +{ + int nUCMode = 1; + for (sal_Int32 n = 0; n < rStr.getLength(); ++n) + Out_Char(rStream, rStr[n], &nUCMode, eDestEnc); + if (nUCMode != 1) + rStream.WriteCharPtr( "\\uc1" ).WriteCharPtr( " " ); // #i47831# add an additional whitespace, so that "document whitespaces" are not ignored.; + return rStream; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/svrtf/svparser.cxx b/svtools/source/svrtf/svparser.cxx new file mode 100644 index 000000000..cafb5b8d3 --- /dev/null +++ b/svtools/source/svrtf/svparser.cxx @@ -0,0 +1,737 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <svtools/svparser.hxx> +#include <svtools/htmltokn.h> +#include <tools/stream.hxx> +#include <tools/debug.hxx> +#include <rtl/textcvt.h> +#include <rtl/tencinfo.h> +#include <rtl/character.hxx> +#include <sal/log.hxx> + +#include <vector> +#include <climits> + +// structure to store the actual data +template<typename T> +struct SvParser_Impl +{ + OUString aToken; // gescanntes Token + sal_uInt64 nFilePos; // actual position in stream + sal_uLong nlLineNr; // actual line number + sal_uLong nlLinePos; // actual column number + long nTokenValue; // extra value (RTF) + bool bTokenHasValue; // indicates whether nTokenValue is valid + T nToken; // actual Token + sal_uInt32 nNextCh; // actual character + T nSaveToken; // the token from Continue + + rtl_TextToUnicodeConverter hConv; + rtl_TextToUnicodeContext hContext; + + SvParser_Impl() + : nFilePos(0) + , nlLineNr(0) + , nlLinePos(0) + , nTokenValue(0) + , bTokenHasValue(false) + , nToken(static_cast<T>(0)) + , nNextCh(0) + , nSaveToken(static_cast<T>(0)) + , hConv( nullptr ) + , hContext( reinterpret_cast<rtl_TextToUnicodeContext>(1) ) + { + } + +}; + + +template<typename T> +SvParser<T>::TokenStackType::TokenStackType() + : nTokenValue(0) + , bTokenHasValue(false) + , nTokenId(static_cast<T>(0)) +{ +} + +// Constructor +template<typename T> +SvParser<T>::SvParser( SvStream& rIn, sal_uInt8 nStackSize ) + : rInput( rIn ) + , nlLineNr( 1 ) + , nlLinePos( 1 ) + , pImplData( nullptr ) + , m_nTokenIndex(0) + , nTokenValue( 0 ) + , bTokenHasValue( false ) + , eState( SvParserState::NotStarted ) + , eSrcEnc( RTL_TEXTENCODING_DONTKNOW ) + , nNextChPos(0) + , nNextCh(0) + , bUCS2BSrcEnc(false) + , bSwitchToUCS2(false) + , bRTF_InTextRead(false) + , nTokenStackSize( nStackSize ) + , nTokenStackPos( 0 ) +{ + eState = SvParserState::NotStarted; + if( nTokenStackSize < 3 ) + nTokenStackSize = 3; + pTokenStack.reset(new TokenStackType[ nTokenStackSize ]); + pTokenStackPos = pTokenStack.get(); +} + +template<typename T> +SvParser<T>::~SvParser() +{ + if( pImplData && pImplData->hConv ) + { + rtl_destroyTextToUnicodeContext( pImplData->hConv, + pImplData->hContext ); + rtl_destroyTextToUnicodeConverter( pImplData->hConv ); + } + + pTokenStack.reset(); +} + +template<typename T> SvParserState SvParser<T>::GetStatus() const { return eState; } +template<typename T> sal_uLong SvParser<T>::GetLineNr() const { return nlLineNr; } +template<typename T> sal_uLong SvParser<T>::GetLinePos() const { return nlLinePos; } +template<typename T> void SvParser<T>::IncLineNr() { ++nlLineNr; } +template<typename T> sal_uLong SvParser<T>::IncLinePos() { return ++nlLinePos; } +template<typename T> void SvParser<T>::SetLineNr( sal_uLong nlNum ) { nlLineNr = nlNum; } +template<typename T> void SvParser<T>::SetLinePos( sal_uLong nlPos ) { nlLinePos = nlPos; } +template<typename T> bool SvParser<T>::IsParserWorking() const { return SvParserState::Working == eState; } +template<typename T> rtl_TextEncoding SvParser<T>::GetSrcEncoding() const { return eSrcEnc; } +template<typename T> void SvParser<T>::SetSwitchToUCS2( bool bSet ) { bSwitchToUCS2 = bSet; } +template<typename T> bool SvParser<T>::IsSwitchToUCS2() const { return bSwitchToUCS2; } +template<typename T> sal_uInt16 SvParser<T>::GetCharSize() const { return (RTL_TEXTENCODING_UCS2 == eSrcEnc) ? 2 : 1; } +template<typename T> Link<LinkParamNone*,void> SvParser<T>::GetAsynchCallLink() const +{ + return LINK( const_cast<SvParser*>(this), SvParser, NewDataRead ); +} + +template<typename T> +void SvParser<T>::ClearTxtConvContext() +{ + if( pImplData && pImplData->hConv ) + rtl_resetTextToUnicodeContext( pImplData->hConv, pImplData->hContext ); +} + +template<typename T> +void SvParser<T>::SetSrcEncoding( rtl_TextEncoding eEnc ) +{ + if( eEnc == eSrcEnc ) + return; + + if( pImplData && pImplData->hConv ) + { + rtl_destroyTextToUnicodeContext( pImplData->hConv, + pImplData->hContext ); + rtl_destroyTextToUnicodeConverter( pImplData->hConv ); + pImplData->hConv = nullptr; + pImplData->hContext = reinterpret_cast<rtl_TextToUnicodeContext>(1); + } + + if( rtl_isOctetTextEncoding(eEnc) || + RTL_TEXTENCODING_UCS2 == eEnc ) + { + eSrcEnc = eEnc; + if( !pImplData ) + pImplData.reset(new SvParser_Impl<T>); + pImplData->hConv = rtl_createTextToUnicodeConverter( eSrcEnc ); + DBG_ASSERT( pImplData->hConv, + "SvParser::SetSrcEncoding: no converter for source encoding" ); + if( !pImplData->hConv ) + eSrcEnc = RTL_TEXTENCODING_DONTKNOW; + else + pImplData->hContext = + rtl_createTextToUnicodeContext( pImplData->hConv ); + } + else + { + SAL_WARN( "svtools", + "SvParser::SetSrcEncoding: invalid source encoding" ); + eSrcEnc = RTL_TEXTENCODING_DONTKNOW; + } +} + +template<typename T> +void SvParser<T>::RereadLookahead() +{ + rInput.Seek(nNextChPos); + nNextCh = GetNextChar(); +} + +template<typename T> +sal_uInt32 SvParser<T>::GetNextChar() +{ + sal_uInt32 c = 0U; + + // When reading multiple bytes, we don't have to care about the file + // position when we run into the pending state. The file position is + // maintained by SaveState/RestoreState. + bool bErr; + if( bSwitchToUCS2 && 0 == rInput.Tell() ) + { + unsigned char c1; + bool bSeekBack = true; + + rInput.ReadUChar( c1 ); + bErr = !rInput.good(); + if( !bErr ) + { + if( 0xff == c1 || 0xfe == c1 ) + { + unsigned char c2; + rInput.ReadUChar( c2 ); + bErr = !rInput.good(); + if( !bErr ) + { + if( 0xfe == c1 && 0xff == c2 ) + { + eSrcEnc = RTL_TEXTENCODING_UCS2; + bUCS2BSrcEnc = true; + bSeekBack = false; + } + else if( 0xff == c1 && 0xfe == c2 ) + { + eSrcEnc = RTL_TEXTENCODING_UCS2; + bUCS2BSrcEnc = false; + bSeekBack = false; + } + } + } + else if( 0xef == c1 || 0xbb == c1 ) // check for UTF-8 BOM + { + unsigned char c2; + rInput.ReadUChar( c2 ); + bErr = !rInput.good(); + if( !bErr ) + { + if( ( 0xef == c1 && 0xbb == c2 ) || ( 0xbb == c1 && 0xef == c2 ) ) + { + unsigned char c3(0); + rInput.ReadUChar( c3 ); + bErr = !rInput.good(); + if( !bErr && ( 0xbf == c3 ) ) + { + SetSrcEncoding(RTL_TEXTENCODING_UTF8); + bSeekBack = false; + } + } + } + } + } + if( bSeekBack ) + rInput.Seek( 0 ); + + bSwitchToUCS2 = false; + } + + nNextChPos = rInput.Tell(); + + if( RTL_TEXTENCODING_UCS2 == eSrcEnc ) + { + sal_Unicode cUC = USHRT_MAX; + unsigned char c1, c2; + + rInput.ReadUChar( c1 ).ReadUChar( c2 ); + if( 2 == rInput.Tell() && rInput.good() && + ( (bUCS2BSrcEnc && 0xfe == c1 && 0xff == c2) || + (!bUCS2BSrcEnc && 0xff == c1 && 0xfe == c2) ) ) + rInput.ReadUChar( c1 ).ReadUChar( c2 ); + + bErr = !rInput.good(); + if( !bErr ) + { + if( bUCS2BSrcEnc ) + cUC = (sal_Unicode(c1) << 8) | c2; + else + cUC = (sal_Unicode(c2) << 8) | c1; + + c = cUC; + } + } + else + { + sal_Size nChars = 0; + do + { + char c1; // signed, that's the text converter expects + rInput.ReadChar( c1 ); + bErr = !rInput.good(); + if( !bErr ) + { + if ( + RTL_TEXTENCODING_DONTKNOW == eSrcEnc || + RTL_TEXTENCODING_SYMBOL == eSrcEnc + ) + { + // no conversion shall take place + c = reinterpret_cast<sal_uChar&>( c1 ); + nChars = 1; + } + else + { + assert(pImplData && pImplData->hConv && "no text converter!"); + + sal_Unicode cUC; + sal_uInt32 nInfo = 0; + sal_Size nCvtBytes; + nChars = rtl_convertTextToUnicode( + pImplData->hConv, pImplData->hContext, + &c1, 1, &cUC, 1, + RTL_TEXTTOUNICODE_FLAGS_UNDEFINED_ERROR| + RTL_TEXTTOUNICODE_FLAGS_MBUNDEFINED_ERROR| + RTL_TEXTTOUNICODE_FLAGS_INVALID_ERROR, + &nInfo, &nCvtBytes); + if( (nInfo&RTL_TEXTTOUNICODE_INFO_SRCBUFFERTOOSMALL) != 0 ) + { + // The conversion wasn't successful because we haven't + // read enough characters. + if( pImplData->hContext != reinterpret_cast<rtl_TextToUnicodeContext>(1) ) + { + sal_Unicode sCh[2]; + while( (nInfo&RTL_TEXTTOUNICODE_INFO_SRCBUFFERTOOSMALL) != 0 ) + { + rInput.ReadChar( c1 ); + bErr = !rInput.good(); + if( bErr ) + break; + + nChars = rtl_convertTextToUnicode( + pImplData->hConv, pImplData->hContext, + &c1, 1, sCh , 2, + RTL_TEXTTOUNICODE_FLAGS_UNDEFINED_ERROR| + RTL_TEXTTOUNICODE_FLAGS_MBUNDEFINED_ERROR| + RTL_TEXTTOUNICODE_FLAGS_INVALID_ERROR, + &nInfo, &nCvtBytes); + } + if( !bErr ) + { + if( 1 == nChars && 0 == nInfo ) + { + c = sal_uInt32( sCh[0] ); + } + else if( 2 == nChars && 0 == nInfo ) + { + c = rtl::combineSurrogates( sCh[0], sCh[1] ); + } + else if( 0 != nChars || 0 != nInfo ) + { + DBG_ASSERT( (nInfo&RTL_TEXTTOUNICODE_INFO_SRCBUFFERTOOSMALL) == 0, + "source buffer is too small" ); + DBG_ASSERT( (nInfo&~(RTL_TEXTTOUNICODE_INFO_SRCBUFFERTOOSMALL)) == 0, + "there is a conversion error" ); + DBG_ASSERT( 0 == nChars, + "there is a converted character, but an error" ); + // There are still errors, but nothing we can + // do + c = '?'; + nChars = 1; + } + } + } + else + { + char sBuffer[10]; + sBuffer[0] = c1; + sal_uInt16 nLen = 1; + while( (nInfo&RTL_TEXTTOUNICODE_INFO_SRCBUFFERTOOSMALL) != 0 && + nLen < 10 ) + { + rInput.ReadChar( c1 ); + bErr = !rInput.good(); + if( bErr ) + break; + + sBuffer[nLen++] = c1; + nChars = rtl_convertTextToUnicode( + pImplData->hConv, nullptr, sBuffer, nLen, &cUC, 1, + RTL_TEXTTOUNICODE_FLAGS_UNDEFINED_ERROR| + RTL_TEXTTOUNICODE_FLAGS_MBUNDEFINED_ERROR| + RTL_TEXTTOUNICODE_FLAGS_INVALID_ERROR, + &nInfo, &nCvtBytes); + } + if( !bErr ) + { + if( 1 == nChars && 0 == nInfo ) + { + DBG_ASSERT( nCvtBytes == nLen, + "no all bytes have been converted!" ); + c = cUC; + } + else + { + DBG_ASSERT( (nInfo&RTL_TEXTTOUNICODE_INFO_SRCBUFFERTOOSMALL) == 0, + "source buffer is too small" ); + DBG_ASSERT( (nInfo&~(RTL_TEXTTOUNICODE_INFO_SRCBUFFERTOOSMALL)) == 0, + "there is a conversion error" ); + DBG_ASSERT( 0 == nChars, + "there is a converted character, but an error" ); + + // There are still errors, so we use the first + // character and restart after that. + c = reinterpret_cast<sal_uChar&>( sBuffer[0] ); + rInput.SeekRel( -(nLen-1) ); + nChars = 1; + } + } + } + } + else if( 1 == nChars && 0 == nInfo ) + { + // The conversion was successful + DBG_ASSERT( nCvtBytes == 1, + "no all bytes have been converted!" ); + c = cUC; + } + else if( 0 != nChars || 0 != nInfo ) + { + DBG_ASSERT( 0 == nChars, + "there is a converted character, but an error" ); + DBG_ASSERT( 0 != nInfo, + "there is no converted character and no error" ); + // #73398#: If the character could not be converted, + // because a conversion is not available, do no conversion at all. + c = reinterpret_cast<sal_uChar&>( c1 ); + nChars = 1; + + } + } + } + } + while( 0 == nChars && !bErr ); + } + + if ( ! rtl::isUnicodeScalarValue( c ) ) + c = '?' ; + + if( bErr ) + { + if( ERRCODE_IO_PENDING == rInput.GetError() ) + { + eState = SvParserState::Pending; + return c; + } + else + return sal_Unicode(EOF); + } + + if( c == '\n' ) + { + IncLineNr(); + SetLinePos( 1 ); + } + else + IncLinePos(); + + return c; +} + +template<typename T> +T SvParser<T>::GetNextToken() +{ + T nRet = static_cast<T>(0); + + if( !nTokenStackPos ) + { + aToken.clear(); // empty token buffer + nTokenValue = -1; // marker for no value read + bTokenHasValue = false; + + nRet = GetNextToken_(); + if( SvParserState::Pending == eState ) + return nRet; + } + + ++pTokenStackPos; + if( pTokenStackPos == pTokenStack.get() + nTokenStackSize ) + pTokenStackPos = pTokenStack.get(); + + // pop from stack ?? + if( nTokenStackPos ) + { + --nTokenStackPos; + nTokenValue = pTokenStackPos->nTokenValue; + bTokenHasValue = pTokenStackPos->bTokenHasValue; + aToken = pTokenStackPos->sToken; + nRet = pTokenStackPos->nTokenId; + ++m_nTokenIndex; + } + // no, now push actual value on stack + else if( SvParserState::Working == eState ) + { + pTokenStackPos->sToken = aToken; + pTokenStackPos->nTokenValue = nTokenValue; + pTokenStackPos->bTokenHasValue = bTokenHasValue; + pTokenStackPos->nTokenId = nRet; + ++m_nTokenIndex; + } + else if( SvParserState::Accepted != eState && SvParserState::Pending != eState ) + eState = SvParserState::Error; // an error occurred + + return nRet; +} + +template<typename T> +T SvParser<T>::SkipToken( short nCnt ) // "skip" n Tokens backward +{ + pTokenStackPos = GetStackPtr( nCnt ); + short nTmp = nTokenStackPos - nCnt; + if( nTmp < 0 ) + nTmp = 0; + else if( nTmp > nTokenStackSize ) + nTmp = nTokenStackSize; + nTokenStackPos = sal_uInt8(nTmp); + + m_nTokenIndex -= nTmp; + + // restore values + aToken = pTokenStackPos->sToken; + nTokenValue = pTokenStackPos->nTokenValue; + bTokenHasValue = pTokenStackPos->bTokenHasValue; + + return pTokenStackPos->nTokenId; +} + +template<typename T> +typename SvParser<T>::TokenStackType* SvParser<T>::GetStackPtr( short nCnt ) +{ + sal_uInt8 nCurrentPos = sal_uInt8(pTokenStackPos - pTokenStack.get()); + if( nCnt > 0 ) + { + if( nCnt >= nTokenStackSize ) + nCnt = (nTokenStackSize-1); + if( nCurrentPos + nCnt < nTokenStackSize ) + nCurrentPos = sal::static_int_cast< sal_uInt8 >(nCurrentPos + nCnt); + else + nCurrentPos = sal::static_int_cast< sal_uInt8 >( + nCurrentPos + (nCnt - nTokenStackSize)); + } + else if( nCnt < 0 ) + { + if( -nCnt >= nTokenStackSize ) + nCnt = -nTokenStackSize+1; + if( -nCnt <= nCurrentPos ) + nCurrentPos = sal::static_int_cast< sal_uInt8 >(nCurrentPos + nCnt); + else + nCurrentPos = sal::static_int_cast< sal_uInt8 >( + nCurrentPos + (nCnt + nTokenStackSize)); + } + return pTokenStack.get() + nCurrentPos; +} + +// to read asynchronous from SvStream + +template<typename T> +T SvParser<T>::GetSaveToken() const +{ + return pImplData ? pImplData->nSaveToken : static_cast<T>(0); +} + +template<typename T> +void SvParser<T>::SaveState( T nToken ) +{ + // save actual status + if( !pImplData ) + { + pImplData.reset(new SvParser_Impl<T>); + pImplData->nSaveToken = static_cast<T>(0); + } + + pImplData->nFilePos = rInput.Tell(); + pImplData->nToken = nToken; + + pImplData->aToken = aToken; + pImplData->nlLineNr = nlLineNr; + pImplData->nlLinePos = nlLinePos; + pImplData->nTokenValue= nTokenValue; + pImplData->bTokenHasValue = bTokenHasValue; + pImplData->nNextCh = nNextCh; +} + +template<typename T> +void SvParser<T>::RestoreState() +{ + // restore old status + if( !pImplData ) + return; + + if( ERRCODE_IO_PENDING == rInput.GetError() ) + rInput.ResetError(); + aToken = pImplData->aToken; + nlLineNr = pImplData->nlLineNr; + nlLinePos = pImplData->nlLinePos; + nTokenValue= pImplData->nTokenValue; + bTokenHasValue=pImplData->bTokenHasValue; + nNextCh = pImplData->nNextCh; + + pImplData->nSaveToken = pImplData->nToken; + + rInput.Seek( pImplData->nFilePos ); +} + +template<typename T> +void SvParser<T>::Continue( T ) +{ +} + +void BuildWhichTable( std::vector<sal_uInt16> &rWhichMap, + sal_uInt16 const *pWhichIds, + sal_uInt16 nWhichIds ) +{ + sal_uInt16 aNewRange[2]; + + for( sal_uInt16 nCnt = 0; nCnt < nWhichIds; ++nCnt, ++pWhichIds ) + if( *pWhichIds ) + { + aNewRange[0] = aNewRange[1] = *pWhichIds; + bool bIns = true; + + // search position + for ( sal_uInt16 nOfs = 0; rWhichMap[nOfs]; nOfs += 2 ) + { + if( *pWhichIds < rWhichMap[nOfs] - 1 ) + { + // new range before + rWhichMap.insert( rWhichMap.begin() + nOfs, aNewRange, aNewRange + 2 ); + bIns = false; + break; + } + else if( *pWhichIds == rWhichMap[nOfs] - 1 ) + { + // extend range downwards + rWhichMap[nOfs] = *pWhichIds; + bIns = false; + break; + } + else if( *pWhichIds == rWhichMap[nOfs+1] + 1 ) + { + if( rWhichMap[nOfs+2] != 0 && rWhichMap[nOfs+2] == *pWhichIds + 1 ) + { + // merge with next field + rWhichMap[nOfs+1] = rWhichMap[nOfs+3]; + rWhichMap.erase( rWhichMap.begin() + nOfs + 2, + rWhichMap.begin() + nOfs + 4 ); + } + else + // extend range upwards + rWhichMap[nOfs+1] = *pWhichIds; + bIns = false; + break; + } + } + + // append range + if( bIns ) + { + rWhichMap.insert( rWhichMap.begin() + rWhichMap.size() - 1, + aNewRange, aNewRange + 2 ); + } + } +} + + +// expanded out version of +// IMPL_LINK_NOARG( SvParser, NewDataRead, LinkParamNone*, void ) +// since it can't cope with template methods +template<typename T> +void SvParser<T>::LinkStubNewDataRead(void * instance, LinkParamNone* data) { + return static_cast<SvParser<T> *>(instance)->NewDataRead(data); +} +template<typename T> +void SvParser<T>::NewDataRead(SAL_UNUSED_PARAMETER LinkParamNone*) +{ + switch( eState ) + { + case SvParserState::Pending: + eState = SvParserState::Working; + RestoreState(); + + Continue( pImplData->nToken ); + + if( ERRCODE_IO_PENDING == rInput.GetError() ) + rInput.ResetError(); + + if( SvParserState::Pending != eState ) + ReleaseRef(); // ready otherwise! + break; + + case SvParserState::NotStarted: + case SvParserState::Working: + break; + + default: + ReleaseRef(); // ready otherwise! + break; + } +} + +template class SVT_DLLPUBLIC SvParser<int>; +template class SVT_DLLPUBLIC SvParser<HtmlTokenId>; + +/*======================================================================== + * + * SvKeyValueIterator. + * + *======================================================================*/ + +typedef std::vector<SvKeyValue> SvKeyValueList_Impl; + +struct SvKeyValueIterator::Impl +{ + SvKeyValueList_Impl maList; + sal_uInt16 mnPos; + + Impl() : mnPos(0) {} +}; + +SvKeyValueIterator::SvKeyValueIterator() : mpImpl(new Impl) {} + +SvKeyValueIterator::~SvKeyValueIterator() = default; + +bool SvKeyValueIterator::GetFirst (SvKeyValue &rKeyVal) +{ + mpImpl->mnPos = mpImpl->maList.size(); + return GetNext (rKeyVal); +} + +bool SvKeyValueIterator::GetNext (SvKeyValue &rKeyVal) +{ + if (mpImpl->mnPos > 0) + { + rKeyVal = mpImpl->maList[--mpImpl->mnPos]; + return true; + } + else + { + // Nothing to do. + return false; + } +} + +void SvKeyValueIterator::Append (const SvKeyValue &rKeyVal) +{ + mpImpl->maList.push_back(rKeyVal); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/table/cellvalueconversion.cxx b/svtools/source/table/cellvalueconversion.cxx new file mode 100644 index 000000000..2ca15c7ca --- /dev/null +++ b/svtools/source/table/cellvalueconversion.cxx @@ -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 incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 "cellvalueconversion.hxx" + +#include <com/sun/star/util/NumberFormatter.hpp> +#include <com/sun/star/util/NumberFormatsSupplier.hpp> +#include <com/sun/star/beans/XPropertySet.hpp> +#include <com/sun/star/util/Date.hpp> +#include <com/sun/star/util/Time.hpp> +#include <com/sun/star/util/DateTime.hpp> +#include <com/sun/star/util/XNumberFormatTypes.hpp> +#include <com/sun/star/util/NumberFormat.hpp> +#include <rtl/math.hxx> +#include <sal/log.hxx> +#include <tools/date.hxx> +#include <tools/time.hxx> +#include <tools/diagnose_ex.h> +#include <unotools/syslocale.hxx> +#include <i18nlangtag/languagetag.hxx> +#include <comphelper/processfactory.hxx> + +#include <memory> +#include <unordered_map> + +namespace svt +{ + + + using namespace ::com::sun::star::uno; + using ::com::sun::star::util::XNumberFormatter; + using ::com::sun::star::util::NumberFormatter; + using ::com::sun::star::util::XNumberFormatsSupplier; + using ::com::sun::star::util::NumberFormatsSupplier; + using ::com::sun::star::beans::XPropertySet; + using ::com::sun::star::lang::Locale; + using ::com::sun::star::util::DateTime; + using ::com::sun::star::util::XNumberFormatTypes; + + namespace NumberFormat = ::com::sun::star::util::NumberFormat; + + + //= helper + + namespace + { + + double lcl_convertDateToDays( sal_uInt16 const i_day, sal_uInt16 const i_month, sal_Int16 const i_year ) + { + long const nNullDateDays = ::Date::DateToDays( 1, 1, 1900 ); + long const nValueDateDays = ::Date::DateToDays( i_day, i_month, i_year ); + + return nValueDateDays - nNullDateDays; + } + + + double lcl_convertTimeToDays( long const i_hours, long const i_minutes, long const i_seconds, long const i_100thSeconds ) + { + return tools::Time( i_hours, i_minutes, i_seconds, i_100thSeconds ).GetTimeInDays(); + } + + //= CellValueConversion_Data + class StandardFormatNormalizer; + + } + + struct CellValueConversion_Data + { + typedef std::unordered_map< OUString, std::shared_ptr< StandardFormatNormalizer > > NormalizerCache; + + Reference< XNumberFormatter > xNumberFormatter; + bool bAttemptedFormatterCreation; + NormalizerCache aNormalizers; + + CellValueConversion_Data() + :xNumberFormatter() + ,bAttemptedFormatterCreation( false ) + ,aNormalizers() + { + } + }; + + + //= StandardFormatNormalizer + + namespace { + + class StandardFormatNormalizer + { + public: + /** converts the given <code>Any</code> into a <code>double</code> value to be fed into a number formatter + */ + virtual double convertToDouble( Any const & i_value ) const = 0; + + /** returns the format key to be used for formatting values + */ + sal_Int32 getFormatKey() const + { + return m_nFormatKey; + } + + protected: + StandardFormatNormalizer( Reference< XNumberFormatter > const & i_formatter, ::sal_Int32 const i_numberFormatType ) + :m_nFormatKey( 0 ) + { + try + { + ENSURE_OR_THROW( i_formatter.is(), "StandardFormatNormalizer: no formatter!" ); + Reference< XNumberFormatsSupplier > const xSupplier( i_formatter->getNumberFormatsSupplier(), UNO_SET_THROW ); + Reference< XNumberFormatTypes > const xTypes( xSupplier->getNumberFormats(), UNO_QUERY_THROW ); + m_nFormatKey = xTypes->getStandardFormat( i_numberFormatType, SvtSysLocale().GetLanguageTag().getLocale() ); + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION("svtools.table"); + } + } + + virtual ~StandardFormatNormalizer() {} + + private: + ::sal_Int32 m_nFormatKey; + }; + + + //= DoubleNormalization + + class DoubleNormalization : public StandardFormatNormalizer + { + public: + explicit DoubleNormalization( Reference< XNumberFormatter > const & i_formatter ) + :StandardFormatNormalizer( i_formatter, NumberFormat::NUMBER ) + { + } + + virtual double convertToDouble( Any const & i_value ) const override + { + double returnValue(0); + ::rtl::math::setNan( &returnValue ); + OSL_VERIFY( i_value >>= returnValue ); + return returnValue; + } + }; + + + //= IntegerNormalization + + class IntegerNormalization : public StandardFormatNormalizer + { + public: + explicit IntegerNormalization( Reference< XNumberFormatter > const & i_formatter ) + :StandardFormatNormalizer( i_formatter, NumberFormat::NUMBER ) + { + } + + virtual double convertToDouble( Any const & i_value ) const override + { + sal_Int64 value( 0 ); + OSL_VERIFY( i_value >>= value ); + return value; + } + }; + + + //= BooleanNormalization + + class BooleanNormalization : public StandardFormatNormalizer + { + public: + explicit BooleanNormalization( Reference< XNumberFormatter > const & i_formatter ) + :StandardFormatNormalizer( i_formatter, NumberFormat::LOGICAL ) + { + } + + virtual double convertToDouble( Any const & i_value ) const override + { + bool value( false ); + OSL_VERIFY( i_value >>= value ); + return value ? 1 : 0; + } + }; + + + //= DateTimeNormalization + + class DateTimeNormalization : public StandardFormatNormalizer + { + public: + explicit DateTimeNormalization( Reference< XNumberFormatter > const & i_formatter ) + :StandardFormatNormalizer( i_formatter, NumberFormat::DATETIME ) + { + } + + virtual double convertToDouble( Any const & i_value ) const override + { + double returnValue(0); + ::rtl::math::setNan( &returnValue ); + + // extract actual UNO value + DateTime aDateTimeValue; + ENSURE_OR_RETURN( i_value >>= aDateTimeValue, "allowed for DateTime values only", returnValue ); + + // date part + returnValue = lcl_convertDateToDays( aDateTimeValue.Day, aDateTimeValue.Month, aDateTimeValue.Year ); + + // time part + returnValue += lcl_convertTimeToDays( + aDateTimeValue.Hours, aDateTimeValue.Minutes, aDateTimeValue.Seconds, aDateTimeValue.NanoSeconds ); + + // done + return returnValue; + } + }; + + + //= DateNormalization + + class DateNormalization : public StandardFormatNormalizer + { + public: + explicit DateNormalization( Reference< XNumberFormatter > const & i_formatter ) + :StandardFormatNormalizer( i_formatter, NumberFormat::DATE ) + { + } + + virtual double convertToDouble( Any const & i_value ) const override + { + double returnValue(0); + ::rtl::math::setNan( &returnValue ); + + // extract + css::util::Date aDateValue; + ENSURE_OR_RETURN( i_value >>= aDateValue, "allowed for Date values only", returnValue ); + + // convert + returnValue = lcl_convertDateToDays( aDateValue.Day, aDateValue.Month, aDateValue.Year ); + + // done + return returnValue; + } + }; + + + //= TimeNormalization + + class TimeNormalization : public StandardFormatNormalizer + { + public: + explicit TimeNormalization( Reference< XNumberFormatter > const & i_formatter ) + :StandardFormatNormalizer( i_formatter, NumberFormat::TIME ) + { + } + + virtual double convertToDouble( Any const & i_value ) const override + { + double returnValue(0); + ::rtl::math::setNan( &returnValue ); + + // extract + css::util::Time aTimeValue; + ENSURE_OR_RETURN( i_value >>= aTimeValue, "allowed for tools::Time values only", returnValue ); + + // convert + returnValue += lcl_convertTimeToDays( + aTimeValue.Hours, aTimeValue.Minutes, aTimeValue.Seconds, aTimeValue.NanoSeconds ); + + // done + return returnValue; + } + }; + + + //= operations + + bool lcl_ensureNumberFormatter( CellValueConversion_Data & io_data ) + { + if ( io_data.bAttemptedFormatterCreation ) + return io_data.xNumberFormatter.is(); + io_data.bAttemptedFormatterCreation = true; + + try + { + Reference< XComponentContext > xContext = ::comphelper::getProcessComponentContext(); + // a number formatter + Reference< XNumberFormatter > const xFormatter( NumberFormatter::create( xContext ), UNO_QUERY_THROW ); + + // a supplier of number formats + Locale aLocale = SvtSysLocale().GetLanguageTag().getLocale(); + + Reference< XNumberFormatsSupplier > const xSupplier = + NumberFormatsSupplier::createWithLocale( xContext, aLocale ); + + // ensure a NullDate we will assume later on + css::util::Date const aNullDate( 1, 1, 1900 ); + Reference< XPropertySet > const xFormatSettings( xSupplier->getNumberFormatSettings(), UNO_SET_THROW ); + xFormatSettings->setPropertyValue( "NullDate", makeAny( aNullDate ) ); + + // knit + xFormatter->attachNumberFormatsSupplier( xSupplier ); + + // done + io_data.xNumberFormatter = xFormatter; + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION("svtools.table"); + } + + return io_data.xNumberFormatter.is(); + } + + + bool lcl_getValueNormalizer( CellValueConversion_Data & io_data, Type const & i_valueType, + std::shared_ptr< StandardFormatNormalizer > & o_formatter ) + { + CellValueConversion_Data::NormalizerCache::const_iterator pos = io_data.aNormalizers.find( i_valueType.getTypeName() ); + if ( pos == io_data.aNormalizers.end() ) + { + // never encountered this type before + o_formatter.reset(); + + OUString const sTypeName( i_valueType.getTypeName() ); + TypeClass const eTypeClass = i_valueType.getTypeClass(); + + if ( sTypeName == ::cppu::UnoType< DateTime >::get().getTypeName() ) + { + o_formatter = std::make_shared<DateTimeNormalization>( io_data.xNumberFormatter ); + } + else if ( sTypeName == ::cppu::UnoType< css::util::Date >::get().getTypeName() ) + { + o_formatter = std::make_shared<DateNormalization>( io_data.xNumberFormatter ); + } + else if ( sTypeName == ::cppu::UnoType< css::util::Time >::get().getTypeName() ) + { + o_formatter = std::make_shared<TimeNormalization>( io_data.xNumberFormatter ); + } + else if ( sTypeName == ::cppu::UnoType< sal_Bool >::get().getTypeName() ) + { + o_formatter = std::make_shared<BooleanNormalization>( io_data.xNumberFormatter ); + } + else if ( sTypeName == ::cppu::UnoType< double >::get().getTypeName() + || sTypeName == ::cppu::UnoType< float >::get().getTypeName() + ) + { + o_formatter = std::make_shared<DoubleNormalization>( io_data.xNumberFormatter ); + } + else if ( ( eTypeClass == TypeClass_BYTE ) + || ( eTypeClass == TypeClass_SHORT ) + || ( eTypeClass == TypeClass_UNSIGNED_SHORT ) + || ( eTypeClass == TypeClass_LONG ) + || ( eTypeClass == TypeClass_UNSIGNED_LONG ) + || ( eTypeClass == TypeClass_HYPER ) + ) + { + o_formatter = std::make_shared<IntegerNormalization>( io_data.xNumberFormatter ); + } + else + { + SAL_WARN( "svtools.table", "unsupported type '" << sTypeName << "'!" ); + } + io_data.aNormalizers[ sTypeName ] = o_formatter; + } + else + o_formatter = pos->second; + + return bool(o_formatter); + } + } + + + //= CellValueConversion + + + CellValueConversion::CellValueConversion() + :m_pData( new CellValueConversion_Data ) + { + } + + + CellValueConversion::~CellValueConversion() + { + } + + + OUString CellValueConversion::convertToString( const Any& i_value ) + { + OUString sStringValue; + if ( !i_value.hasValue() ) + return sStringValue; + + if ( ! ( i_value >>= sStringValue ) ) + { + if ( lcl_ensureNumberFormatter( *m_pData ) ) + { + std::shared_ptr< StandardFormatNormalizer > pNormalizer; + if ( lcl_getValueNormalizer( *m_pData, i_value.getValueType(), pNormalizer ) ) + { + try + { + double const formatterCompliantValue = pNormalizer->convertToDouble( i_value ); + sal_Int32 const formatKey = pNormalizer->getFormatKey(); + sStringValue = m_pData->xNumberFormatter->convertNumberToString( + formatKey, formatterCompliantValue ); + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION("svtools.table"); + } + } + } + } + + return sStringValue; + } + + +} // namespace svt + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/table/cellvalueconversion.hxx b/svtools/source/table/cellvalueconversion.hxx new file mode 100644 index 000000000..3a5bb924c --- /dev/null +++ b/svtools/source/table/cellvalueconversion.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 <com/sun/star/uno/Any.hxx> + +#include <memory> + + +namespace svt +{ + + + //= CellValueConversion + + struct CellValueConversion_Data; + class CellValueConversion + { + public: + CellValueConversion(); + ~CellValueConversion(); + + OUString convertToString( const css::uno::Any& i_cellValue ); + + private: + ::std::unique_ptr< CellValueConversion_Data > m_pData; + }; + + +} // namespace svt + + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/table/defaultinputhandler.cxx b/svtools/source/table/defaultinputhandler.cxx new file mode 100644 index 000000000..6b84fbf31 --- /dev/null +++ b/svtools/source/table/defaultinputhandler.cxx @@ -0,0 +1,201 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <table/defaultinputhandler.hxx> +#include <table/tablecontrolinterface.hxx> + +#include "mousefunction.hxx" + +#include <vcl/event.hxx> +#include <osl/diagnose.h> + + +namespace svt::table +{ + + + typedef ::rtl::Reference< MouseFunction > PMouseFunction; + typedef ::std::vector< PMouseFunction > MouseFunctions; + struct DefaultInputHandler_Impl + { + PMouseFunction pActiveFunction; + MouseFunctions aMouseFunctions; + }; + + + //= DefaultInputHandler + + + DefaultInputHandler::DefaultInputHandler() + :m_pImpl( new DefaultInputHandler_Impl ) + { + m_pImpl->aMouseFunctions.push_back( new ColumnResize ); + m_pImpl->aMouseFunctions.push_back( new RowSelection ); + m_pImpl->aMouseFunctions.push_back( new ColumnSortHandler ); + } + + + DefaultInputHandler::~DefaultInputHandler() + { + } + + + namespace + { + bool lcl_delegateMouseEvent( DefaultInputHandler_Impl& i_impl, ITableControl& i_control, const MouseEvent& i_event, + FunctionResult ( MouseFunction::*i_handlerMethod )( ITableControl&, const MouseEvent& ) ) + { + if ( i_impl.pActiveFunction.is() ) + { + bool furtherHandler = false; + switch ( (i_impl.pActiveFunction.get()->*i_handlerMethod)( i_control, i_event ) ) + { + case ActivateFunction: + OSL_ENSURE( false, "lcl_delegateMouseEvent: unexpected - function already *is* active!" ); + break; + case ContinueFunction: + break; + case DeactivateFunction: + i_impl.pActiveFunction.clear(); + break; + case SkipFunction: + furtherHandler = true; + break; + } + if ( !furtherHandler ) + // handled the event + return true; + } + + // ask all other handlers + bool handled = false; + for (auto const& mouseFunction : i_impl.aMouseFunctions) + { + if (handled) + break; + if (mouseFunction == i_impl.pActiveFunction) + // we already invoked this function + continue; + + switch ( (mouseFunction.get()->*i_handlerMethod)( i_control, i_event ) ) + { + case ActivateFunction: + i_impl.pActiveFunction = mouseFunction; + handled = true; + break; + case ContinueFunction: + case DeactivateFunction: + OSL_ENSURE( false, "lcl_delegateMouseEvent: unexpected: inactive handler cannot be continued or deactivated!" ); + break; + case SkipFunction: + handled = false; + break; + } + } + return handled; + } + } + + + bool DefaultInputHandler::MouseMove( ITableControl& i_tableControl, const MouseEvent& i_event ) + { + return lcl_delegateMouseEvent( *m_pImpl, i_tableControl, i_event, &MouseFunction::handleMouseMove ); + } + + + bool DefaultInputHandler::MouseButtonDown( ITableControl& i_tableControl, const MouseEvent& i_event ) + { + return lcl_delegateMouseEvent( *m_pImpl, i_tableControl, i_event, &MouseFunction::handleMouseDown ); + } + + + bool DefaultInputHandler::MouseButtonUp( ITableControl& i_tableControl, const MouseEvent& i_event ) + { + return lcl_delegateMouseEvent( *m_pImpl, i_tableControl, i_event, &MouseFunction::handleMouseUp ); + } + + + bool DefaultInputHandler::KeyInput( ITableControl& _rControl, const KeyEvent& rKEvt ) + { + bool bHandled = false; + + const vcl::KeyCode& rKeyCode = rKEvt.GetKeyCode(); + sal_uInt16 nKeyCode = rKeyCode.GetCode(); + + struct ActionMapEntry + { + sal_uInt16 nKeyCode; + sal_uInt16 nKeyModifier; + TableControlAction eAction; + } + static const aKnownActions[] = { + { KEY_DOWN, 0, cursorDown }, + { KEY_UP, 0, cursorUp }, + { KEY_LEFT, 0, cursorLeft }, + { KEY_RIGHT, 0, cursorRight }, + { KEY_HOME, 0, cursorToLineStart }, + { KEY_END, 0, cursorToLineEnd }, + { KEY_PAGEUP, 0, cursorPageUp }, + { KEY_PAGEDOWN, 0, cursorPageDown }, + { KEY_PAGEUP, KEY_MOD1, cursorToFirstLine }, + { KEY_PAGEDOWN, KEY_MOD1, cursorToLastLine }, + { KEY_HOME, KEY_MOD1, cursorTopLeft }, + { KEY_END, KEY_MOD1, cursorBottomRight }, + { KEY_SPACE, KEY_MOD1, cursorSelectRow }, + { KEY_UP, KEY_SHIFT, cursorSelectRowUp }, + { KEY_DOWN, KEY_SHIFT, cursorSelectRowDown }, + { KEY_END, KEY_SHIFT, cursorSelectRowAreaBottom }, + { KEY_HOME, KEY_SHIFT, cursorSelectRowAreaTop }, + + { 0, 0, invalidTableControlAction } + }; + + const ActionMapEntry* pActions = aKnownActions; + for ( ; pActions->eAction != invalidTableControlAction; ++pActions ) + { + if ( ( pActions->nKeyCode == nKeyCode ) && ( pActions->nKeyModifier == rKeyCode.GetModifier() ) ) + { + bHandled = _rControl.dispatchAction( pActions->eAction ); + break; + } + } + + return bHandled; + } + + + bool DefaultInputHandler::GetFocus( ITableControl& _rControl ) + { + _rControl.showCursor(); + return false; // continue processing + } + + + bool DefaultInputHandler::LoseFocus( ITableControl& _rControl ) + { + _rControl.hideCursor(); + return false; // continue processing + } + + +} // namespace svt::table + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/table/gridtablerenderer.cxx b/svtools/source/table/gridtablerenderer.cxx new file mode 100644 index 000000000..8ab7ae182 --- /dev/null +++ b/svtools/source/table/gridtablerenderer.cxx @@ -0,0 +1,603 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 "cellvalueconversion.hxx" +#include <table/gridtablerenderer.hxx> +#include <table/tablesort.hxx> + +#include <com/sun/star/graphic/XGraphic.hpp> + +#include <tools/debug.hxx> +#include <tools/diagnose_ex.h> +#include <vcl/window.hxx> +#include <vcl/image.hxx> +#include <vcl/virdev.hxx> +#include <vcl/decoview.hxx> +#include <vcl/settings.hxx> + + +namespace svt::table +{ + using ::css::uno::Any; + using ::css::uno::Reference; + using ::css::uno::UNO_QUERY; + using ::css::uno::XInterface; + using ::css::uno::TypeClass_INTERFACE; + using ::css::graphic::XGraphic; + using ::css::style::HorizontalAlignment; + using ::css::style::HorizontalAlignment_CENTER; + using ::css::style::HorizontalAlignment_RIGHT; + using ::css::style::VerticalAlignment; + using ::css::style::VerticalAlignment_MIDDLE; + using ::css::style::VerticalAlignment_BOTTOM; + + + //= CachedSortIndicator + + namespace { + + class CachedSortIndicator + { + public: + CachedSortIndicator() + : m_lastHeaderHeight( 0 ) + , m_lastArrowColor( COL_TRANSPARENT ) + { + } + + BitmapEx const & getBitmapFor(vcl::RenderContext const & i_device, long const i_headerHeight, + StyleSettings const & i_style, bool const i_sortAscending); + + private: + long m_lastHeaderHeight; + Color m_lastArrowColor; + BitmapEx m_sortAscending; + BitmapEx m_sortDescending; + }; + + } + + BitmapEx const & CachedSortIndicator::getBitmapFor(vcl::RenderContext const& i_device, long const i_headerHeight, + StyleSettings const & i_style, bool const i_sortAscending ) + { + BitmapEx& rBitmap(i_sortAscending ? m_sortAscending : m_sortDescending); + if (!rBitmap || (i_headerHeight != m_lastHeaderHeight) || (i_style.GetActiveColor() != m_lastArrowColor)) + { + long const nSortIndicatorWidth = 2 * i_headerHeight / 3; + long const nSortIndicatorHeight = 2 * nSortIndicatorWidth / 3; + + Point const aBitmapPos( 0, 0 ); + Size const aBitmapSize( nSortIndicatorWidth, nSortIndicatorHeight ); + ScopedVclPtrInstance< VirtualDevice > aDevice(i_device, DeviceFormat::DEFAULT, + DeviceFormat::DEFAULT); + aDevice->SetOutputSizePixel( aBitmapSize ); + + DecorationView aDecoView(aDevice.get()); + aDecoView.DrawSymbol(tools::Rectangle(aBitmapPos, aBitmapSize), + i_sortAscending ? SymbolType::SPIN_UP : SymbolType::SPIN_DOWN, + i_style.GetActiveColor()); + + rBitmap = aDevice->GetBitmapEx(aBitmapPos, aBitmapSize); + m_lastHeaderHeight = i_headerHeight; + m_lastArrowColor = i_style.GetActiveColor(); + } + return rBitmap; + } + + + //= GridTableRenderer_Impl + + struct GridTableRenderer_Impl + { + ITableModel& rModel; + RowPos nCurrentRow; + bool bUseGridLines; + CachedSortIndicator aSortIndicator; + CellValueConversion aStringConverter; + + explicit GridTableRenderer_Impl( ITableModel& _rModel ) + : rModel( _rModel ) + , nCurrentRow( ROW_INVALID ) + , bUseGridLines( true ) + , aSortIndicator( ) + , aStringConverter() + { + } + }; + + + //= helper + + namespace + { + tools::Rectangle lcl_getContentArea( GridTableRenderer_Impl const & i_impl, tools::Rectangle const & i_cellArea ) + { + tools::Rectangle aContentArea( i_cellArea ); + if ( i_impl.bUseGridLines ) + { + aContentArea.AdjustRight( -1 ); + aContentArea.AdjustBottom( -1 ); + } + return aContentArea; + } + tools::Rectangle lcl_getTextRenderingArea( tools::Rectangle const & i_contentArea ) + { + tools::Rectangle aTextArea( i_contentArea ); + aTextArea.AdjustLeft(2 ); aTextArea.AdjustRight( -2 ); + aTextArea.AdjustTop( 1 ); aTextArea.AdjustBottom( -1 ); + return aTextArea; + } + + DrawTextFlags lcl_getAlignmentTextDrawFlags( GridTableRenderer_Impl const & i_impl, ColPos const i_columnPos ) + { + DrawTextFlags nVertFlag = DrawTextFlags::Top; + VerticalAlignment const eVertAlign = i_impl.rModel.getVerticalAlign(); + switch ( eVertAlign ) + { + case VerticalAlignment_MIDDLE: nVertFlag = DrawTextFlags::VCenter; break; + case VerticalAlignment_BOTTOM: nVertFlag = DrawTextFlags::Bottom; break; + default: + break; + } + + DrawTextFlags nHorzFlag = DrawTextFlags::Left; + HorizontalAlignment const eHorzAlign = i_impl.rModel.getColumnCount() > 0 + ? i_impl.rModel.getColumnModel( i_columnPos )->getHorizontalAlign() + : HorizontalAlignment_CENTER; + switch ( eHorzAlign ) + { + case HorizontalAlignment_CENTER: nHorzFlag = DrawTextFlags::Center; break; + case HorizontalAlignment_RIGHT: nHorzFlag = DrawTextFlags::Right; break; + default: + break; + } + + return nVertFlag | nHorzFlag; + } + + } + + + //= GridTableRenderer + + + GridTableRenderer::GridTableRenderer( ITableModel& _rModel ) + :m_pImpl( new GridTableRenderer_Impl( _rModel ) ) + { + } + + + GridTableRenderer::~GridTableRenderer() + { + } + + + bool GridTableRenderer::useGridLines() const + { + return m_pImpl->bUseGridLines; + } + + + void GridTableRenderer::useGridLines( bool const i_use ) + { + m_pImpl->bUseGridLines = i_use; + } + + + namespace + { + Color lcl_getEffectiveColor(std::optional<Color> const& i_modelColor, + StyleSettings const& i_styleSettings, + Color const& (StyleSettings::*i_getDefaultColor) () const) + { + if (!!i_modelColor) + return *i_modelColor; + return (i_styleSettings.*i_getDefaultColor)(); + } + } + + + void GridTableRenderer::PaintHeaderArea(vcl::RenderContext& rRenderContext, const tools::Rectangle& _rArea, + bool _bIsColHeaderArea, bool _bIsRowHeaderArea, const StyleSettings& _rStyle) + { + OSL_PRECOND(_bIsColHeaderArea || _bIsRowHeaderArea, "GridTableRenderer::PaintHeaderArea: invalid area flags!"); + + rRenderContext.Push(PushFlags::FILLCOLOR | PushFlags::LINECOLOR); + + Color const background = lcl_getEffectiveColor(m_pImpl->rModel.getHeaderBackgroundColor(), + _rStyle, &StyleSettings::GetDialogColor); + rRenderContext.SetFillColor(background); + + rRenderContext.SetLineColor(); + rRenderContext.DrawRect(_rArea); + + // delimiter lines at bottom/right + std::optional<Color> aLineColor(m_pImpl->rModel.getLineColor()); + Color const lineColor = !aLineColor ? _rStyle.GetSeparatorColor() : *aLineColor; + rRenderContext.SetLineColor(lineColor); + rRenderContext.DrawLine(_rArea.BottomLeft(), _rArea.BottomRight()); + rRenderContext.DrawLine(_rArea.BottomRight(), _rArea.TopRight()); + + rRenderContext.Pop(); + } + + + void GridTableRenderer::PaintColumnHeader( + ColPos _nCol, + vcl::RenderContext& rRenderContext, + const tools::Rectangle& _rArea, const StyleSettings& _rStyle) + { + rRenderContext.Push(PushFlags::LINECOLOR); + + OUString sHeaderText; + PColumnModel const pColumn = m_pImpl->rModel.getColumnModel( _nCol ); + DBG_ASSERT( pColumn, "GridTableRenderer::PaintColumnHeader: invalid column model object!" ); + if ( pColumn ) + sHeaderText = pColumn->getName(); + + Color const textColor = lcl_getEffectiveColor( m_pImpl->rModel.getTextColor(), _rStyle, &StyleSettings::GetFieldTextColor ); + rRenderContext.SetTextColor(textColor); + + tools::Rectangle const aTextRect( lcl_getTextRenderingArea( lcl_getContentArea( *m_pImpl, _rArea ) ) ); + DrawTextFlags nDrawTextFlags = lcl_getAlignmentTextDrawFlags( *m_pImpl, _nCol ) | DrawTextFlags::Clip; + if (!m_pImpl->rModel.isEnabled()) + nDrawTextFlags |= DrawTextFlags::Disable; + rRenderContext.DrawText( aTextRect, sHeaderText, nDrawTextFlags ); + + std::optional<Color> const aLineColor( m_pImpl->rModel.getLineColor() ); + Color const lineColor = !aLineColor ? _rStyle.GetSeparatorColor() : *aLineColor; + rRenderContext.SetLineColor( lineColor ); + rRenderContext.DrawLine( _rArea.BottomRight(), _rArea.TopRight()); + rRenderContext.DrawLine( _rArea.BottomLeft(), _rArea.BottomRight() ); + + // draw sort indicator if the model data is sorted by the given column + ITableDataSort const * pSortAdapter = m_pImpl->rModel.getSortAdapter(); + ColumnSort aCurrentSortOrder; + if ( pSortAdapter != nullptr ) + aCurrentSortOrder = pSortAdapter->getCurrentSortOrder(); + if ( aCurrentSortOrder.nColumnPos == _nCol ) + { + long const nHeaderHeight( _rArea.GetHeight() ); + BitmapEx const aIndicatorBitmap = m_pImpl->aSortIndicator.getBitmapFor(rRenderContext, nHeaderHeight, _rStyle, + aCurrentSortOrder.eSortDirection == ColumnSortAscending); + Size const aBitmapSize( aIndicatorBitmap.GetSizePixel() ); + long const nSortIndicatorPaddingX = 2; + long const nSortIndicatorPaddingY = ( nHeaderHeight - aBitmapSize.Height() ) / 2; + + if ( nDrawTextFlags & DrawTextFlags::Right ) + { + // text is right aligned => draw the sort indicator at the left hand side + rRenderContext.DrawBitmapEx(Point(_rArea.Left() + nSortIndicatorPaddingX, _rArea.Top() + nSortIndicatorPaddingY), + aIndicatorBitmap); + } + else + { + // text is left-aligned or centered => draw the sort indicator at the right hand side + rRenderContext.DrawBitmapEx(Point(_rArea.Right() - nSortIndicatorPaddingX - aBitmapSize.Width(), nSortIndicatorPaddingY), + aIndicatorBitmap); + } + } + + rRenderContext.Pop(); + } + + + void GridTableRenderer::PrepareRow(RowPos _nRow, bool i_hasControlFocus, bool _bSelected, vcl::RenderContext& rRenderContext, + const tools::Rectangle& _rRowArea, const StyleSettings& _rStyle) + { + // remember the row for subsequent calls to the other ->ITableRenderer methods + m_pImpl->nCurrentRow = _nRow; + + rRenderContext.Push(PushFlags::FILLCOLOR | PushFlags::LINECOLOR); + + Color backgroundColor = _rStyle.GetFieldColor(); + + std::optional<Color> const aLineColor( m_pImpl->rModel.getLineColor() ); + Color lineColor = !aLineColor ? _rStyle.GetSeparatorColor() : *aLineColor; + + Color const activeSelectionBackColor = lcl_getEffectiveColor(m_pImpl->rModel.getActiveSelectionBackColor(), + _rStyle, &StyleSettings::GetHighlightColor); + if (_bSelected) + { + // selected rows use the background color from the style + backgroundColor = i_hasControlFocus + ? activeSelectionBackColor + : lcl_getEffectiveColor(m_pImpl->rModel.getInactiveSelectionBackColor(), _rStyle, &StyleSettings::GetDeactiveColor); + if (!aLineColor) + lineColor = backgroundColor; + } + else + { + std::optional< std::vector<Color> > aRowColors = m_pImpl->rModel.getRowBackgroundColors(); + if (!aRowColors) + { + // use alternating default colors + Color const fieldColor = _rStyle.GetFieldColor(); + if (_rStyle.GetHighContrastMode() || ((m_pImpl->nCurrentRow % 2) == 0)) + { + backgroundColor = fieldColor; + } + else + { + Color hilightColor = activeSelectionBackColor; + hilightColor.SetRed( 9 * ( fieldColor.GetRed() - hilightColor.GetRed() ) / 10 + hilightColor.GetRed() ); + hilightColor.SetGreen( 9 * ( fieldColor.GetGreen() - hilightColor.GetGreen() ) / 10 + hilightColor.GetGreen() ); + hilightColor.SetBlue( 9 * ( fieldColor.GetBlue() - hilightColor.GetBlue() ) / 10 + hilightColor.GetBlue() ); + backgroundColor = hilightColor; + } + } + else + { + if (aRowColors->empty()) + { + // all colors have the same background color + backgroundColor = _rStyle.GetFieldColor(); + } + else + { + backgroundColor = aRowColors->at(m_pImpl->nCurrentRow % aRowColors->size()); + } + } + } + + rRenderContext.SetLineColor(); + rRenderContext.SetFillColor(backgroundColor); + rRenderContext.DrawRect(_rRowArea); + + rRenderContext.Pop(); + } + + + void GridTableRenderer::PaintRowHeader(vcl::RenderContext& rRenderContext, + const tools::Rectangle& _rArea, const StyleSettings& _rStyle) + { + rRenderContext.Push( PushFlags::LINECOLOR | PushFlags::TEXTCOLOR ); + + std::optional<Color> const aLineColor( m_pImpl->rModel.getLineColor() ); + Color const lineColor = !aLineColor ? _rStyle.GetSeparatorColor() : *aLineColor; + rRenderContext.SetLineColor(lineColor); + rRenderContext.DrawLine(_rArea.BottomLeft(), _rArea.BottomRight()); + + Any const rowHeading( m_pImpl->rModel.getRowHeading( m_pImpl->nCurrentRow ) ); + OUString const rowTitle( m_pImpl->aStringConverter.convertToString( rowHeading ) ); + if (!rowTitle.isEmpty()) + { + Color const textColor = lcl_getEffectiveColor(m_pImpl->rModel.getHeaderTextColor(), + _rStyle, &StyleSettings::GetFieldTextColor); + rRenderContext.SetTextColor(textColor); + + tools::Rectangle const aTextRect(lcl_getTextRenderingArea(lcl_getContentArea(*m_pImpl, _rArea))); + DrawTextFlags nDrawTextFlags = lcl_getAlignmentTextDrawFlags(*m_pImpl, 0) | DrawTextFlags::Clip; + if (!m_pImpl->rModel.isEnabled()) + nDrawTextFlags |= DrawTextFlags::Disable; + // TODO: is using the horizontal alignment of the 0'th column a good idea here? This is pretty ... arbitrary .. + rRenderContext.DrawText(aTextRect, rowTitle, nDrawTextFlags); + } + + rRenderContext.Pop(); + } + + + struct GridTableRenderer::CellRenderContext + { + OutputDevice& rDevice; + tools::Rectangle const aContentArea; + StyleSettings const & rStyle; + ColPos const nColumn; + bool const bSelected; + bool const bHasControlFocus; + + CellRenderContext( OutputDevice& i_device, tools::Rectangle const & i_contentArea, + StyleSettings const & i_style, ColPos const i_column, bool const i_selected, bool const i_hasControlFocus ) + :rDevice( i_device ) + ,aContentArea( i_contentArea ) + ,rStyle( i_style ) + ,nColumn( i_column ) + ,bSelected( i_selected ) + ,bHasControlFocus( i_hasControlFocus ) + { + } + }; + + + void GridTableRenderer::PaintCell(ColPos const i_column, bool _bSelected, bool i_hasControlFocus, + vcl::RenderContext& rRenderContext, const tools::Rectangle& _rArea, const StyleSettings& _rStyle) + { + rRenderContext.Push(PushFlags::LINECOLOR | PushFlags::FILLCOLOR); + + tools::Rectangle const aContentArea(lcl_getContentArea(*m_pImpl, _rArea)); + CellRenderContext const aCellRenderContext(rRenderContext, aContentArea, _rStyle, i_column, _bSelected, i_hasControlFocus); + impl_paintCellContent(aCellRenderContext); + + if ( m_pImpl->bUseGridLines ) + { + ::std::optional< ::Color > aLineColor( m_pImpl->rModel.getLineColor() ); + ::Color lineColor = !aLineColor ? _rStyle.GetSeparatorColor() : *aLineColor; + + if ( _bSelected && !aLineColor ) + { + // if no line color is specified by the model, use the usual selection color for lines in selected cells + lineColor = i_hasControlFocus + ? lcl_getEffectiveColor( m_pImpl->rModel.getActiveSelectionBackColor(), _rStyle, &StyleSettings::GetHighlightColor ) + : lcl_getEffectiveColor( m_pImpl->rModel.getInactiveSelectionBackColor(), _rStyle, &StyleSettings::GetDeactiveColor ); + } + + rRenderContext.SetLineColor( lineColor ); + rRenderContext.DrawLine( _rArea.BottomLeft(), _rArea.BottomRight() ); + rRenderContext.DrawLine( _rArea.BottomRight(), _rArea.TopRight() ); + } + + rRenderContext.Pop(); + } + + + void GridTableRenderer::impl_paintCellImage( CellRenderContext const & i_context, Image const & i_image ) + { + Point imagePos( Point( i_context.aContentArea.Left(), i_context.aContentArea.Top() ) ); + Size imageSize = i_image.GetSizePixel(); + if ( i_context.aContentArea.GetWidth() > imageSize.Width() ) + { + const HorizontalAlignment eHorzAlign = m_pImpl->rModel.getColumnModel( i_context.nColumn )->getHorizontalAlign(); + switch ( eHorzAlign ) + { + case HorizontalAlignment_CENTER: + imagePos.AdjustX(( i_context.aContentArea.GetWidth() - imageSize.Width() ) / 2 ); + break; + case HorizontalAlignment_RIGHT: + imagePos.setX( i_context.aContentArea.Right() - imageSize.Width() ); + break; + default: + break; + } + + } + else + imageSize.setWidth( i_context.aContentArea.GetWidth() ); + + if ( i_context.aContentArea.GetHeight() > imageSize.Height() ) + { + const VerticalAlignment eVertAlign = m_pImpl->rModel.getVerticalAlign(); + switch ( eVertAlign ) + { + case VerticalAlignment_MIDDLE: + imagePos.AdjustY(( i_context.aContentArea.GetHeight() - imageSize.Height() ) / 2 ); + break; + case VerticalAlignment_BOTTOM: + imagePos.setY( i_context.aContentArea.Bottom() - imageSize.Height() ); + break; + default: + break; + } + } + else + imageSize.setHeight( i_context.aContentArea.GetHeight() - 1 ); + DrawImageFlags const nStyle = m_pImpl->rModel.isEnabled() ? DrawImageFlags::NONE : DrawImageFlags::Disable; + i_context.rDevice.DrawImage( imagePos, imageSize, i_image, nStyle ); + } + + + void GridTableRenderer::impl_paintCellContent( CellRenderContext const & i_context ) + { + Any aCellContent; + m_pImpl->rModel.getCellContent( i_context.nColumn, m_pImpl->nCurrentRow, aCellContent ); + + if ( aCellContent.getValueTypeClass() == TypeClass_INTERFACE ) + { + Reference< XInterface > const xContentInterface( aCellContent, UNO_QUERY ); + if ( !xContentInterface.is() ) + // allowed. kind of. + return; + + Reference< XGraphic > const xGraphic( aCellContent, UNO_QUERY ); + ENSURE_OR_RETURN_VOID( xGraphic.is(), "GridTableRenderer::impl_paintCellContent: only XGraphic interfaces (or NULL) are supported for painting." ); + + const Image aImage( xGraphic ); + impl_paintCellImage( i_context, aImage ); + return; + } + + const OUString sText( m_pImpl->aStringConverter.convertToString( aCellContent ) ); + impl_paintCellText( i_context, sText ); + } + + + void GridTableRenderer::impl_paintCellText( CellRenderContext const & i_context, OUString const & i_text ) + { + if ( i_context.bSelected ) + { + ::Color const textColor = i_context.bHasControlFocus + ? lcl_getEffectiveColor( m_pImpl->rModel.getActiveSelectionTextColor(), i_context.rStyle, &StyleSettings::GetHighlightTextColor ) + : lcl_getEffectiveColor( m_pImpl->rModel.getInactiveSelectionTextColor(), i_context.rStyle, &StyleSettings::GetDeactiveTextColor ); + i_context.rDevice.SetTextColor( textColor ); + } + else + { + ::Color const textColor = lcl_getEffectiveColor( m_pImpl->rModel.getTextColor(), i_context.rStyle, &StyleSettings::GetFieldTextColor ); + i_context.rDevice.SetTextColor( textColor ); + } + + tools::Rectangle const textRect( lcl_getTextRenderingArea( i_context.aContentArea ) ); + DrawTextFlags nDrawTextFlags = lcl_getAlignmentTextDrawFlags( *m_pImpl, i_context.nColumn ) | DrawTextFlags::Clip; + if ( !m_pImpl->rModel.isEnabled() ) + nDrawTextFlags |= DrawTextFlags::Disable; + i_context.rDevice.DrawText( textRect, i_text, nDrawTextFlags ); + } + + + void GridTableRenderer::ShowCellCursor( vcl::Window& _rView, const tools::Rectangle& _rCursorRect) + { + _rView.ShowFocus( _rCursorRect ); + } + + + void GridTableRenderer::HideCellCursor( vcl::Window& _rView ) + { + _rView.HideFocus(); + } + + + bool GridTableRenderer::FitsIntoCell( Any const & i_cellContent, + OutputDevice& i_targetDevice, tools::Rectangle const & i_targetArea ) const + { + if ( !i_cellContent.hasValue() ) + return true; + + if ( i_cellContent.getValueTypeClass() == TypeClass_INTERFACE ) + { + Reference< XInterface > const xContentInterface( i_cellContent, UNO_QUERY ); + if ( !xContentInterface.is() ) + return true; + + Reference< XGraphic > const xGraphic( i_cellContent, UNO_QUERY ); + if ( xGraphic.is() ) + // for the moment, assume it fits. We can always scale it down during painting ... + return true; + + OSL_ENSURE( false, "GridTableRenderer::FitsIntoCell: only XGraphic interfaces (or NULL) are supported for painting." ); + return true; + } + + OUString const sText( m_pImpl->aStringConverter.convertToString( i_cellContent ) ); + if ( sText.isEmpty() ) + return true; + + tools::Rectangle const aTargetArea( lcl_getTextRenderingArea( lcl_getContentArea( *m_pImpl, i_targetArea ) ) ); + + long const nTextHeight = i_targetDevice.GetTextHeight(); + if ( nTextHeight > aTargetArea.GetHeight() ) + return false; + + long const nTextWidth = i_targetDevice.GetTextWidth( sText ); + return nTextWidth <= aTargetArea.GetWidth(); + } + + + bool GridTableRenderer::GetFormattedCellString( Any const & i_cellValue, OUString & o_cellString ) const + { + o_cellString = m_pImpl->aStringConverter.convertToString( i_cellValue ); + + return true; + } + + +} // namespace svt::table + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/table/mousefunction.cxx b/svtools/source/table/mousefunction.cxx new file mode 100644 index 000000000..3d2986f10 --- /dev/null +++ b/svtools/source/table/mousefunction.cxx @@ -0,0 +1,276 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 "mousefunction.hxx" +#include <table/tablecontrolinterface.hxx> +#include <table/tablesort.hxx> + +#include <tools/diagnose_ex.h> +#include <vcl/window.hxx> +#include <vcl/ptrstyle.hxx> + + +namespace svt::table +{ + + + //= ColumnResize + + + FunctionResult ColumnResize::handleMouseMove( ITableControl& i_tableControl, MouseEvent const & i_event ) + { + Point const aPoint = i_event.GetPosPixel(); + + if ( m_nResizingColumn == COL_INVALID ) + { + // if we hit a column divider, change the mouse pointer accordingly + PointerStyle aNewPointer( PointerStyle::Arrow ); + TableCell const tableCell = i_tableControl.hitTest( aPoint ); + if ( ( tableCell.nRow == ROW_COL_HEADERS ) && ( tableCell.eArea == ColumnDivider ) ) + { + aNewPointer = PointerStyle::HSplit; + } + i_tableControl.setPointer( aNewPointer ); + + return SkipFunction; // TODO: is this correct? + } + + ::Size const tableSize = i_tableControl.getTableSizePixel(); + + // set proper pointer + PointerStyle aNewPointer( PointerStyle::Arrow ); + ColumnMetrics const & columnMetrics( i_tableControl.getColumnMetrics( m_nResizingColumn ) ); + if ( ( aPoint.X() > tableSize.Width() ) + || ( aPoint.X() < columnMetrics.nStartPixel ) + ) + { + aNewPointer = PointerStyle::NotAllowed; + } + else + { + aNewPointer = PointerStyle::HSplit; + } + i_tableControl.setPointer( aNewPointer ); + + // show tracking line + i_tableControl.hideTracking(); + i_tableControl.showTracking( + tools::Rectangle( + Point( aPoint.X(), 0 ), + Size( 1, tableSize.Height() ) + ), + ShowTrackFlags::Split | ShowTrackFlags::TrackWindow + ); + + return ContinueFunction; + } + + + FunctionResult ColumnResize::handleMouseDown( ITableControl& i_tableControl, MouseEvent const & i_event ) + { + if ( m_nResizingColumn != COL_INVALID ) + { + OSL_ENSURE( false, "ColumnResize::handleMouseDown: suspicious: MouseButtonDown while still tracking?" ); + return ContinueFunction; + } + + TableCell const tableCell( i_tableControl.hitTest( i_event.GetPosPixel() ) ); + if ( tableCell.nRow == ROW_COL_HEADERS ) + { + if ( ( tableCell.nColumn != COL_INVALID ) + && ( tableCell.eArea == ColumnDivider ) + ) + { + m_nResizingColumn = tableCell.nColumn; + i_tableControl.captureMouse(); + return ActivateFunction; + } + } + + return SkipFunction; + } + + + FunctionResult ColumnResize::handleMouseUp( ITableControl& i_tableControl, MouseEvent const & i_event ) + { + if ( m_nResizingColumn == COL_INVALID ) + return SkipFunction; + + Point const aPoint = i_event.GetPosPixel(); + + i_tableControl.hideTracking(); + PColumnModel const pColumn = i_tableControl.getModel()->getColumnModel( m_nResizingColumn ); + long const maxWidthLogical = pColumn->getMaxWidth(); + long const minWidthLogical = pColumn->getMinWidth(); + + // new position of mouse + long const requestedEnd = aPoint.X(); + + // old position of right border + long const oldEnd = i_tableControl.getColumnMetrics( m_nResizingColumn ).nEndPixel; + + // position of left border if cursor in the to-be-resized column + long const columnStart = i_tableControl.getColumnMetrics( m_nResizingColumn ).nStartPixel; + long const requestedWidth = requestedEnd - columnStart; + // TODO: this is not correct, strictly: It assumes that the mouse was pressed exactly on the "end" pos, + // but for a while now, we have relaxed this, and allow clicking a few pixels aside, too + + if ( requestedEnd >= columnStart ) + { + long requestedWidthLogical = i_tableControl.pixelWidthToAppFont( requestedWidth ); + // respect column width limits + if ( oldEnd > requestedEnd ) + { + // column has become smaller, check against minimum width + if ( ( minWidthLogical != 0 ) && ( requestedWidthLogical < minWidthLogical ) ) + requestedWidthLogical = minWidthLogical; + } + else if ( oldEnd < requestedEnd ) + { + // column has become larger, check against max width + if ( ( maxWidthLogical != 0 ) && ( requestedWidthLogical >= maxWidthLogical ) ) + requestedWidthLogical = maxWidthLogical; + } + pColumn->setWidth( requestedWidthLogical ); + i_tableControl.invalidate( TableArea::All ); + } + + i_tableControl.setPointer( PointerStyle::Arrow ); + i_tableControl.releaseMouse(); + + m_nResizingColumn = COL_INVALID; + return DeactivateFunction; + } + + + //= RowSelection + + + FunctionResult RowSelection::handleMouseMove( ITableControl&, MouseEvent const & ) + { + return SkipFunction; + } + + + FunctionResult RowSelection::handleMouseDown( ITableControl& i_tableControl, MouseEvent const & i_event ) + { + bool handled = false; + + TableCell const tableCell( i_tableControl.hitTest( i_event.GetPosPixel() ) ); + if ( tableCell.nRow >= 0 ) + { + if ( i_tableControl.getSelEngine()->GetSelectionMode() == SelectionMode::NONE ) + { + i_tableControl.activateCell( tableCell.nColumn, tableCell.nRow ); + handled = true; + } + else + { + handled = i_tableControl.getSelEngine()->SelMouseButtonDown( i_event ); + } + } + + if ( handled ) + m_bActive = true; + return handled ? ActivateFunction : SkipFunction; + } + + + FunctionResult RowSelection::handleMouseUp( ITableControl& i_tableControl, MouseEvent const & i_event ) + { + TableCell const tableCell = i_tableControl.hitTest( i_event.GetPosPixel() ); + if ( tableCell.nRow >= 0 ) + { + if ( i_tableControl.getSelEngine()->GetSelectionMode() != SelectionMode::NONE ) + { + i_tableControl.getSelEngine()->SelMouseButtonUp( i_event ); + } + } + if ( m_bActive ) + { + m_bActive = false; + return DeactivateFunction; + } + return SkipFunction; + } + + + //= ColumnSortHandler + + + FunctionResult ColumnSortHandler::handleMouseMove( ITableControl&, MouseEvent const & ) + { + return SkipFunction; + } + + + FunctionResult ColumnSortHandler::handleMouseDown( ITableControl& i_tableControl, MouseEvent const & i_event ) + { + if ( m_nActiveColumn != COL_INVALID ) + { + OSL_ENSURE( false, "ColumnSortHandler::handleMouseDown: called while already active - suspicious!" ); + return ContinueFunction; + } + + if ( i_tableControl.getModel()->getSortAdapter() == nullptr ) + // no sorting support at the model + return SkipFunction; + + TableCell const tableCell( i_tableControl.hitTest( i_event.GetPosPixel() ) ); + if ( ( tableCell.nRow != ROW_COL_HEADERS ) || ( tableCell.nColumn < 0 ) ) + return SkipFunction; + + // TODO: ensure the column header is rendered in some special way, indicating its current state + + m_nActiveColumn = tableCell.nColumn; + return ActivateFunction; + } + + + FunctionResult ColumnSortHandler::handleMouseUp( ITableControl& i_tableControl, MouseEvent const & i_event ) + { + if ( m_nActiveColumn == COL_INVALID ) + return SkipFunction; + + TableCell const tableCell( i_tableControl.hitTest( i_event.GetPosPixel() ) ); + if ( ( tableCell.nRow == ROW_COL_HEADERS ) && ( tableCell.nColumn == m_nActiveColumn ) ) + { + ITableDataSort* pSort = i_tableControl.getModel()->getSortAdapter(); + ENSURE_OR_RETURN( pSort != nullptr, "ColumnSortHandler::handleMouseUp: somebody is mocking with us!", DeactivateFunction ); + // in handleMousButtonDown, the model claimed to have sort support ... + + ColumnSortDirection eSortDirection = ColumnSortAscending; + ColumnSort const aCurrentSort = pSort->getCurrentSortOrder(); + if ( aCurrentSort.nColumnPos == m_nActiveColumn ) + // invert existing sort order + eSortDirection = ( aCurrentSort.eSortDirection == ColumnSortAscending ) ? ColumnSortDescending : ColumnSortAscending; + + pSort->sortByColumn( m_nActiveColumn, eSortDirection ); + } + + m_nActiveColumn = COL_INVALID; + return DeactivateFunction; + } + + +} // namespace svt::table + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/table/mousefunction.hxx b/svtools/source/table/mousefunction.hxx new file mode 100644 index 000000000..beadbcf59 --- /dev/null +++ b/svtools/source/table/mousefunction.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 <table/tabletypes.hxx> + +#include <salhelper/simplereferenceobject.hxx> + +class MouseEvent; + + +namespace svt::table +{ + + + class ITableControl; + + + //= FunctionResult + + enum FunctionResult + { + ActivateFunction, + ContinueFunction, + DeactivateFunction, + + SkipFunction + }; + + + //= MouseFunction + + class MouseFunction : public ::salhelper::SimpleReferenceObject + { + public: + MouseFunction() {} + MouseFunction(const MouseFunction&) = delete; + MouseFunction& operator=(const MouseFunction&) = delete; + virtual FunctionResult handleMouseMove( ITableControl& i_tableControl, MouseEvent const & i_event ) = 0; + virtual FunctionResult handleMouseDown( ITableControl& i_tableControl, MouseEvent const & i_event ) = 0; + virtual FunctionResult handleMouseUp( ITableControl& i_tableControl, MouseEvent const & i_event ) = 0; + + protected: + virtual ~MouseFunction() override { } + }; + + + //= ColumnResize + + class ColumnResize : public MouseFunction + { + public: + ColumnResize() + :m_nResizingColumn( COL_INVALID ) + { + } + + public: + // MouseFunction + virtual FunctionResult handleMouseMove( ITableControl& i_tableControl, MouseEvent const & i_event ) override; + virtual FunctionResult handleMouseDown( ITableControl& i_tableControl, MouseEvent const & i_event ) override; + virtual FunctionResult handleMouseUp( ITableControl& i_tableControl, MouseEvent const & i_event ) override; + + private: + ColPos m_nResizingColumn; + }; + + + //= RowSelection + + class RowSelection : public MouseFunction + { + public: + RowSelection() + :m_bActive( false ) + { + } + + public: + // MouseFunction + virtual FunctionResult handleMouseMove( ITableControl& i_tableControl, MouseEvent const & i_event ) override; + virtual FunctionResult handleMouseDown( ITableControl& i_tableControl, MouseEvent const & i_event ) override; + virtual FunctionResult handleMouseUp( ITableControl& i_tableControl, MouseEvent const & i_event ) override; + + private: + bool m_bActive; + }; + + + //= ColumnSortHandler + + class ColumnSortHandler : public MouseFunction + { + public: + ColumnSortHandler() + :m_nActiveColumn( COL_INVALID ) + { + } + + public: + // MouseFunction + virtual FunctionResult handleMouseMove( ITableControl& i_tableControl, MouseEvent const & i_event ) override; + virtual FunctionResult handleMouseDown( ITableControl& i_tableControl, MouseEvent const & i_event ) override; + virtual FunctionResult handleMouseUp( ITableControl& i_tableControl, MouseEvent const & i_event ) override; + + private: + ColPos m_nActiveColumn; + }; + + +} // namespace svt::table + + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/table/tablecontrol.cxx b/svtools/source/table/tablecontrol.cxx new file mode 100644 index 000000000..ce88591a5 --- /dev/null +++ b/svtools/source/table/tablecontrol.cxx @@ -0,0 +1,646 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <table/tablecontrol.hxx> + +#include "tablecontrol_impl.hxx" +#include "tabledatawindow.hxx" + +#include <com/sun/star/accessibility/AccessibleStateType.hpp> +#include <com/sun/star/accessibility/AccessibleEventId.hpp> + +#include <sal/log.hxx> +#include <tools/diagnose_ex.h> +#include <unotools/accessiblestatesethelper.hxx> +#include <vcl/settings.hxx> +#include <vcl/vclevent.hxx> + +using namespace ::com::sun::star::uno; +using ::com::sun::star::accessibility::XAccessible; +using namespace ::com::sun::star::accessibility; +using namespace ::com::sun::star::lang; +using namespace utl; + +namespace svt::table +{ + + + namespace AccessibleEventId = ::com::sun::star::accessibility::AccessibleEventId; + + + //= TableControl + + + TableControl::TableControl( vcl::Window* _pParent, WinBits _nStyle ) + :Control( _pParent, _nStyle ) + ,m_pImpl( std::make_shared<TableControl_Impl>( *this ) ) + { + TableDataWindow& rDataWindow = m_pImpl->getDataWindow(); + rDataWindow.SetSelectHdl( LINK( this, TableControl, ImplSelectHdl ) ); + + // by default, use the background as determined by the style settings + const Color aWindowColor( GetSettings().GetStyleSettings().GetFieldColor() ); + SetBackground( Wallpaper( aWindowColor ) ); + SetFillColor( aWindowColor ); + + SetCompoundControl( true ); + } + + + TableControl::~TableControl() + { + disposeOnce(); + } + + void TableControl::dispose() + { + CallEventListeners( VclEventId::ObjectDying ); + + m_pImpl->setModel( PTableModel() ); + m_pImpl->disposeAccessible(); + m_pImpl.reset(); + Control::dispose(); + } + + + void TableControl::GetFocus() + { + if ( !m_pImpl || !m_pImpl->getInputHandler()->GetFocus( *m_pImpl ) ) + Control::GetFocus(); + } + + + void TableControl::LoseFocus() + { + if ( !m_pImpl || !m_pImpl->getInputHandler()->LoseFocus( *m_pImpl ) ) + Control::LoseFocus(); + } + + + void TableControl::KeyInput( const KeyEvent& rKEvt ) + { + if ( !m_pImpl->getInputHandler()->KeyInput( *m_pImpl, rKEvt ) ) + Control::KeyInput( rKEvt ); + else + { + if ( m_pImpl->isAccessibleAlive() ) + { + m_pImpl->commitCellEvent( AccessibleEventId::STATE_CHANGED, + makeAny( AccessibleStateType::FOCUSED ), + Any() + ); + // Huh? What the heck? Why do we unconditionally notify a STATE_CHANGE/FOCUSED after each and every + // (handled) key stroke? + + m_pImpl->commitTableEvent( AccessibleEventId::ACTIVE_DESCENDANT_CHANGED, + Any(), + Any() + ); + // ditto: Why do we notify this unconditionally? We should find the right place to notify the + // ACTIVE_DESCENDANT_CHANGED event. + // Also, we should check if STATE_CHANGED/FOCUSED is really necessary: finally, the children are + // transient, aren't they? + } + } + } + + + void TableControl::StateChanged( StateChangedType i_nStateChange ) + { + Control::StateChanged( i_nStateChange ); + + // forward certain settings to the data window + switch ( i_nStateChange ) + { + case StateChangedType::ControlFocus: + m_pImpl->invalidateSelectedRows(); + break; + + case StateChangedType::ControlBackground: + if ( IsControlBackground() ) + getDataWindow().SetControlBackground( GetControlBackground() ); + else + getDataWindow().SetControlBackground(); + break; + + case StateChangedType::ControlForeground: + if ( IsControlForeground() ) + getDataWindow().SetControlForeground( GetControlForeground() ); + else + getDataWindow().SetControlForeground(); + break; + + case StateChangedType::ControlFont: + if ( IsControlFont() ) + getDataWindow().SetControlFont( GetControlFont() ); + else + getDataWindow().SetControlFont(); + break; + default:; + } + } + + + void TableControl::Resize() + { + Control::Resize(); + m_pImpl->onResize(); + } + + + void TableControl::SetModel( const PTableModel& _pModel ) + { + m_pImpl->setModel( _pModel ); + } + + + PTableModel TableControl::GetModel() const + { + return m_pImpl->getModel(); + } + + + sal_Int32 TableControl::GetCurrentRow() const + { + return m_pImpl->getCurrentRow(); + } + + + sal_Int32 TableControl::GetCurrentColumn() const + { + return m_pImpl->getCurrentColumn(); + } + + + void TableControl::GoTo( ColPos _nColumn, RowPos _nRow ) + { + m_pImpl->goTo( _nColumn, _nRow ); + } + + + void TableControl::GoToCell(sal_Int32 _nColPos, sal_Int32 _nRowPos) + { + m_pImpl->goTo( _nColPos, _nRowPos ); + } + + + sal_Int32 TableControl::GetSelectedRowCount() const + { + return sal_Int32( m_pImpl->getSelectedRowCount() ); + } + + + sal_Int32 TableControl::GetSelectedRowIndex( sal_Int32 const i_selectionIndex ) const + { + return m_pImpl->getSelectedRowIndex( i_selectionIndex ); + } + + + bool TableControl::IsRowSelected( sal_Int32 const i_rowIndex ) const + { + return m_pImpl->isRowSelected( i_rowIndex ); + } + + + void TableControl::SelectRow( sal_Int32 const i_rowIndex, bool const i_select ) + { + ENSURE_OR_RETURN_VOID( ( i_rowIndex >= 0 ) && ( i_rowIndex < m_pImpl->getModel()->getRowCount() ), + "TableControl::SelectRow: invalid row index!" ); + + if ( i_select ) + { + if ( !m_pImpl->markRowAsSelected( i_rowIndex ) ) + // nothing to do + return; + } + else + { + m_pImpl->markRowAsDeselected( i_rowIndex ); + } + + m_pImpl->invalidateRowRange( i_rowIndex, i_rowIndex ); + Select(); + } + + + void TableControl::SelectAllRows( bool const i_select ) + { + if ( i_select ) + { + if ( !m_pImpl->markAllRowsAsSelected() ) + // nothing to do + return; + } + else + { + if ( !m_pImpl->markAllRowsAsDeselected() ) + // nothing to do + return; + } + + + Invalidate(); + // TODO: can't we do better than this, and invalidate only the rows which changed? + Select(); + } + + + ITableControl& TableControl::getTableControlInterface() + { + return *m_pImpl; + } + + + SelectionEngine* TableControl::getSelEngine() + { + return m_pImpl->getSelEngine(); + } + + + vcl::Window& TableControl::getDataWindow() + { + return m_pImpl->getDataWindow(); + } + + + Reference< XAccessible > TableControl::CreateAccessible() + { + vcl::Window* pParent = GetAccessibleParentWindow(); + ENSURE_OR_RETURN( pParent, "TableControl::CreateAccessible - parent not found", nullptr ); + + return m_pImpl->getAccessible( *pParent ); + } + + + Reference<XAccessible> TableControl::CreateAccessibleControl( sal_Int32 ) + { + SAL_WARN( "svtools", "TableControl::CreateAccessibleControl: to be overwritten!" ); + return nullptr; + } + + + OUString TableControl::GetAccessibleObjectName( vcl::table::AccessibleTableControlObjType eObjType, sal_Int32 _nRow, sal_Int32 _nCol) const + { + OUString aRetText; + //Window* pWin; + switch( eObjType ) + { + case vcl::table::TCTYPE_GRIDCONTROL: + aRetText = "Grid control"; + break; + case vcl::table::TCTYPE_TABLE: + aRetText = "Grid control"; + break; + case vcl::table::TCTYPE_ROWHEADERBAR: + aRetText = "RowHeaderBar"; + break; + case vcl::table::TCTYPE_COLUMNHEADERBAR: + aRetText = "ColumnHeaderBar"; + break; + case vcl::table::TCTYPE_TABLECELL: + //the name of the cell consists of column name and row name if defined + //if the name is equal to cell content, it'll be read twice + if(GetModel()->hasColumnHeaders()) + { + aRetText = GetColumnName(_nCol) + " , "; + } + if(GetModel()->hasRowHeaders()) + { + aRetText += GetRowName(_nRow) + " , "; + } + //aRetText = GetAccessibleCellText(_nRow, _nCol); + break; + case vcl::table::TCTYPE_ROWHEADERCELL: + aRetText = GetRowName(_nRow); + break; + case vcl::table::TCTYPE_COLUMNHEADERCELL: + aRetText = GetColumnName(_nCol); + break; + default: + OSL_FAIL("GridControl::GetAccessibleName: invalid enum!"); + } + return aRetText; + } + + + OUString TableControl::GetAccessibleObjectDescription( vcl::table::AccessibleTableControlObjType eObjType ) const + { + OUString aRetText; + switch( eObjType ) + { + case vcl::table::TCTYPE_GRIDCONTROL: + aRetText = "Grid control description"; + break; + case vcl::table::TCTYPE_TABLE: + aRetText = "TABLE description"; + break; + case vcl::table::TCTYPE_ROWHEADERBAR: + aRetText = "ROWHEADERBAR description"; + break; + case vcl::table::TCTYPE_COLUMNHEADERBAR: + aRetText = "COLUMNHEADERBAR description"; + break; + case vcl::table::TCTYPE_TABLECELL: + // the description of the cell consists of column name and row name if defined + // if the name is equal to cell content, it'll be read twice + if ( GetModel()->hasColumnHeaders() ) + { + aRetText = GetColumnName( GetCurrentColumn() ) + " , "; + } + if ( GetModel()->hasRowHeaders() ) + { + aRetText += GetRowName( GetCurrentRow() ); + } + break; + case vcl::table::TCTYPE_ROWHEADERCELL: + aRetText = "ROWHEADERCELL description"; + break; + case vcl::table::TCTYPE_COLUMNHEADERCELL: + aRetText = "COLUMNHEADERCELL description"; + break; + } + return aRetText; + } + + + OUString TableControl::GetRowName( sal_Int32 _nIndex) const + { + OUString sRowName; + GetModel()->getRowHeading( _nIndex ) >>= sRowName; + return sRowName; + } + + + OUString TableControl::GetColumnName( sal_Int32 _nIndex) const + { + return GetModel()->getColumnModel(_nIndex)->getName(); + } + + + OUString TableControl::GetAccessibleCellText( sal_Int32 _nRowPos, sal_Int32 _nColPos) const + { + return m_pImpl->getCellContentAsString( _nRowPos, _nColPos ); + } + + + void TableControl::FillAccessibleStateSet( + ::utl::AccessibleStateSetHelper& rStateSet, + vcl::table::AccessibleTableControlObjType eObjType ) const + { + switch( eObjType ) + { + case vcl::table::TCTYPE_GRIDCONTROL: + case vcl::table::TCTYPE_TABLE: + + rStateSet.AddState( AccessibleStateType::FOCUSABLE ); + + if ( m_pImpl->getSelEngine()->GetSelectionMode() == SelectionMode::Multiple ) + rStateSet.AddState( AccessibleStateType::MULTI_SELECTABLE); + + if ( HasChildPathFocus() ) + rStateSet.AddState( AccessibleStateType::FOCUSED ); + + if ( IsActive() ) + rStateSet.AddState( AccessibleStateType::ACTIVE ); + + if ( m_pImpl->getDataWindow().IsEnabled() ) + { + rStateSet.AddState( AccessibleStateType::ENABLED ); + rStateSet.AddState( AccessibleStateType::SENSITIVE ); + } + + if ( IsReallyVisible() ) + rStateSet.AddState( AccessibleStateType::VISIBLE ); + + if ( eObjType == vcl::table::TCTYPE_TABLE ) + rStateSet.AddState( AccessibleStateType::MANAGES_DESCENDANTS ); + break; + + case vcl::table::TCTYPE_ROWHEADERBAR: + rStateSet.AddState( AccessibleStateType::VISIBLE ); + rStateSet.AddState( AccessibleStateType::MANAGES_DESCENDANTS ); + break; + + case vcl::table::TCTYPE_COLUMNHEADERBAR: + rStateSet.AddState( AccessibleStateType::VISIBLE ); + rStateSet.AddState( AccessibleStateType::MANAGES_DESCENDANTS ); + break; + + case vcl::table::TCTYPE_TABLECELL: + { + rStateSet.AddState( AccessibleStateType::FOCUSABLE ); + if ( HasChildPathFocus() ) + rStateSet.AddState( AccessibleStateType::FOCUSED ); + rStateSet.AddState( AccessibleStateType::ACTIVE ); + rStateSet.AddState( AccessibleStateType::TRANSIENT ); + rStateSet.AddState( AccessibleStateType::SELECTABLE); + rStateSet.AddState( AccessibleStateType::VISIBLE ); + rStateSet.AddState( AccessibleStateType::SHOWING ); + if ( IsRowSelected( GetCurrentRow() ) ) + // Hmm? Wouldn't we expect the affected row to be a parameter to this function? + rStateSet.AddState( AccessibleStateType::SELECTED ); + } + break; + + case vcl::table::TCTYPE_ROWHEADERCELL: + rStateSet.AddState( AccessibleStateType::VISIBLE ); + rStateSet.AddState( AccessibleStateType::TRANSIENT ); + break; + + case vcl::table::TCTYPE_COLUMNHEADERCELL: + rStateSet.AddState( AccessibleStateType::VISIBLE ); + break; + } + } + + + void TableControl::commitCellEventIfAccessibleAlive( sal_Int16 const i_eventID, const Any& i_newValue, const Any& i_oldValue ) + { + if ( m_pImpl->isAccessibleAlive() ) + m_pImpl->commitCellEvent( i_eventID, i_newValue, i_oldValue ); + } + + + void TableControl::commitTableEventIfAccessibleAlive( sal_Int16 const i_eventID, const Any& i_newValue, const Any& i_oldValue ) + { + if ( m_pImpl->isAccessibleAlive() ) + m_pImpl->commitTableEvent( i_eventID, i_newValue, i_oldValue ); + } + + + tools::Rectangle TableControl::GetWindowExtentsRelative( vcl::Window *pRelativeWindow ) const + { + return Control::GetWindowExtentsRelative( pRelativeWindow ); + } + + + void TableControl::GrabFocus() + { + Control::GrabFocus(); + } + + + Reference< XAccessible > TableControl::GetAccessible() + { + return Control::GetAccessible(); + } + + + vcl::Window* TableControl::GetAccessibleParentWindow() const + { + return Control::GetAccessibleParentWindow(); + } + + + vcl::Window* TableControl::GetWindowInstance() + { + return this; + } + + + bool TableControl::HasRowHeader() + { + return GetModel()->hasRowHeaders(); + } + + + bool TableControl::HasColHeader() + { + return GetModel()->hasColumnHeaders(); + } + + + sal_Int32 TableControl::GetAccessibleControlCount() const + { + // TC_TABLE is always defined, no matter whether empty or not + sal_Int32 count = 1; + if ( GetModel()->hasRowHeaders() ) + ++count; + if ( GetModel()->hasColumnHeaders() ) + ++count; + return count; + } + + + bool TableControl::ConvertPointToControlIndex( sal_Int32& _rnIndex, const Point& _rPoint ) + { + sal_Int32 nRow = m_pImpl->getRowAtPoint( _rPoint ); + sal_Int32 nCol = m_pImpl->getColAtPoint( _rPoint ); + _rnIndex = nRow * GetColumnCount() + nCol; + return nRow >= 0; + } + + + long TableControl::GetRowCount() const + { + return GetModel()->getRowCount(); + } + + + long TableControl::GetColumnCount() const + { + return GetModel()->getColumnCount(); + } + + + bool TableControl::ConvertPointToCellAddress( sal_Int32& _rnRow, sal_Int32& _rnColPos, const Point& _rPoint ) + { + _rnRow = m_pImpl->getRowAtPoint( _rPoint ); + _rnColPos = m_pImpl->getColAtPoint( _rPoint ); + return _rnRow >= 0; + } + + + void TableControl::FillAccessibleStateSetForCell( ::utl::AccessibleStateSetHelper& _rStateSet, sal_Int32 _nRow, sal_uInt16 ) const + { + if ( IsRowSelected( _nRow ) ) + _rStateSet.AddState( AccessibleStateType::SELECTED ); + if ( HasChildPathFocus() ) + _rStateSet.AddState( AccessibleStateType::FOCUSED ); + else // only transient when column is not focused + _rStateSet.AddState( AccessibleStateType::TRANSIENT ); + + _rStateSet.AddState( AccessibleStateType::VISIBLE ); + _rStateSet.AddState( AccessibleStateType::SHOWING ); + _rStateSet.AddState( AccessibleStateType::ENABLED ); + _rStateSet.AddState( AccessibleStateType::SENSITIVE ); + _rStateSet.AddState( AccessibleStateType::ACTIVE ); + } + + + tools::Rectangle TableControl::GetFieldCharacterBounds(sal_Int32,sal_Int32,sal_Int32 nIndex) + { + return GetCharacterBounds(nIndex); + } + + + sal_Int32 TableControl::GetFieldIndexAtPoint(sal_Int32,sal_Int32,const Point& _rPoint) + { + return GetIndexForPoint(_rPoint); + } + + + tools::Rectangle TableControl::calcHeaderRect(bool _bIsColumnBar ) + { + return m_pImpl->calcHeaderRect( !_bIsColumnBar ); + } + + + tools::Rectangle TableControl::calcHeaderCellRect( bool _bIsColumnBar, sal_Int32 nPos ) + { + return m_pImpl->calcHeaderCellRect( _bIsColumnBar, nPos ); + } + + + tools::Rectangle TableControl::calcTableRect() + { + return m_pImpl->calcTableRect(); + } + + + tools::Rectangle TableControl::calcCellRect( sal_Int32 _nRowPos, sal_Int32 _nColPos ) + { + return m_pImpl->calcCellRect( _nRowPos, _nColPos ); + } + + + IMPL_LINK_NOARG(TableControl, ImplSelectHdl, LinkParamNone*, void) + { + Select(); + } + + + void TableControl::Select() + { + ImplCallEventListenersAndHandler( VclEventId::TableRowSelect, nullptr ); + + if ( m_pImpl->isAccessibleAlive() ) + { + m_pImpl->commitAccessibleEvent( AccessibleEventId::SELECTION_CHANGED ); + + m_pImpl->commitTableEvent( AccessibleEventId::ACTIVE_DESCENDANT_CHANGED, Any(), Any() ); + // TODO: why do we notify this when the *selection* changed? Shouldn't we find a better place for this, + // actually, when the active descendant, i.e. the current cell, *really* changed? + } + } + +} // namespace svt::table + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/table/tablecontrol_impl.cxx b/svtools/source/table/tablecontrol_impl.cxx new file mode 100644 index 000000000..b4cf55917 --- /dev/null +++ b/svtools/source/table/tablecontrol_impl.cxx @@ -0,0 +1,2553 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <table/tablecontrol.hxx> +#include <table/defaultinputhandler.hxx> +#include <table/tablemodel.hxx> + +#include "tabledatawindow.hxx" +#include "tablecontrol_impl.hxx" +#include "tablegeometry.hxx" + +#include <com/sun/star/accessibility/XAccessible.hpp> +#include <com/sun/star/accessibility/AccessibleTableModelChange.hpp> +#include <com/sun/star/accessibility/AccessibleEventId.hpp> +#include <com/sun/star/accessibility/AccessibleTableModelChangeType.hpp> + +#include <comphelper/flagguard.hxx> +#include <vcl/accessiblefactory.hxx> +#include <vcl/scrbar.hxx> +#include <vcl/seleng.hxx> +#include <vcl/settings.hxx> +#include <vcl/image.hxx> +#include <tools/diagnose_ex.h> +#include <tools/debug.hxx> + +#include <cstdlib> +#include <numeric> + +#define MIN_COLUMN_WIDTH_PIXEL 4 + + +namespace svt::table +{ + + + using ::com::sun::star::accessibility::AccessibleTableModelChange; + using ::com::sun::star::uno::makeAny; + using ::com::sun::star::uno::Any; + using ::com::sun::star::accessibility::XAccessible; + using ::com::sun::star::uno::Reference; + + namespace AccessibleEventId = ::com::sun::star::accessibility::AccessibleEventId; + namespace AccessibleTableModelChangeType = ::com::sun::star::accessibility::AccessibleTableModelChangeType; + + + //= SuppressCursor + + namespace { + + class SuppressCursor + { + private: + ITableControl& m_rTable; + + public: + explicit SuppressCursor( ITableControl& _rTable ) + :m_rTable( _rTable ) + { + m_rTable.hideCursor(); + } + ~SuppressCursor() + { + m_rTable.showCursor(); + } + }; + + + //= EmptyTableModel + + /** default implementation of an ->ITableModel, used as fallback when no + real model is present + + Instances of this class are static in any way, and provide the least + necessary default functionality for a table model. + */ + class EmptyTableModel : public ITableModel + { + public: + EmptyTableModel() + { + } + + // ITableModel overridables + virtual TableSize getColumnCount() const override + { + return 0; + } + virtual TableSize getRowCount() const override + { + return 0; + } + virtual bool hasColumnHeaders() const override + { + return false; + } + virtual bool hasRowHeaders() const override + { + return false; + } + virtual PColumnModel getColumnModel( ColPos ) override + { + OSL_FAIL( "EmptyTableModel::getColumnModel: invalid call!" ); + return PColumnModel(); + } + virtual PTableRenderer getRenderer() const override + { + return PTableRenderer(); + } + virtual PTableInputHandler getInputHandler() const override + { + return PTableInputHandler(); + } + virtual TableMetrics getRowHeight() const override + { + return 5 * 100; + } + virtual TableMetrics getColumnHeaderHeight() const override + { + return 0; + } + virtual TableMetrics getRowHeaderWidth() const override + { + return 0; + } + virtual ScrollbarVisibility getVerticalScrollbarVisibility() const override + { + return ScrollbarShowNever; + } + virtual ScrollbarVisibility getHorizontalScrollbarVisibility() const override + { + return ScrollbarShowNever; + } + virtual void addTableModelListener( const PTableModelListener& ) override {} + virtual void removeTableModelListener( const PTableModelListener& ) override {} + virtual ::std::optional< ::Color > getLineColor() const override + { + return ::std::optional< ::Color >(); + } + virtual ::std::optional< ::Color > getHeaderBackgroundColor() const override + { + return ::std::optional< ::Color >(); + } + virtual ::std::optional< ::Color > getHeaderTextColor() const override + { + return ::std::optional< ::Color >(); + } + virtual ::std::optional< ::Color > getActiveSelectionBackColor() const override + { + return ::std::optional< ::Color >(); + } + virtual ::std::optional< ::Color > getInactiveSelectionBackColor() const override + { + return ::std::optional< ::Color >(); + } + virtual ::std::optional< ::Color > getActiveSelectionTextColor() const override + { + return ::std::optional< ::Color >(); + } + virtual ::std::optional< ::Color > getInactiveSelectionTextColor() const override + { + return ::std::optional< ::Color >(); + } + virtual ::std::optional< ::Color > getTextColor() const override + { + return ::std::optional< ::Color >(); + } + virtual ::std::optional< ::Color > getTextLineColor() const override + { + return ::std::optional< ::Color >(); + } + virtual ::std::optional< ::std::vector< ::Color > > getRowBackgroundColors() const override + { + return ::std::optional< ::std::vector< ::Color > >(); + } + virtual css::style::VerticalAlignment getVerticalAlign() const override + { + return css::style::VerticalAlignment(0); + } + virtual ITableDataSort* getSortAdapter() override + { + return nullptr; + } + virtual bool isEnabled() const override + { + return true; + } + virtual void getCellContent( ColPos const, RowPos const, css::uno::Any& o_cellContent ) override + { + o_cellContent.clear(); + } + virtual void getCellToolTip( ColPos const, RowPos const, css::uno::Any& ) override + { + } + virtual Any getRowHeading( RowPos const ) const override + { + return Any(); + } + }; + + } + + TableControl_Impl::TableControl_Impl( TableControl& _rAntiImpl ) + :m_rAntiImpl ( _rAntiImpl ) + ,m_pModel ( std::make_shared<EmptyTableModel>() ) + ,m_pInputHandler ( ) + ,m_nRowHeightPixel ( 15 ) + ,m_nColHeaderHeightPixel( 0 ) + ,m_nRowHeaderWidthPixel ( 0 ) + ,m_nColumnCount ( 0 ) + ,m_nRowCount ( 0 ) + ,m_nCurColumn ( COL_INVALID ) + ,m_nCurRow ( ROW_INVALID ) + ,m_nLeftColumn ( 0 ) + ,m_nTopRow ( 0 ) + ,m_nCursorHidden ( 1 ) + ,m_pDataWindow ( VclPtr<TableDataWindow>::Create( *this ) ) + ,m_pVScroll ( nullptr ) + ,m_pHScroll ( nullptr ) + ,m_pScrollCorner ( nullptr ) + ,m_aSelectedRows ( ) + ,m_pTableFunctionSet ( new TableFunctionSet( this ) ) + ,m_nAnchor ( -1 ) + ,m_bUpdatingColWidths ( false ) + ,m_pAccessibleTable ( nullptr ) + { + m_pSelEngine.reset( new SelectionEngine( m_pDataWindow.get(), m_pTableFunctionSet.get() ) ); + m_pSelEngine->SetSelectionMode(SelectionMode::Single); + m_pDataWindow->SetPosPixel( Point( 0, 0 ) ); + m_pDataWindow->Show(); + } + + TableControl_Impl::~TableControl_Impl() + { + m_pVScroll.disposeAndClear(); + m_pHScroll.disposeAndClear(); + m_pScrollCorner.disposeAndClear(); + m_pDataWindow.disposeAndClear(); + m_pTableFunctionSet.reset(); + m_pSelEngine.reset(); + } + + void TableControl_Impl::setModel( const PTableModel& _pModel ) + { + SuppressCursor aHideCursor( *this ); + + if ( m_pModel ) + m_pModel->removeTableModelListener( shared_from_this() ); + + m_pModel = _pModel; + if ( !m_pModel) + m_pModel = std::make_shared<EmptyTableModel>(); + + m_pModel->addTableModelListener( shared_from_this() ); + + m_nCurRow = ROW_INVALID; + m_nCurColumn = COL_INVALID; + + // recalc some model-dependent cached info + impl_ni_updateCachedModelValues(); + impl_ni_relayout(); + + // completely invalidate + m_rAntiImpl.Invalidate(); + + // reset cursor to (0,0) + if ( m_nRowCount ) m_nCurRow = 0; + if ( m_nColumnCount ) m_nCurColumn = 0; + } + + + namespace + { + bool lcl_adjustSelectedRows( ::std::vector< RowPos >& io_selectionIndexes, RowPos const i_firstAffectedRowIndex, TableSize const i_offset ) + { + bool didChanges = false; + for (auto & selectionIndex : io_selectionIndexes) + { + if ( selectionIndex < i_firstAffectedRowIndex ) + continue; + selectionIndex += i_offset; + didChanges = true; + } + return didChanges; + } + } + + + void TableControl_Impl::rowsInserted( RowPos i_first, RowPos i_last ) + { + OSL_PRECOND( i_last >= i_first, "TableControl_Impl::rowsInserted: invalid row indexes!" ); + + TableSize const insertedRows = i_last - i_first + 1; + + // adjust selection, if necessary + bool const selectionChanged = lcl_adjustSelectedRows( m_aSelectedRows, i_first, insertedRows ); + + // adjust our cached row count + m_nRowCount = m_pModel->getRowCount(); + + // if the rows have been inserted before the current row, adjust this + if ( i_first <= m_nCurRow ) + goTo( m_nCurColumn, m_nCurRow + insertedRows ); + + // relayout, since the scrollbar need might have changed + impl_ni_relayout(); + + // notify A1YY events + if ( impl_isAccessibleAlive() ) + { + impl_commitAccessibleEvent( AccessibleEventId::TABLE_MODEL_CHANGED, + makeAny( AccessibleTableModelChange( AccessibleTableModelChangeType::INSERT, i_first, i_last, 0, m_pModel->getColumnCount() ) ) + ); + } + + // schedule repaint + invalidateRowRange( i_first, ROW_INVALID ); + + // call selection handlers, if necessary + if ( selectionChanged ) + m_rAntiImpl.Select(); + } + + + void TableControl_Impl::rowsRemoved( RowPos i_first, RowPos i_last ) + { + sal_Int32 firstRemovedRow = i_first; + sal_Int32 lastRemovedRow = i_last; + + // adjust selection, if necessary + bool selectionChanged = false; + if ( i_first == -1 ) + { + selectionChanged = markAllRowsAsDeselected(); + + firstRemovedRow = 0; + lastRemovedRow = m_nRowCount - 1; + } + else + { + ENSURE_OR_RETURN_VOID( i_last >= i_first, "TableControl_Impl::rowsRemoved: illegal indexes!" ); + + for ( sal_Int32 row = i_first; row <= i_last; ++row ) + { + if ( markRowAsDeselected( row ) ) + selectionChanged = true; + } + + if ( lcl_adjustSelectedRows( m_aSelectedRows, i_last + 1, i_first - i_last - 1 ) ) + selectionChanged = true; + } + + // adjust cached row count + m_nRowCount = m_pModel->getRowCount(); + + // adjust the current row, if it is larger than the row count now + if ( m_nCurRow >= m_nRowCount ) + { + if ( m_nRowCount > 0 ) + goTo( m_nCurColumn, m_nRowCount - 1 ); + else + { + m_nCurRow = ROW_INVALID; + m_nTopRow = 0; + } + } + else if ( m_nRowCount == 0 ) + { + m_nTopRow = 0; + } + + + // relayout, since the scrollbar need might have changed + impl_ni_relayout(); + + // notify A11Y events + if ( impl_isAccessibleAlive() ) + { + commitTableEvent( + AccessibleEventId::TABLE_MODEL_CHANGED, + makeAny( AccessibleTableModelChange( + AccessibleTableModelChangeType::DELETE, + firstRemovedRow, + lastRemovedRow, + 0, + m_pModel->getColumnCount() + ) ), + Any() + ); + } + + // schedule a repaint + invalidateRowRange( firstRemovedRow, ROW_INVALID ); + + // call selection handlers, if necessary + if ( selectionChanged ) + m_rAntiImpl.Select(); + } + + + void TableControl_Impl::columnInserted() + { + m_nColumnCount = m_pModel->getColumnCount(); + impl_ni_relayout(); + + m_rAntiImpl.Invalidate(); + } + + + void TableControl_Impl::columnRemoved() + { + m_nColumnCount = m_pModel->getColumnCount(); + + // adjust the current column, if it is larger than the column count now + if ( m_nCurColumn >= m_nColumnCount ) + { + if ( m_nColumnCount > 0 ) + goTo( m_nCurColumn - 1, m_nCurRow ); + else + m_nCurColumn = COL_INVALID; + } + + impl_ni_relayout(); + + m_rAntiImpl.Invalidate(); + } + + + void TableControl_Impl::allColumnsRemoved() + { + m_nColumnCount = m_pModel->getColumnCount(); + impl_ni_relayout(); + + m_rAntiImpl.Invalidate(); + } + + + void TableControl_Impl::cellsUpdated( RowPos const i_firstRow, RowPos const i_lastRow ) + { + invalidateRowRange( i_firstRow, i_lastRow ); + } + + + void TableControl_Impl::tableMetricsChanged() + { + impl_ni_updateCachedTableMetrics(); + impl_ni_relayout(); + m_rAntiImpl.Invalidate(); + } + + + void TableControl_Impl::impl_invalidateColumn( ColPos const i_column ) + { + tools::Rectangle const aAllCellsArea( impl_getAllVisibleCellsArea() ); + + const TableColumnGeometry aColumn( *this, aAllCellsArea, i_column ); + if ( aColumn.isValid() ) + m_rAntiImpl.Invalidate( aColumn.getRect() ); + } + + + void TableControl_Impl::columnChanged( ColPos const i_column, ColumnAttributeGroup const i_attributeGroup ) + { + ColumnAttributeGroup nGroup( i_attributeGroup ); + if ( nGroup & ColumnAttributeGroup::APPEARANCE ) + { + impl_invalidateColumn( i_column ); + nGroup &= ~ColumnAttributeGroup::APPEARANCE; + } + + if ( nGroup & ColumnAttributeGroup::WIDTH ) + { + if ( !m_bUpdatingColWidths ) + { + impl_ni_relayout( i_column ); + invalidate( TableArea::All ); + } + + nGroup &= ~ColumnAttributeGroup::WIDTH; + } + + OSL_ENSURE( ( nGroup == ColumnAttributeGroup::NONE ) || ( i_attributeGroup == ColumnAttributeGroup::ALL ), + "TableControl_Impl::columnChanged: don't know how to handle this change!" ); + } + + + tools::Rectangle TableControl_Impl::impl_getAllVisibleCellsArea() const + { + tools::Rectangle aArea( Point( 0, 0 ), Size( 0, 0 ) ); + + // determine the right-most border of the last column which is + // at least partially visible + aArea.SetRight( m_nRowHeaderWidthPixel ); + if ( !m_aColumnWidths.empty() ) + { + // the number of pixels which are scrolled out of the left hand + // side of the window + const long nScrolledOutLeft = m_nLeftColumn == 0 ? 0 : m_aColumnWidths[ m_nLeftColumn - 1 ].getEnd(); + + ColumnPositions::const_reverse_iterator loop = m_aColumnWidths.rbegin(); + do + { + aArea.SetRight( loop->getEnd() - nScrolledOutLeft + m_nRowHeaderWidthPixel ); + ++loop; + } + while ( ( loop != m_aColumnWidths.rend() ) + && ( loop->getEnd() - nScrolledOutLeft >= aArea.Right() ) + ); + } + // so far, aArea.Right() denotes the first pixel *after* the cell area + aArea.AdjustRight( -1 ); + + // determine the last row which is at least partially visible + aArea.SetBottom( + m_nColHeaderHeightPixel + + impl_getVisibleRows( true ) * m_nRowHeightPixel + - 1 ); + + return aArea; + } + + + tools::Rectangle TableControl_Impl::impl_getAllVisibleDataCellArea() const + { + tools::Rectangle aArea( impl_getAllVisibleCellsArea() ); + aArea.SetLeft( m_nRowHeaderWidthPixel ); + aArea.SetTop( m_nColHeaderHeightPixel ); + return aArea; + } + + + void TableControl_Impl::impl_ni_updateCachedTableMetrics() + { + m_nRowHeightPixel = m_rAntiImpl.LogicToPixel(Size(0, m_pModel->getRowHeight()), MapMode(MapUnit::MapAppFont)).Height(); + + m_nColHeaderHeightPixel = 0; + if ( m_pModel->hasColumnHeaders() ) + m_nColHeaderHeightPixel = m_rAntiImpl.LogicToPixel(Size(0, m_pModel->getColumnHeaderHeight()), MapMode(MapUnit::MapAppFont)).Height(); + + m_nRowHeaderWidthPixel = 0; + if ( m_pModel->hasRowHeaders() ) + m_nRowHeaderWidthPixel = m_rAntiImpl.LogicToPixel(Size(m_pModel->getRowHeaderWidth(), 0), MapMode(MapUnit::MapAppFont)).Width(); + } + + + void TableControl_Impl::impl_ni_updateCachedModelValues() + { + m_pInputHandler = m_pModel->getInputHandler(); + if ( !m_pInputHandler ) + m_pInputHandler = std::make_shared<DefaultInputHandler>(); + + m_nColumnCount = m_pModel->getColumnCount(); + if ( m_nLeftColumn >= m_nColumnCount ) + m_nLeftColumn = ( m_nColumnCount > 0 ) ? m_nColumnCount - 1 : 0; + + m_nRowCount = m_pModel->getRowCount(); + if ( m_nTopRow >= m_nRowCount ) + m_nTopRow = ( m_nRowCount > 0 ) ? m_nRowCount - 1 : 0; + + impl_ni_updateCachedTableMetrics(); + } + + + namespace + { + + /// determines whether a scrollbar is needed for the given values + bool lcl_determineScrollbarNeed( long const i_position, ScrollbarVisibility const i_visibility, + long const i_availableSpace, long const i_neededSpace ) + { + if ( i_visibility == ScrollbarShowNever ) + return false; + if ( i_visibility == ScrollbarShowAlways ) + return true; + if ( i_position > 0 ) + return true; + if ( i_availableSpace >= i_neededSpace ) + return false; + return true; + } + + + void lcl_setButtonRepeat( vcl::Window& _rWindow ) + { + AllSettings aSettings = _rWindow.GetSettings(); + MouseSettings aMouseSettings = aSettings.GetMouseSettings(); + + aMouseSettings.SetButtonRepeat( 0 ); + aSettings.SetMouseSettings( aMouseSettings ); + + _rWindow.SetSettings( aSettings, true ); + } + + + bool lcl_updateScrollbar( vcl::Window& _rParent, VclPtr<ScrollBar>& _rpBar, + bool const i_needBar, long _nVisibleUnits, + long _nPosition, long _nRange, + bool _bHorizontal, const Link<ScrollBar*,void>& _rScrollHandler ) + { + // do we currently have the scrollbar? + bool bHaveBar = _rpBar != nullptr; + + // do we need to correct the scrollbar visibility? + if ( bHaveBar && !i_needBar ) + { + if ( _rpBar->IsTracking() ) + _rpBar->EndTracking(); + _rpBar.disposeAndClear(); + } + else if ( !bHaveBar && i_needBar ) + { + _rpBar = VclPtr<ScrollBar>::Create( + + &_rParent, + WB_DRAG | ( _bHorizontal ? WB_HSCROLL : WB_VSCROLL ) + ); + _rpBar->SetScrollHdl( _rScrollHandler ); + // get some speed into the scrolling... + lcl_setButtonRepeat( *_rpBar ); + } + + if ( _rpBar ) + { + _rpBar->SetRange( Range( 0, _nRange ) ); + _rpBar->SetVisibleSize( _nVisibleUnits ); + _rpBar->SetPageSize( _nVisibleUnits ); + _rpBar->SetLineSize( 1 ); + _rpBar->SetThumbPos( _nPosition ); + _rpBar->Show(); + } + + return ( bHaveBar != i_needBar ); + } + + + /** returns the number of rows fitting into the given range, + for the given row height. Partially fitting rows are counted, too, if the + respective parameter says so. + */ + TableSize lcl_getRowsFittingInto( long _nOverallHeight, long _nRowHeightPixel, bool _bAcceptPartialRow ) + { + return _bAcceptPartialRow + ? ( _nOverallHeight + ( _nRowHeightPixel - 1 ) ) / _nRowHeightPixel + : _nOverallHeight / _nRowHeightPixel; + } + + + /** returns the number of columns fitting into the given area, + with the first visible column as given. Partially fitting columns are counted, too, + if the respective parameter says so. + */ + TableSize lcl_getColumnsVisibleWithin( const tools::Rectangle& _rArea, ColPos _nFirstVisibleColumn, + const TableControl_Impl& _rControl, bool _bAcceptPartialRow ) + { + TableSize visibleColumns = 0; + TableColumnGeometry aColumn( _rControl, _rArea, _nFirstVisibleColumn ); + while ( aColumn.isValid() ) + { + if ( !_bAcceptPartialRow ) + if ( aColumn.getRect().Right() > _rArea.Right() ) + // this column is only partially visible, and this is not allowed + break; + + aColumn.moveRight(); + ++visibleColumns; + } + return visibleColumns; + } + + } + + + long TableControl_Impl::impl_ni_calculateColumnWidths( ColPos const i_assumeInflexibleColumnsUpToIncluding, + bool const i_assumeVerticalScrollbar, ::std::vector< long >& o_newColWidthsPixel ) const + { + // the available horizontal space + long gridWidthPixel = m_rAntiImpl.GetOutputSizePixel().Width(); + ENSURE_OR_RETURN( !!m_pModel, "TableControl_Impl::impl_ni_calculateColumnWidths: not allowed without a model!", gridWidthPixel ); + if ( m_pModel->hasRowHeaders() && ( gridWidthPixel != 0 ) ) + { + gridWidthPixel -= m_nRowHeaderWidthPixel; + } + + if ( i_assumeVerticalScrollbar && ( m_pModel->getVerticalScrollbarVisibility() != ScrollbarShowNever ) ) + { + long nScrollbarMetrics = m_rAntiImpl.GetSettings().GetStyleSettings().GetScrollBarSize(); + gridWidthPixel -= nScrollbarMetrics; + } + + // no need to do anything without columns + TableSize const colCount = m_pModel->getColumnCount(); + if ( colCount == 0 ) + return gridWidthPixel; + + // collect some meta data for our columns: + // - their current (pixel) metrics + long accumulatedCurrentWidth = 0; + ::std::vector< long > currentColWidths; + currentColWidths.reserve( colCount ); + typedef ::std::vector< ::std::pair< long, long > > ColumnLimits; + ColumnLimits effectiveColumnLimits; + effectiveColumnLimits.reserve( colCount ); + long accumulatedMinWidth = 0; + long accumulatedMaxWidth = 0; + // - their relative flexibility + ::std::vector< ::sal_Int32 > columnFlexibilities; + columnFlexibilities.reserve( colCount ); + long flexibilityDenominator = 0; + size_t flexibleColumnCount = 0; + for ( ColPos col = 0; col < colCount; ++col ) + { + PColumnModel const pColumn = m_pModel->getColumnModel( col ); + ENSURE_OR_THROW( !!pColumn, "invalid column returned by the model!" ); + + // current width + long const currentWidth = appFontWidthToPixel( pColumn->getWidth() ); + currentColWidths.push_back( currentWidth ); + + // accumulated width + accumulatedCurrentWidth += currentWidth; + + // flexibility + ::sal_Int32 flexibility = pColumn->getFlexibility(); + OSL_ENSURE( flexibility >= 0, "TableControl_Impl::impl_ni_calculateColumnWidths: a column's flexibility should be non-negative." ); + if ( ( flexibility < 0 ) // normalization + || ( !pColumn->isResizable() ) // column not resizable => no auto-resize + || ( col <= i_assumeInflexibleColumnsUpToIncluding ) // column shall be treated as inflexible => respect this + ) + flexibility = 0; + + // min/max width + long effectiveMin = currentWidth, effectiveMax = currentWidth; + // if the column is not flexible, it will not be asked for min/max, but we assume the current width as limit then + if ( flexibility > 0 ) + { + long const minWidth = appFontWidthToPixel( pColumn->getMinWidth() ); + if ( minWidth > 0 ) + effectiveMin = minWidth; + else + effectiveMin = MIN_COLUMN_WIDTH_PIXEL; + + long const maxWidth = appFontWidthToPixel( pColumn->getMaxWidth() ); + OSL_ENSURE( minWidth <= maxWidth, "TableControl_Impl::impl_ni_calculateColumnWidths: pretty undecided 'bout its width limits, this column!" ); + if ( ( maxWidth > 0 ) && ( maxWidth >= minWidth ) ) + effectiveMax = maxWidth; + else + effectiveMax = gridWidthPixel; // TODO: any better guess here? + + if ( effectiveMin == effectiveMax ) + // if the min and the max are identical, this implies no flexibility at all + flexibility = 0; + } + + columnFlexibilities.push_back( flexibility ); + flexibilityDenominator += flexibility; + if ( flexibility > 0 ) + ++flexibleColumnCount; + + effectiveColumnLimits.emplace_back( effectiveMin, effectiveMax ); + accumulatedMinWidth += effectiveMin; + accumulatedMaxWidth += effectiveMax; + } + + o_newColWidthsPixel = currentColWidths; + if ( flexibilityDenominator == 0 ) + { + // no column is flexible => don't adjust anything + } + else if ( gridWidthPixel > accumulatedCurrentWidth ) + { // we have space to give away ... + long distributePixel = gridWidthPixel - accumulatedCurrentWidth; + if ( gridWidthPixel > accumulatedMaxWidth ) + { + // ... but the column's maximal widths are still less than we have + // => set them all to max + for ( svt::table::TableSize i = 0; i < colCount; ++i ) + { + o_newColWidthsPixel[i] = effectiveColumnLimits[i].second; + } + } + else + { + bool startOver = false; + do + { + startOver = false; + // distribute the remaining space amongst all columns with a positive flexibility + for ( size_t i=0; i<o_newColWidthsPixel.size() && !startOver; ++i ) + { + long const columnFlexibility = columnFlexibilities[i]; + if ( columnFlexibility == 0 ) + continue; + + long newColWidth = currentColWidths[i] + columnFlexibility * distributePixel / flexibilityDenominator; + + if ( newColWidth > effectiveColumnLimits[i].second ) + { // that was too much, we hit the col's maximum + // set the new width to exactly this maximum + newColWidth = effectiveColumnLimits[i].second; + // adjust the flexibility denominator ... + flexibilityDenominator -= columnFlexibility; + columnFlexibilities[i] = 0; + --flexibleColumnCount; + // ... and the remaining width ... + long const difference = newColWidth - currentColWidths[i]; + distributePixel -= difference; + // ... this way, we ensure that the width not taken up by this column is consumed by the other + // flexible ones (if there are some) + + // and start over with the first column, since there might be earlier columns which need + // to be recalculated now + startOver = true; + } + + o_newColWidthsPixel[i] = newColWidth; + } + } + while ( startOver ); + + // are there pixels left (might be caused by rounding errors)? + distributePixel = gridWidthPixel - ::std::accumulate( o_newColWidthsPixel.begin(), o_newColWidthsPixel.end(), 0 ); + while ( ( distributePixel > 0 ) && ( flexibleColumnCount > 0 ) ) + { + // yes => ignore relative flexibilities, and subsequently distribute single pixels to all flexible + // columns which did not yet reach their maximum. + for ( size_t i=0; ( i < o_newColWidthsPixel.size() ) && ( distributePixel > 0 ); ++i ) + { + if ( columnFlexibilities[i] == 0 ) + continue; + + OSL_ENSURE( o_newColWidthsPixel[i] <= effectiveColumnLimits[i].second, + "TableControl_Impl::impl_ni_calculateColumnWidths: inconsistency!" ); + if ( o_newColWidthsPixel[i] >= effectiveColumnLimits[i].first ) + { + columnFlexibilities[i] = 0; + --flexibleColumnCount; + continue; + } + + ++o_newColWidthsPixel[i]; + --distributePixel; + } + } + } + } + else if ( gridWidthPixel < accumulatedCurrentWidth ) + { // we need to take away some space from the columns which allow it ... + long takeAwayPixel = accumulatedCurrentWidth - gridWidthPixel; + if ( gridWidthPixel < accumulatedMinWidth ) + { + // ... but the column's minimal widths are still more than we have + // => set them all to min + for ( svt::table::TableSize i = 0; i < colCount; ++i ) + { + o_newColWidthsPixel[i] = effectiveColumnLimits[i].first; + } + } + else + { + bool startOver = false; + do + { + startOver = false; + // take away the space we need from the columns with a positive flexibility + for ( size_t i=0; i<o_newColWidthsPixel.size() && !startOver; ++i ) + { + long const columnFlexibility = columnFlexibilities[i]; + if ( columnFlexibility == 0 ) + continue; + + long newColWidth = currentColWidths[i] - columnFlexibility * takeAwayPixel / flexibilityDenominator; + + if ( newColWidth < effectiveColumnLimits[i].first ) + { // that was too much, we hit the col's minimum + // set the new width to exactly this minimum + newColWidth = effectiveColumnLimits[i].first; + // adjust the flexibility denominator ... + flexibilityDenominator -= columnFlexibility; + columnFlexibilities[i] = 0; + --flexibleColumnCount; + // ... and the remaining width ... + long const difference = currentColWidths[i] - newColWidth; + takeAwayPixel -= difference; + + // and start over with the first column, since there might be earlier columns which need + // to be recalculated now + startOver = true; + } + + o_newColWidthsPixel[i] = newColWidth; + } + } + while ( startOver ); + + // are there pixels left (might be caused by rounding errors)? + takeAwayPixel = ::std::accumulate( o_newColWidthsPixel.begin(), o_newColWidthsPixel.end(), 0 ) - gridWidthPixel; + while ( ( takeAwayPixel > 0 ) && ( flexibleColumnCount > 0 ) ) + { + // yes => ignore relative flexibilities, and subsequently take away pixels from all flexible + // columns which did not yet reach their minimum. + for ( size_t i=0; ( i < o_newColWidthsPixel.size() ) && ( takeAwayPixel > 0 ); ++i ) + { + if ( columnFlexibilities[i] == 0 ) + continue; + + OSL_ENSURE( o_newColWidthsPixel[i] >= effectiveColumnLimits[i].first, + "TableControl_Impl::impl_ni_calculateColumnWidths: inconsistency!" ); + if ( o_newColWidthsPixel[i] <= effectiveColumnLimits[i].first ) + { + columnFlexibilities[i] = 0; + --flexibleColumnCount; + continue; + } + + --o_newColWidthsPixel[i]; + --takeAwayPixel; + } + } + } + } + + return gridWidthPixel; + } + + + void TableControl_Impl::impl_ni_relayout( ColPos const i_assumeInflexibleColumnsUpToIncluding ) + { + ENSURE_OR_RETURN_VOID( !m_bUpdatingColWidths, "TableControl_Impl::impl_ni_relayout: recursive call detected!" ); + + m_aColumnWidths.resize( 0 ); + if ( !m_pModel ) + return; + + ::comphelper::FlagRestorationGuard const aWidthUpdateFlag( m_bUpdatingColWidths, true ); + SuppressCursor aHideCursor( *this ); + + // layouting steps: + + // 1. adjust column widths, leaving space for a vertical scrollbar + // 2. determine need for a vertical scrollbar + // - V-YES: all fine, result from 1. is still valid + // - V-NO: result from 1. is still under consideration + + // 3. determine need for a horizontal scrollbar + // - H-NO: all fine, result from 2. is still valid + // - H-YES: reconsider need for a vertical scrollbar, if result of 2. was V-NO + // - V-YES: all fine, result from 1. is still valid + // - V-NO: redistribute the remaining space (if any) amongst all columns which allow it + + ::std::vector< long > newWidthsPixel; + long gridWidthPixel = impl_ni_calculateColumnWidths( i_assumeInflexibleColumnsUpToIncluding, true, newWidthsPixel ); + + // the width/height of a scrollbar, needed several times below + long const nScrollbarMetrics = m_rAntiImpl.GetSettings().GetStyleSettings().GetScrollBarSize(); + + // determine the playground for the data cells (excluding headers) + // TODO: what if the control is smaller than needed for the headers/scrollbars? + tools::Rectangle aDataCellPlayground( Point( 0, 0 ), m_rAntiImpl.GetOutputSizePixel() ); + aDataCellPlayground.SetLeft( m_nRowHeaderWidthPixel ); + aDataCellPlayground.SetTop( m_nColHeaderHeightPixel ); + + OSL_ENSURE( ( m_nRowCount == m_pModel->getRowCount() ) && ( m_nColumnCount == m_pModel->getColumnCount() ), + "TableControl_Impl::impl_ni_relayout: how is this expected to work with invalid data?" ); + long const nAllColumnsWidth = ::std::accumulate( newWidthsPixel.begin(), newWidthsPixel.end(), 0 ); + + ScrollbarVisibility const eVertScrollbar = m_pModel->getVerticalScrollbarVisibility(); + ScrollbarVisibility const eHorzScrollbar = m_pModel->getHorizontalScrollbarVisibility(); + + // do we need a vertical scrollbar? + bool bNeedVerticalScrollbar = lcl_determineScrollbarNeed( + m_nTopRow, eVertScrollbar, aDataCellPlayground.GetHeight(), m_nRowHeightPixel * m_nRowCount ); + bool bFirstRoundVScrollNeed = false; + if ( bNeedVerticalScrollbar ) + { + aDataCellPlayground.AdjustRight( -nScrollbarMetrics ); + bFirstRoundVScrollNeed = true; + } + + // do we need a horizontal scrollbar? + bool const bNeedHorizontalScrollbar = lcl_determineScrollbarNeed( + m_nLeftColumn, eHorzScrollbar, aDataCellPlayground.GetWidth(), nAllColumnsWidth ); + if ( bNeedHorizontalScrollbar ) + { + aDataCellPlayground.AdjustBottom( -nScrollbarMetrics ); + + // now that we just found that we need a horizontal scrollbar, + // the need for a vertical one may have changed, since the horizontal + // SB might just occupy enough space so that not all rows do fit + // anymore + if ( !bFirstRoundVScrollNeed ) + { + bNeedVerticalScrollbar = lcl_determineScrollbarNeed( + m_nTopRow, eVertScrollbar, aDataCellPlayground.GetHeight(), m_nRowHeightPixel * m_nRowCount ); + if ( bNeedVerticalScrollbar ) + { + aDataCellPlayground.AdjustRight( -nScrollbarMetrics ); + } + } + } + + // the initial call to impl_ni_calculateColumnWidths assumed that we need a vertical scrollbar. If, by now, + // we know that this is not the case, re-calculate the column widths. + if ( !bNeedVerticalScrollbar ) + gridWidthPixel = impl_ni_calculateColumnWidths( i_assumeInflexibleColumnsUpToIncluding, false, newWidthsPixel ); + + // update the column objects with the new widths we finally calculated + TableSize const colCount = m_pModel->getColumnCount(); + m_aColumnWidths.reserve( colCount ); + long accumulatedWidthPixel = m_nRowHeaderWidthPixel; + bool anyColumnWidthChanged = false; + for ( ColPos col = 0; col < colCount; ++col ) + { + const long columnStart = accumulatedWidthPixel; + const long columnEnd = columnStart + newWidthsPixel[col]; + m_aColumnWidths.emplace_back( columnStart, columnEnd ); + accumulatedWidthPixel = columnEnd; + + // and don't forget to forward this to the column models + PColumnModel const pColumn = m_pModel->getColumnModel( col ); + ENSURE_OR_THROW( !!pColumn, "invalid column returned by the model!" ); + + long const oldColumnWidthAppFont = pColumn->getWidth(); + long const newColumnWidthAppFont = pixelWidthToAppFont( newWidthsPixel[col] ); + pColumn->setWidth( newColumnWidthAppFont ); + + anyColumnWidthChanged |= ( oldColumnWidthAppFont != newColumnWidthAppFont ); + } + + // if the column widths changed, ensure everything is repainted + if ( anyColumnWidthChanged ) + invalidate( TableArea::All ); + + // if the column resizing happened to leave some space at the right, but there are columns + // scrolled out to the left, scroll them in + while ( ( m_nLeftColumn > 0 ) + && ( accumulatedWidthPixel - m_aColumnWidths[ m_nLeftColumn - 1 ].getStart() <= gridWidthPixel ) + ) + { + --m_nLeftColumn; + } + + // now adjust the column metrics, since they currently ignore the horizontal scroll position + if ( m_nLeftColumn > 0 ) + { + const long offsetPixel = m_aColumnWidths[ 0 ].getStart() - m_aColumnWidths[ m_nLeftColumn ].getStart(); + for (auto & columnWidth : m_aColumnWidths) + { + columnWidth.move( offsetPixel ); + } + } + + // show or hide the scrollbars as needed, and position the data window + impl_ni_positionChildWindows( aDataCellPlayground, bNeedVerticalScrollbar, bNeedHorizontalScrollbar ); + } + + + void TableControl_Impl::impl_ni_positionChildWindows( tools::Rectangle const & i_dataCellPlayground, + bool const i_verticalScrollbar, bool const i_horizontalScrollbar ) + { + long const nScrollbarMetrics = m_rAntiImpl.GetSettings().GetStyleSettings().GetScrollBarSize(); + + // create or destroy the vertical scrollbar, as needed + lcl_updateScrollbar( + m_rAntiImpl, + m_pVScroll, + i_verticalScrollbar, + lcl_getRowsFittingInto( i_dataCellPlayground.GetHeight(), m_nRowHeightPixel, false ), + // visible units + m_nTopRow, // current position + m_nRowCount, // range + false, // vertical + LINK( this, TableControl_Impl, OnScroll ) // scroll handler + ); + + // position it + if ( m_pVScroll ) + { + tools::Rectangle aScrollbarArea( + Point( i_dataCellPlayground.Right() + 1, 0 ), + Size( nScrollbarMetrics, i_dataCellPlayground.Bottom() + 1 ) + ); + m_pVScroll->SetPosSizePixel( + aScrollbarArea.TopLeft(), aScrollbarArea.GetSize() ); + } + + // create or destroy the horizontal scrollbar, as needed + lcl_updateScrollbar( + m_rAntiImpl, + m_pHScroll, + i_horizontalScrollbar, + lcl_getColumnsVisibleWithin( i_dataCellPlayground, m_nLeftColumn, *this, false ), + // visible units + m_nLeftColumn, // current position + m_nColumnCount, // range + true, // horizontal + LINK( this, TableControl_Impl, OnScroll ) // scroll handler + ); + + // position it + if ( m_pHScroll ) + { + TableSize const nVisibleUnits = lcl_getColumnsVisibleWithin( i_dataCellPlayground, m_nLeftColumn, *this, false ); + TableMetrics const nRange = m_nColumnCount; + if( m_nLeftColumn + nVisibleUnits == nRange - 1 ) + { + if ( m_aColumnWidths[ nRange - 1 ].getStart() - m_aColumnWidths[ m_nLeftColumn ].getEnd() + m_aColumnWidths[ nRange-1 ].getWidth() > i_dataCellPlayground.GetWidth() ) + { + m_pHScroll->SetVisibleSize( nVisibleUnits -1 ); + m_pHScroll->SetPageSize( nVisibleUnits - 1 ); + } + } + tools::Rectangle aScrollbarArea( + Point( 0, i_dataCellPlayground.Bottom() + 1 ), + Size( i_dataCellPlayground.Right() + 1, nScrollbarMetrics ) + ); + m_pHScroll->SetPosSizePixel( + aScrollbarArea.TopLeft(), aScrollbarArea.GetSize() ); + } + + // the corner window connecting the two scrollbars in the lower right corner + bool bHaveScrollCorner = nullptr != m_pScrollCorner; + bool bNeedScrollCorner = ( nullptr != m_pHScroll ) && ( nullptr != m_pVScroll ); + if ( bHaveScrollCorner && !bNeedScrollCorner ) + { + m_pScrollCorner.disposeAndClear(); + } + else if ( !bHaveScrollCorner && bNeedScrollCorner ) + { + m_pScrollCorner = VclPtr<ScrollBarBox>::Create( &m_rAntiImpl ); + m_pScrollCorner->SetSizePixel( Size( nScrollbarMetrics, nScrollbarMetrics ) ); + m_pScrollCorner->SetPosPixel( Point( i_dataCellPlayground.Right() + 1, i_dataCellPlayground.Bottom() + 1 ) ); + m_pScrollCorner->Show(); + } + else if(bHaveScrollCorner && bNeedScrollCorner) + { + m_pScrollCorner->SetPosPixel( Point( i_dataCellPlayground.Right() + 1, i_dataCellPlayground.Bottom() + 1 ) ); + m_pScrollCorner->Show(); + } + + // resize the data window + m_pDataWindow->SetSizePixel( Size( + i_dataCellPlayground.GetWidth() + m_nRowHeaderWidthPixel, + i_dataCellPlayground.GetHeight() + m_nColHeaderHeightPixel + ) ); + } + + + void TableControl_Impl::onResize() + { + impl_ni_relayout(); + checkCursorPosition(); + } + + + void TableControl_Impl::doPaintContent(vcl::RenderContext& rRenderContext, const tools::Rectangle& _rUpdateRect) + { + if (!getModel()) + return; + PTableRenderer pRenderer = getModel()->getRenderer(); + DBG_ASSERT(!!pRenderer, "TableDataWindow::doPaintContent: invalid renderer!"); + if (!pRenderer) + return; + + // our current style settings, to be passed to the renderer + const StyleSettings& rStyle = rRenderContext.GetSettings().GetStyleSettings(); + m_nRowCount = m_pModel->getRowCount(); + // the area occupied by all (at least partially) visible cells, including + // headers + tools::Rectangle const aAllCellsWithHeaders( impl_getAllVisibleCellsArea() ); + + // draw the header column area + if (m_pModel->hasColumnHeaders()) + { + TableRowGeometry const aHeaderRow(*this, tools::Rectangle(Point(0, 0), aAllCellsWithHeaders.BottomRight()), ROW_COL_HEADERS); + tools::Rectangle const aColRect(aHeaderRow.getRect()); + pRenderer->PaintHeaderArea(rRenderContext, aColRect, true, false, rStyle); + // Note that strictly, aHeaderRow.getRect() also contains the intersection between column + // and row header area. However, below we go to paint this intersection, again, + // so this hopefully doesn't hurt if we already paint it here. + + for (TableCellGeometry aCell(aHeaderRow, m_nLeftColumn); aCell.isValid(); aCell.moveRight()) + { + if (_rUpdateRect.GetIntersection(aCell.getRect()).IsEmpty()) + continue; + + pRenderer->PaintColumnHeader(aCell.getColumn(), rRenderContext, aCell.getRect(), rStyle); + } + } + // the area occupied by the row header, if any + tools::Rectangle aRowHeaderArea; + if (m_pModel->hasRowHeaders()) + { + aRowHeaderArea = aAllCellsWithHeaders; + aRowHeaderArea.SetRight( m_nRowHeaderWidthPixel - 1 ); + + TableSize const nVisibleRows = impl_getVisibleRows(true); + TableSize nActualRows = nVisibleRows; + if (m_nTopRow + nActualRows > m_nRowCount) + nActualRows = m_nRowCount - m_nTopRow; + aRowHeaderArea.SetBottom( m_nColHeaderHeightPixel + m_nRowHeightPixel * nActualRows - 1 ); + + pRenderer->PaintHeaderArea(rRenderContext, aRowHeaderArea, false, true, rStyle); + // Note that strictly, aRowHeaderArea also contains the intersection between column + // and row header area. However, below we go to paint this intersection, again, + // so this hopefully doesn't hurt if we already paint it here. + + if (m_pModel->hasColumnHeaders()) + { + TableCellGeometry const aIntersection(*this, tools::Rectangle(Point(0, 0), aAllCellsWithHeaders.BottomRight()), + COL_ROW_HEADERS, ROW_COL_HEADERS); + tools::Rectangle const aInters(aIntersection.getRect()); + pRenderer->PaintHeaderArea(rRenderContext, aInters, true, true, rStyle); + } + } + + // draw the table content row by row + TableSize colCount = getModel()->getColumnCount(); + + // paint all rows + tools::Rectangle const aAllDataCellsArea(impl_getAllVisibleDataCellArea()); + for (TableRowGeometry aRowIterator(*this, aAllCellsWithHeaders, getTopRow()); aRowIterator.isValid(); aRowIterator.moveDown()) + { + if (_rUpdateRect.GetIntersection(aRowIterator.getRect() ).IsEmpty()) + continue; + + bool const isControlFocused = m_rAntiImpl.HasControlFocus(); + bool const isSelectedRow = isRowSelected(aRowIterator.getRow()); + + tools::Rectangle const aRect = aRowIterator.getRect().GetIntersection(aAllDataCellsArea); + + // give the renderer a chance to prepare the row + pRenderer->PrepareRow(aRowIterator.getRow(), isControlFocused, isSelectedRow, rRenderContext, aRect, rStyle); + + // paint the row header + if (m_pModel->hasRowHeaders()) + { + const tools::Rectangle aCurrentRowHeader(aRowHeaderArea.GetIntersection(aRowIterator.getRect())); + pRenderer->PaintRowHeader(rRenderContext, aCurrentRowHeader, rStyle); + } + + if (!colCount) + continue; + + // paint all cells in this row + for (TableCellGeometry aCell(aRowIterator, m_nLeftColumn); aCell.isValid(); aCell.moveRight()) + { + pRenderer->PaintCell(aCell.getColumn(), isSelectedRow, isControlFocused, + rRenderContext, aCell.getRect(), rStyle); + } + } + } + + void TableControl_Impl::hideCursor() + { + if ( ++m_nCursorHidden == 1 ) + impl_ni_doSwitchCursor( false ); + } + + + void TableControl_Impl::showCursor() + { + DBG_ASSERT( m_nCursorHidden > 0, "TableControl_Impl::showCursor: cursor not hidden!" ); + if ( --m_nCursorHidden == 0 ) + impl_ni_doSwitchCursor( true ); + } + + + bool TableControl_Impl::dispatchAction( TableControlAction _eAction ) + { + bool bSuccess = false; + bool selectionChanged = false; + + switch ( _eAction ) + { + case cursorDown: + if ( m_pSelEngine->GetSelectionMode() == SelectionMode::Single ) + { + //if other rows already selected, deselect them + if(!m_aSelectedRows.empty()) + { + invalidateSelectedRows(); + m_aSelectedRows.clear(); + } + if ( m_nCurRow < m_nRowCount-1 ) + { + ++m_nCurRow; + m_aSelectedRows.push_back(m_nCurRow); + } + else + m_aSelectedRows.push_back(m_nCurRow); + invalidateRow( m_nCurRow ); + ensureVisible(m_nCurColumn,m_nCurRow); + selectionChanged = true; + bSuccess = true; + } + else + { + if ( m_nCurRow < m_nRowCount - 1 ) + bSuccess = goTo( m_nCurColumn, m_nCurRow + 1 ); + } + break; + + case cursorUp: + if(m_pSelEngine->GetSelectionMode() == SelectionMode::Single) + { + if(!m_aSelectedRows.empty()) + { + invalidateSelectedRows(); + m_aSelectedRows.clear(); + } + if(m_nCurRow>0) + { + --m_nCurRow; + m_aSelectedRows.push_back(m_nCurRow); + invalidateRow( m_nCurRow ); + } + else + { + m_aSelectedRows.push_back(m_nCurRow); + invalidateRow( m_nCurRow ); + } + ensureVisible(m_nCurColumn,m_nCurRow); + selectionChanged = true; + bSuccess = true; + } + else + { + if ( m_nCurRow > 0 ) + bSuccess = goTo( m_nCurColumn, m_nCurRow - 1 ); + } + break; + case cursorLeft: + if ( m_nCurColumn > 0 ) + bSuccess = goTo( m_nCurColumn - 1, m_nCurRow ); + else + if ( ( m_nCurColumn == 0) && ( m_nCurRow > 0 ) ) + bSuccess = goTo( m_nColumnCount - 1, m_nCurRow - 1 ); + break; + + case cursorRight: + if ( m_nCurColumn < m_nColumnCount - 1 ) + bSuccess = goTo( m_nCurColumn + 1, m_nCurRow ); + else + if ( ( m_nCurColumn == m_nColumnCount - 1 ) && ( m_nCurRow < m_nRowCount - 1 ) ) + bSuccess = goTo( 0, m_nCurRow + 1 ); + break; + + case cursorToLineStart: + bSuccess = goTo( 0, m_nCurRow ); + break; + + case cursorToLineEnd: + bSuccess = goTo( m_nColumnCount - 1, m_nCurRow ); + break; + + case cursorToFirstLine: + bSuccess = goTo( m_nCurColumn, 0 ); + break; + + case cursorToLastLine: + bSuccess = goTo( m_nCurColumn, m_nRowCount - 1 ); + break; + + case cursorPageUp: + { + RowPos nNewRow = ::std::max( RowPos(0), m_nCurRow - impl_getVisibleRows( false ) ); + bSuccess = goTo( m_nCurColumn, nNewRow ); + } + break; + + case cursorPageDown: + { + RowPos nNewRow = ::std::min( m_nRowCount - 1, m_nCurRow + impl_getVisibleRows( false ) ); + bSuccess = goTo( m_nCurColumn, nNewRow ); + } + break; + + case cursorTopLeft: + bSuccess = goTo( 0, 0 ); + break; + + case cursorBottomRight: + bSuccess = goTo( m_nColumnCount - 1, m_nRowCount - 1 ); + break; + + case cursorSelectRow: + { + if(m_pSelEngine->GetSelectionMode() == SelectionMode::NONE) + return false; + //pos is the position of the current row in the vector of selected rows, if current row is selected + int pos = getRowSelectedNumber(m_aSelectedRows, m_nCurRow); + //if current row is selected, it should be deselected, when ALT+SPACE are pressed + if(pos>-1) + { + m_aSelectedRows.erase(m_aSelectedRows.begin()+pos); + if(m_aSelectedRows.empty() && m_nAnchor != -1) + m_nAnchor = -1; + } + //else select the row->put it in the vector + else + m_aSelectedRows.push_back(m_nCurRow); + invalidateRow( m_nCurRow ); + selectionChanged = true; + bSuccess = true; + } + break; + case cursorSelectRowUp: + { + if(m_pSelEngine->GetSelectionMode() == SelectionMode::NONE) + return false; + else if(m_pSelEngine->GetSelectionMode() == SelectionMode::Single) + { + //if there are other selected rows, deselect them + return false; + } + else + { + //there are other selected rows + if(!m_aSelectedRows.empty()) + { + //the anchor wasn't set -> a region is not selected, that's why clear all selection + //and select the current row + if(m_nAnchor==-1) + { + invalidateSelectedRows(); + m_aSelectedRows.clear(); + m_aSelectedRows.push_back(m_nCurRow); + invalidateRow( m_nCurRow ); + } + else + { + //a region is already selected, prevRow is last selected row and the row above - nextRow - should be selected + int prevRow = getRowSelectedNumber(m_aSelectedRows, m_nCurRow); + int nextRow = getRowSelectedNumber(m_aSelectedRows, m_nCurRow-1); + if(prevRow>-1) + { + //if m_nCurRow isn't the upper one, can move up, otherwise not + if(m_nCurRow>0) + m_nCurRow--; + else + return true; + //if nextRow already selected, deselect it, otherwise select it + if(nextRow>-1 && m_aSelectedRows[nextRow] == m_nCurRow) + { + m_aSelectedRows.erase(m_aSelectedRows.begin()+prevRow); + invalidateRow( m_nCurRow + 1 ); + } + else + { + m_aSelectedRows.push_back(m_nCurRow); + invalidateRow( m_nCurRow ); + } + } + else + { + if(m_nCurRow>0) + { + m_aSelectedRows.push_back(m_nCurRow); + m_nCurRow--; + m_aSelectedRows.push_back(m_nCurRow); + invalidateSelectedRegion( m_nCurRow+1, m_nCurRow ); + } + } + } + } + else + { + //if nothing is selected and the current row isn't the upper one + //select the current and one row above + //otherwise select only the upper row + if(m_nCurRow>0) + { + m_aSelectedRows.push_back(m_nCurRow); + m_nCurRow--; + m_aSelectedRows.push_back(m_nCurRow); + invalidateSelectedRegion( m_nCurRow+1, m_nCurRow ); + } + else + { + m_aSelectedRows.push_back(m_nCurRow); + invalidateRow( m_nCurRow ); + } + } + m_pSelEngine->SetAnchor(true); + m_nAnchor = m_nCurRow; + ensureVisible(m_nCurColumn, m_nCurRow); + selectionChanged = true; + bSuccess = true; + } + } + break; + case cursorSelectRowDown: + { + if(m_pSelEngine->GetSelectionMode() == SelectionMode::NONE) + bSuccess = false; + else if(m_pSelEngine->GetSelectionMode() == SelectionMode::Single) + { + bSuccess = false; + } + else + { + if(!m_aSelectedRows.empty()) + { + //the anchor wasn't set -> a region is not selected, that's why clear all selection + //and select the current row + if(m_nAnchor==-1) + { + invalidateSelectedRows(); + m_aSelectedRows.clear(); + m_aSelectedRows.push_back(m_nCurRow); + invalidateRow( m_nCurRow ); + } + else + { + //a region is already selected, prevRow is last selected row and the row beneath - nextRow - should be selected + int prevRow = getRowSelectedNumber(m_aSelectedRows, m_nCurRow); + int nextRow = getRowSelectedNumber(m_aSelectedRows, m_nCurRow+1); + if(prevRow>-1) + { + //if m_nCurRow isn't the last one, can move down, otherwise not + if(m_nCurRow<m_nRowCount-1) + m_nCurRow++; + else + return true; + //if next row already selected, deselect it, otherwise select it + if(nextRow>-1 && m_aSelectedRows[nextRow] == m_nCurRow) + { + m_aSelectedRows.erase(m_aSelectedRows.begin()+prevRow); + invalidateRow( m_nCurRow - 1 ); + } + else + { + m_aSelectedRows.push_back(m_nCurRow); + invalidateRow( m_nCurRow ); + } + } + else + { + if(m_nCurRow<m_nRowCount-1) + { + m_aSelectedRows.push_back(m_nCurRow); + m_nCurRow++; + m_aSelectedRows.push_back(m_nCurRow); + invalidateSelectedRegion( m_nCurRow-1, m_nCurRow ); + } + } + } + } + else + { + //there wasn't any selection, select current and row beneath, otherwise only row beneath + if(m_nCurRow<m_nRowCount-1) + { + m_aSelectedRows.push_back(m_nCurRow); + m_nCurRow++; + m_aSelectedRows.push_back(m_nCurRow); + invalidateSelectedRegion( m_nCurRow-1, m_nCurRow ); + } + else + { + m_aSelectedRows.push_back(m_nCurRow); + invalidateRow( m_nCurRow ); + } + } + m_pSelEngine->SetAnchor(true); + m_nAnchor = m_nCurRow; + ensureVisible(m_nCurColumn, m_nCurRow); + selectionChanged = true; + bSuccess = true; + } + } + break; + + case cursorSelectRowAreaTop: + { + if(m_pSelEngine->GetSelectionMode() == SelectionMode::NONE) + bSuccess = false; + else if(m_pSelEngine->GetSelectionMode() == SelectionMode::Single) + bSuccess = false; + else + { + //select the region between the current and the upper row + RowPos iter = m_nCurRow; + invalidateSelectedRegion( m_nCurRow, 0 ); + //put the rows in vector + while(iter>=0) + { + if ( !isRowSelected( iter ) ) + m_aSelectedRows.push_back(iter); + --iter; + } + m_nCurRow = 0; + m_nAnchor = m_nCurRow; + m_pSelEngine->SetAnchor(true); + ensureVisible(m_nCurColumn, 0); + selectionChanged = true; + bSuccess = true; + } + } + break; + + case cursorSelectRowAreaBottom: + { + if(m_pSelEngine->GetSelectionMode() == SelectionMode::NONE) + return false; + else if(m_pSelEngine->GetSelectionMode() == SelectionMode::Single) + return false; + //select the region between the current and the last row + RowPos iter = m_nCurRow; + invalidateSelectedRegion( m_nCurRow, m_nRowCount-1 ); + //put the rows in the vector + while(iter<=m_nRowCount) + { + if ( !isRowSelected( iter ) ) + m_aSelectedRows.push_back(iter); + ++iter; + } + m_nCurRow = m_nRowCount-1; + m_nAnchor = m_nCurRow; + m_pSelEngine->SetAnchor(true); + ensureVisible(m_nCurColumn, m_nRowCount-1); + selectionChanged = true; + bSuccess = true; + } + break; + default: + OSL_FAIL( "TableControl_Impl::dispatchAction: unsupported action!" ); + break; + } + + if ( bSuccess && selectionChanged ) + { + m_rAntiImpl.Select(); + } + + return bSuccess; + } + + + void TableControl_Impl::impl_ni_doSwitchCursor( bool _bShow ) + { + PTableRenderer pRenderer = m_pModel ? m_pModel->getRenderer() : PTableRenderer(); + if ( pRenderer ) + { + tools::Rectangle aCellRect; + impl_getCellRect( m_nCurColumn, m_nCurRow, aCellRect ); + if ( _bShow ) + pRenderer->ShowCellCursor( *m_pDataWindow, aCellRect ); + else + pRenderer->HideCellCursor( *m_pDataWindow ); + } + } + + + void TableControl_Impl::impl_getCellRect( ColPos _nColumn, RowPos _nRow, tools::Rectangle& _rCellRect ) const + { + if ( !m_pModel + || ( COL_INVALID == _nColumn ) + || ( ROW_INVALID == _nRow ) + ) + { + _rCellRect.SetEmpty(); + return; + } + + TableCellGeometry aCell( *this, impl_getAllVisibleCellsArea(), _nColumn, _nRow ); + _rCellRect = aCell.getRect(); + } + + + RowPos TableControl_Impl::getRowAtPoint( const Point& rPoint ) const + { + return impl_getRowForAbscissa( rPoint.Y() ); + } + + + ColPos TableControl_Impl::getColAtPoint( const Point& rPoint ) const + { + return impl_getColumnForOrdinate( rPoint.X() ); + } + + + TableCell TableControl_Impl::hitTest( Point const & i_point ) const + { + TableCell aCell( getColAtPoint( i_point ), getRowAtPoint( i_point ) ); + if ( aCell.nColumn > COL_ROW_HEADERS ) + { + PColumnModel const pColumn = m_pModel->getColumnModel( aCell.nColumn ); + MutableColumnMetrics const & rColInfo( m_aColumnWidths[ aCell.nColumn ] ); + if ( ( rColInfo.getEnd() - 3 <= i_point.X() ) + && ( rColInfo.getEnd() >= i_point.X() ) + && pColumn->isResizable() + ) + { + aCell.eArea = ColumnDivider; + } + } + return aCell; + } + + + ColumnMetrics TableControl_Impl::getColumnMetrics( ColPos const i_column ) const + { + ENSURE_OR_RETURN( ( i_column >= 0 ) && ( i_column < m_pModel->getColumnCount() ), + "TableControl_Impl::getColumnMetrics: illegal column index!", ColumnMetrics() ); + return m_aColumnWidths[ i_column ]; + } + + + PTableModel TableControl_Impl::getModel() const + { + return m_pModel; + } + + + ColPos TableControl_Impl::getCurrentColumn() const + { + return m_nCurColumn; + } + + + RowPos TableControl_Impl::getCurrentRow() const + { + return m_nCurRow; + } + + + ::Size TableControl_Impl::getTableSizePixel() const + { + return m_pDataWindow->GetOutputSizePixel(); + } + + + void TableControl_Impl::setPointer( PointerStyle i_pointer ) + { + m_pDataWindow->SetPointer( i_pointer ); + } + + + void TableControl_Impl::captureMouse() + { + m_pDataWindow->CaptureMouse(); + } + + + void TableControl_Impl::releaseMouse() + { + m_pDataWindow->ReleaseMouse(); + } + + + void TableControl_Impl::invalidate( TableArea const i_what ) + { + switch ( i_what ) + { + case TableArea::ColumnHeaders: + m_pDataWindow->Invalidate( calcHeaderRect( true ) ); + break; + + case TableArea::RowHeaders: + m_pDataWindow->Invalidate( calcHeaderRect( false ) ); + break; + + case TableArea::All: + m_pDataWindow->Invalidate(); + m_pDataWindow->GetParent()->Invalidate( InvalidateFlags::Transparent ); + break; + } + } + + + long TableControl_Impl::pixelWidthToAppFont( long const i_pixels ) const + { + return m_pDataWindow->PixelToLogic(Size(i_pixels, 0), MapMode(MapUnit::MapAppFont)).Width(); + } + + + long TableControl_Impl::appFontWidthToPixel( long const i_appFontUnits ) const + { + return m_pDataWindow->LogicToPixel(Size(i_appFontUnits, 0), MapMode(MapUnit::MapAppFont)).Width(); + } + + + void TableControl_Impl::hideTracking() + { + m_pDataWindow->HideTracking(); + } + + + void TableControl_Impl::showTracking( tools::Rectangle const & i_location, ShowTrackFlags const i_flags ) + { + m_pDataWindow->ShowTracking( i_location, i_flags ); + } + + + void TableControl_Impl::activateCell( ColPos const i_col, RowPos const i_row ) + { + goTo( i_col, i_row ); + } + + + void TableControl_Impl::invalidateSelectedRegion( RowPos _nPrevRow, RowPos _nCurRow ) + { + // get the visible area of the table control and set the Left and right border of the region to be repainted + tools::Rectangle const aAllCells( impl_getAllVisibleCellsArea() ); + + tools::Rectangle aInvalidateRect; + aInvalidateRect.SetLeft( aAllCells.Left() ); + aInvalidateRect.SetRight( aAllCells.Right() ); + // if only one row is selected + if ( _nPrevRow == _nCurRow ) + { + tools::Rectangle aCellRect; + impl_getCellRect( m_nCurColumn, _nCurRow, aCellRect ); + aInvalidateRect.SetTop( aCellRect.Top() ); + aInvalidateRect.SetBottom( aCellRect.Bottom() ); + } + //if the region is above the current row + else if(_nPrevRow < _nCurRow ) + { + tools::Rectangle aCellRect; + impl_getCellRect( m_nCurColumn, _nPrevRow, aCellRect ); + aInvalidateRect.SetTop( aCellRect.Top() ); + impl_getCellRect( m_nCurColumn, _nCurRow, aCellRect ); + aInvalidateRect.SetBottom( aCellRect.Bottom() ); + } + //if the region is beneath the current row + else + { + tools::Rectangle aCellRect; + impl_getCellRect( m_nCurColumn, _nCurRow, aCellRect ); + aInvalidateRect.SetTop( aCellRect.Top() ); + impl_getCellRect( m_nCurColumn, _nPrevRow, aCellRect ); + aInvalidateRect.SetBottom( aCellRect.Bottom() ); + } + + invalidateRect(aInvalidateRect); + } + + void TableControl_Impl::invalidateRect(const tools::Rectangle &rInvalidateRect) + { + m_pDataWindow->Invalidate( rInvalidateRect, + m_pDataWindow->GetControlBackground().GetTransparency() ? InvalidateFlags::Transparent : InvalidateFlags::NONE ); + } + + + void TableControl_Impl::invalidateSelectedRows() + { + for (auto const& selectedRow : m_aSelectedRows) + { + invalidateRow(selectedRow); + } + } + + + void TableControl_Impl::invalidateRowRange( RowPos const i_firstRow, RowPos const i_lastRow ) + { + RowPos const firstRow = i_firstRow < m_nTopRow ? m_nTopRow : i_firstRow; + RowPos const lastVisibleRow = m_nTopRow + impl_getVisibleRows( true ) - 1; + RowPos const lastRow = ( ( i_lastRow == ROW_INVALID ) || ( i_lastRow > lastVisibleRow ) ) ? lastVisibleRow : i_lastRow; + + tools::Rectangle aInvalidateRect; + + tools::Rectangle const aVisibleCellsArea( impl_getAllVisibleCellsArea() ); + TableRowGeometry aRow( *this, aVisibleCellsArea, firstRow, true ); + while ( aRow.isValid() && ( aRow.getRow() <= lastRow ) ) + { + aInvalidateRect.Union( aRow.getRect() ); + aRow.moveDown(); + } + + if ( i_lastRow == ROW_INVALID ) + aInvalidateRect.SetBottom( m_pDataWindow->GetOutputSizePixel().Height() ); + + invalidateRect(aInvalidateRect); + } + + + void TableControl_Impl::checkCursorPosition() + { + + TableSize nVisibleRows = impl_getVisibleRows(true); + TableSize nVisibleCols = impl_getVisibleColumns(true); + if ( ( m_nTopRow + nVisibleRows > m_nRowCount ) + && ( m_nRowCount >= nVisibleRows ) + ) + { + --m_nTopRow; + } + else + { + m_nTopRow = 0; + } + + if ( ( m_nLeftColumn + nVisibleCols > m_nColumnCount ) + && ( m_nColumnCount >= nVisibleCols ) + ) + { + --m_nLeftColumn; + } + else + { + m_nLeftColumn = 0; + } + + m_pDataWindow->Invalidate(); + } + + + TableSize TableControl_Impl::impl_getVisibleRows( bool _bAcceptPartialRow ) const + { + DBG_ASSERT( m_pDataWindow, "TableControl_Impl::impl_getVisibleRows: no data window!" ); + + return lcl_getRowsFittingInto( + m_pDataWindow->GetOutputSizePixel().Height() - m_nColHeaderHeightPixel, + m_nRowHeightPixel, + _bAcceptPartialRow + ); + } + + + TableSize TableControl_Impl::impl_getVisibleColumns( bool _bAcceptPartialCol ) const + { + DBG_ASSERT( m_pDataWindow, "TableControl_Impl::impl_getVisibleColumns: no data window!" ); + + return lcl_getColumnsVisibleWithin( + tools::Rectangle( Point( 0, 0 ), m_pDataWindow->GetOutputSizePixel() ), + m_nLeftColumn, + *this, + _bAcceptPartialCol + ); + } + + + bool TableControl_Impl::goTo( ColPos _nColumn, RowPos _nRow ) + { + // TODO: give veto listeners a chance + + if ( ( _nColumn < 0 ) || ( _nColumn >= m_nColumnCount ) + || ( _nRow < 0 ) || ( _nRow >= m_nRowCount ) + ) + { + OSL_ENSURE( false, "TableControl_Impl::goTo: invalid row or column index!" ); + return false; + } + + SuppressCursor aHideCursor( *this ); + m_nCurColumn = _nColumn; + m_nCurRow = _nRow; + + // ensure that the new cell is visible + ensureVisible( m_nCurColumn, m_nCurRow ); + return true; + } + + + void TableControl_Impl::ensureVisible( ColPos _nColumn, RowPos _nRow ) + { + DBG_ASSERT( ( _nColumn >= 0 ) && ( _nColumn < m_nColumnCount ) + && ( _nRow >= 0 ) && ( _nRow < m_nRowCount ), + "TableControl_Impl::ensureVisible: invalid coordinates!" ); + + SuppressCursor aHideCursor( *this ); + + if ( _nColumn < m_nLeftColumn ) + impl_scrollColumns( _nColumn - m_nLeftColumn ); + else + { + TableSize nVisibleColumns = impl_getVisibleColumns( false/*bAcceptPartialVisibility*/ ); + if ( _nColumn > m_nLeftColumn + nVisibleColumns - 1 ) + { + impl_scrollColumns( _nColumn - ( m_nLeftColumn + nVisibleColumns - 1 ) ); + // TODO: since not all columns have the same width, this might in theory result + // in the column still not being visible. + } + } + + if ( _nRow < m_nTopRow ) + impl_scrollRows( _nRow - m_nTopRow ); + else + { + TableSize nVisibleRows = impl_getVisibleRows( false/*_bAcceptPartialVisibility*/ ); + if ( _nRow > m_nTopRow + nVisibleRows - 1 ) + impl_scrollRows( _nRow - ( m_nTopRow + nVisibleRows - 1 ) ); + } + } + + + OUString TableControl_Impl::getCellContentAsString( RowPos const i_row, ColPos const i_col ) + { + Any aCellValue; + m_pModel->getCellContent( i_col, i_row, aCellValue ); + + OUString sCellStringContent; + m_pModel->getRenderer()->GetFormattedCellString( aCellValue, sCellStringContent ); + + return sCellStringContent; + } + + + TableSize TableControl_Impl::impl_ni_ScrollRows( TableSize _nRowDelta ) + { + // compute new top row + RowPos nNewTopRow = + ::std::max( + ::std::min( static_cast<RowPos>( m_nTopRow + _nRowDelta ), static_cast<RowPos>( m_nRowCount - 1 ) ), + RowPos(0) + ); + + RowPos nOldTopRow = m_nTopRow; + m_nTopRow = nNewTopRow; + + // if updates are enabled currently, scroll the viewport + if ( m_nTopRow != nOldTopRow ) + { + SuppressCursor aHideCursor( *this ); + // TODO: call an onStartScroll at our listener (or better an own onStartScroll, + // which hides the cursor and then calls the listener) + // Same for onEndScroll + + // scroll the view port, if possible + long nPixelDelta = m_nRowHeightPixel * ( m_nTopRow - nOldTopRow ); + + tools::Rectangle aDataArea( Point( 0, m_nColHeaderHeightPixel ), m_pDataWindow->GetOutputSizePixel() ); + + if ( m_pDataWindow->GetBackground().IsScrollable() + && std::abs( nPixelDelta ) < aDataArea.GetHeight() + ) + { + m_pDataWindow->Scroll( 0, static_cast<long>(-nPixelDelta), aDataArea, ScrollFlags::Clip | ScrollFlags::Update | ScrollFlags::Children); + } + else + { + m_pDataWindow->Invalidate( InvalidateFlags::Update ); + m_pDataWindow->GetParent()->Invalidate( InvalidateFlags::Transparent ); + } + + // update the position at the vertical scrollbar + if ( m_pVScroll != nullptr ) + m_pVScroll->SetThumbPos( m_nTopRow ); + } + + // The scroll bar availability might change when we scrolled. + // For instance, imagine a view with 10 rows, if which 5 fit into the window, numbered 1 to 10. + // Now let + // - the user scroll to row number 6, so the last 5 rows are visible + // - somebody remove the last 4 rows + // - the user scroll to row number 5 being the top row, so the last two rows are visible + // - somebody remove row number 6 + // - the user scroll to row number 1 + // => in this case, the need for the scrollbar vanishes immediately. + if ( m_nTopRow == 0 ) + m_rAntiImpl.PostUserEvent( LINK( this, TableControl_Impl, OnUpdateScrollbars ) ); + + return static_cast<TableSize>( m_nTopRow - nOldTopRow ); + } + + + TableSize TableControl_Impl::impl_scrollRows( TableSize const i_rowDelta ) + { + return impl_ni_ScrollRows( i_rowDelta ); + } + + + TableSize TableControl_Impl::impl_ni_ScrollColumns( TableSize _nColumnDelta ) + { + // compute new left column + const ColPos nNewLeftColumn = + ::std::max( + ::std::min( static_cast<ColPos>( m_nLeftColumn + _nColumnDelta ), static_cast<ColPos>( m_nColumnCount - 1 ) ), + ColPos(0) + ); + + const ColPos nOldLeftColumn = m_nLeftColumn; + m_nLeftColumn = nNewLeftColumn; + + // if updates are enabled currently, scroll the viewport + if ( m_nLeftColumn != nOldLeftColumn ) + { + SuppressCursor aHideCursor( *this ); + // TODO: call an onStartScroll at our listener (or better an own onStartScroll, + // which hides the cursor and then calls the listener) + // Same for onEndScroll + + // scroll the view port, if possible + const tools::Rectangle aDataArea( Point( m_nRowHeaderWidthPixel, 0 ), m_pDataWindow->GetOutputSizePixel() ); + + long nPixelDelta = + m_aColumnWidths[ nOldLeftColumn ].getStart() + - m_aColumnWidths[ m_nLeftColumn ].getStart(); + + // update our column positions + // Do this *before* scrolling, as ScrollFlags::Update will trigger a paint, which already needs the correct + // information in m_aColumnWidths + for (auto & columnWidth : m_aColumnWidths) + { + columnWidth.move(nPixelDelta); + } + + // scroll the window content (if supported and possible), or invalidate the complete window + if ( m_pDataWindow->GetBackground().IsScrollable() + && std::abs( nPixelDelta ) < aDataArea.GetWidth() + ) + { + m_pDataWindow->Scroll( nPixelDelta, 0, aDataArea, ScrollFlags::Clip | ScrollFlags::Update ); + } + else + { + m_pDataWindow->Invalidate( InvalidateFlags::Update ); + m_pDataWindow->GetParent()->Invalidate( InvalidateFlags::Transparent ); + } + + // update the position at the horizontal scrollbar + if ( m_pHScroll != nullptr ) + m_pHScroll->SetThumbPos( m_nLeftColumn ); + } + + // The scroll bar availability might change when we scrolled. This is because we do not hide + // the scrollbar when it is, in theory, unnecessary, but currently at a position > 0. In this case, it will + // be auto-hidden when it's scrolled back to pos 0. + if ( m_nLeftColumn == 0 ) + m_rAntiImpl.PostUserEvent( LINK( this, TableControl_Impl, OnUpdateScrollbars ) ); + + return static_cast<TableSize>( m_nLeftColumn - nOldLeftColumn ); + } + + + TableSize TableControl_Impl::impl_scrollColumns( TableSize const i_columnDelta ) + { + return impl_ni_ScrollColumns( i_columnDelta ); + } + + + SelectionEngine* TableControl_Impl::getSelEngine() + { + return m_pSelEngine.get(); + } + + bool TableControl_Impl::isRowSelected( RowPos i_row ) const + { + return ::std::find( m_aSelectedRows.begin(), m_aSelectedRows.end(), i_row ) != m_aSelectedRows.end(); + } + + + RowPos TableControl_Impl::getSelectedRowIndex( size_t const i_selectionIndex ) const + { + if ( i_selectionIndex < m_aSelectedRows.size() ) + return m_aSelectedRows[ i_selectionIndex ]; + return ROW_INVALID; + } + + + int TableControl_Impl::getRowSelectedNumber(const ::std::vector<RowPos>& selectedRows, RowPos current) + { + std::vector<RowPos>::const_iterator it = ::std::find(selectedRows.begin(),selectedRows.end(),current); + if ( it != selectedRows.end() ) + { + return it - selectedRows.begin(); + } + return -1; + } + + + ColPos TableControl_Impl::impl_getColumnForOrdinate( long const i_ordinate ) const + { + if ( ( m_aColumnWidths.empty() ) || ( i_ordinate < 0 ) ) + return COL_INVALID; + + if ( i_ordinate < m_nRowHeaderWidthPixel ) + return COL_ROW_HEADERS; + + ColumnPositions::const_iterator lowerBound = ::std::lower_bound( + m_aColumnWidths.begin(), + m_aColumnWidths.end(), + MutableColumnMetrics(i_ordinate+1, i_ordinate+1), + ColumnInfoPositionLess() + ); + if ( lowerBound == m_aColumnWidths.end() ) + { + // point is *behind* the start of the last column ... + if ( i_ordinate < m_aColumnWidths.rbegin()->getEnd() ) + // ... but still before its end + return m_nColumnCount - 1; + return COL_INVALID; + } + return lowerBound - m_aColumnWidths.begin(); + } + + + RowPos TableControl_Impl::impl_getRowForAbscissa( long const i_abscissa ) const + { + if ( i_abscissa < 0 ) + return ROW_INVALID; + + if ( i_abscissa < m_nColHeaderHeightPixel ) + return ROW_COL_HEADERS; + + long const abscissa = i_abscissa - m_nColHeaderHeightPixel; + long const row = m_nTopRow + abscissa / m_nRowHeightPixel; + return row < m_pModel->getRowCount() ? row : ROW_INVALID; + } + + + bool TableControl_Impl::markRowAsDeselected( RowPos const i_rowIndex ) + { + ::std::vector< RowPos >::iterator selPos = ::std::find( m_aSelectedRows.begin(), m_aSelectedRows.end(), i_rowIndex ); + if ( selPos == m_aSelectedRows.end() ) + return false; + + m_aSelectedRows.erase( selPos ); + return true; + } + + + bool TableControl_Impl::markRowAsSelected( RowPos const i_rowIndex ) + { + if ( isRowSelected( i_rowIndex ) ) + return false; + + SelectionMode const eSelMode = getSelEngine()->GetSelectionMode(); + switch ( eSelMode ) + { + case SelectionMode::Single: + if ( !m_aSelectedRows.empty() ) + { + OSL_ENSURE( m_aSelectedRows.size() == 1, "TableControl::markRowAsSelected: SingleSelection with more than one selected element?" ); + m_aSelectedRows[0] = i_rowIndex; + break; + } + [[fallthrough]]; + + case SelectionMode::Multiple: + m_aSelectedRows.push_back( i_rowIndex ); + break; + + default: + OSL_ENSURE( false, "TableControl_Impl::markRowAsSelected: unsupported selection mode!" ); + return false; + } + + return true; + } + + + bool TableControl_Impl::markAllRowsAsDeselected() + { + if ( m_aSelectedRows.empty() ) + return false; + + m_aSelectedRows.clear(); + return true; + } + + + bool TableControl_Impl::markAllRowsAsSelected() + { + SelectionMode const eSelMode = getSelEngine()->GetSelectionMode(); + ENSURE_OR_RETURN_FALSE( eSelMode == SelectionMode::Multiple, "TableControl_Impl::markAllRowsAsSelected: unsupported selection mode!" ); + + if ( m_aSelectedRows.size() == size_t( m_pModel->getRowCount() ) ) + { + #if OSL_DEBUG_LEVEL > 0 + for ( TableSize row = 0; row < m_pModel->getRowCount(); ++row ) + { + OSL_ENSURE( isRowSelected( row ), "TableControl_Impl::markAllRowsAsSelected: inconsistency in the selected rows!" ); + } + #endif + // already all rows marked as selected + return false; + } + + m_aSelectedRows.clear(); + for ( RowPos i=0; i < m_pModel->getRowCount(); ++i ) + m_aSelectedRows.push_back(i); + + return true; + } + + + void TableControl_Impl::commitAccessibleEvent( sal_Int16 const i_eventID ) + { + impl_commitAccessibleEvent( i_eventID, Any() ); + } + + + void TableControl_Impl::commitCellEvent( sal_Int16 const i_eventID, const Any& i_newValue, const Any& i_oldValue ) + { + if ( impl_isAccessibleAlive() ) + m_pAccessibleTable->commitCellEvent( i_eventID, i_newValue, i_oldValue ); + } + + + void TableControl_Impl::commitTableEvent( sal_Int16 const i_eventID, const Any& i_newValue, const Any& i_oldValue ) + { + if ( impl_isAccessibleAlive() ) + m_pAccessibleTable->commitTableEvent( i_eventID, i_newValue, i_oldValue ); + } + + + tools::Rectangle TableControl_Impl::calcHeaderRect(bool bColHeader) + { + tools::Rectangle const aRectTableWithHeaders( impl_getAllVisibleCellsArea() ); + Size const aSizeTableWithHeaders( aRectTableWithHeaders.GetSize() ); + if ( bColHeader ) + return tools::Rectangle( aRectTableWithHeaders.TopLeft(), Size( aSizeTableWithHeaders.Width(), m_nColHeaderHeightPixel ) ); + else + return tools::Rectangle( aRectTableWithHeaders.TopLeft(), Size( m_nRowHeaderWidthPixel, aSizeTableWithHeaders.Height() ) ); + } + + + tools::Rectangle TableControl_Impl::calcHeaderCellRect( bool bColHeader, sal_Int32 nPos ) + { + tools::Rectangle const aHeaderRect = calcHeaderRect( bColHeader ); + TableCellGeometry const aGeometry( + *this, aHeaderRect, + bColHeader ? nPos : COL_ROW_HEADERS, + bColHeader ? ROW_COL_HEADERS : nPos + ); + return aGeometry.getRect(); + } + + + tools::Rectangle TableControl_Impl::calcTableRect() + { + return impl_getAllVisibleDataCellArea(); + } + + + tools::Rectangle TableControl_Impl::calcCellRect( sal_Int32 nRow, sal_Int32 nCol ) + { + tools::Rectangle aCellRect; + impl_getCellRect( nRow, nCol, aCellRect ); + return aCellRect; + } + + + IMPL_LINK_NOARG( TableControl_Impl, OnUpdateScrollbars, void*, void ) + { + // TODO: can't we simply use lcl_updateScrollbar here, so the scrollbars ranges are updated, instead of + // doing a complete re-layout? + impl_ni_relayout(); + } + + + IMPL_LINK( TableControl_Impl, OnScroll, ScrollBar*, _pScrollbar, void ) + { + DBG_ASSERT( ( _pScrollbar == m_pVScroll ) || ( _pScrollbar == m_pHScroll ), + "TableControl_Impl::OnScroll: where did this come from?" ); + + if ( _pScrollbar == m_pVScroll ) + impl_ni_ScrollRows( _pScrollbar->GetDelta() ); + else + impl_ni_ScrollColumns( _pScrollbar->GetDelta() ); + } + + + Reference< XAccessible > TableControl_Impl::getAccessible( vcl::Window& i_parentWindow ) + { + DBG_TESTSOLARMUTEX(); + if ( m_pAccessibleTable == nullptr ) + { + Reference< XAccessible > const xAccParent = i_parentWindow.GetAccessible(); + if ( xAccParent.is() ) + { + m_pAccessibleTable = m_aFactoryAccess.getFactory().createAccessibleTableControl( + xAccParent, m_rAntiImpl + ); + } + } + + Reference< XAccessible > xAccessible; + if ( m_pAccessibleTable ) + xAccessible = m_pAccessibleTable->getMyself(); + return xAccessible; + } + + + void TableControl_Impl::disposeAccessible() + { + if ( m_pAccessibleTable ) + m_pAccessibleTable->DisposeAccessImpl(); + m_pAccessibleTable = nullptr; + } + + + bool TableControl_Impl::impl_isAccessibleAlive() const + { + return ( nullptr != m_pAccessibleTable ) && m_pAccessibleTable->isAlive(); + } + + + void TableControl_Impl::impl_commitAccessibleEvent( sal_Int16 const i_eventID, Any const & i_newValue ) + { + if ( impl_isAccessibleAlive() ) + m_pAccessibleTable->commitEvent( i_eventID, i_newValue ); + } + + + //= TableFunctionSet + + + TableFunctionSet::TableFunctionSet(TableControl_Impl* _pTableControl) + :m_pTableControl( _pTableControl) + ,m_nCurrentRow( ROW_INVALID ) + { + } + + TableFunctionSet::~TableFunctionSet() + { + } + + void TableFunctionSet::BeginDrag() + { + } + + void TableFunctionSet::CreateAnchor() + { + m_pTableControl->setAnchor( m_pTableControl->getCurRow() ); + } + + + void TableFunctionSet::DestroyAnchor() + { + m_pTableControl->setAnchor( ROW_INVALID ); + } + + + void TableFunctionSet::SetCursorAtPoint(const Point& rPoint, bool bDontSelectAtCursor) + { + // newRow is the row which includes the point, getCurRow() is the last selected row, before the mouse click + RowPos newRow = m_pTableControl->getRowAtPoint( rPoint ); + if ( newRow == ROW_COL_HEADERS ) + newRow = m_pTableControl->getTopRow(); + + ColPos newCol = m_pTableControl->getColAtPoint( rPoint ); + if ( newCol == COL_ROW_HEADERS ) + newCol = m_pTableControl->getLeftColumn(); + + if ( ( newRow == ROW_INVALID ) || ( newCol == COL_INVALID ) ) + return; + + if ( bDontSelectAtCursor ) + { + if ( m_pTableControl->getSelectedRowCount() > 1 ) + m_pTableControl->getSelEngine()->AddAlways(true); + } + else if ( m_pTableControl->getAnchor() == m_pTableControl->getCurRow() ) + { + //selected region lies above the last selection + if( m_pTableControl->getCurRow() >= newRow) + { + //put selected rows in vector + while ( m_pTableControl->getAnchor() >= newRow ) + { + m_pTableControl->markRowAsSelected( m_pTableControl->getAnchor() ); + m_pTableControl->setAnchor( m_pTableControl->getAnchor() - 1 ); + } + m_pTableControl->setAnchor( m_pTableControl->getAnchor() + 1 ); + } + //selected region lies beneath the last selected row + else + { + while ( m_pTableControl->getAnchor() <= newRow ) + { + m_pTableControl->markRowAsSelected( m_pTableControl->getAnchor() ); + m_pTableControl->setAnchor( m_pTableControl->getAnchor() + 1 ); + } + m_pTableControl->setAnchor( m_pTableControl->getAnchor() - 1 ); + } + m_pTableControl->invalidateSelectedRegion( m_pTableControl->getCurRow(), newRow ); + } + //no region selected + else + { + if ( !m_pTableControl->hasRowSelection() ) + m_pTableControl->markRowAsSelected( newRow ); + else + { + if ( m_pTableControl->getSelEngine()->GetSelectionMode() == SelectionMode::Single ) + { + DeselectAll(); + m_pTableControl->markRowAsSelected( newRow ); + } + else + { + m_pTableControl->markRowAsSelected( newRow ); + } + } + if ( m_pTableControl->getSelectedRowCount() > 1 && m_pTableControl->getSelEngine()->GetSelectionMode() != SelectionMode::Single ) + m_pTableControl->getSelEngine()->AddAlways(true); + + m_pTableControl->invalidateRow( newRow ); + } + m_pTableControl->goTo( newCol, newRow ); + } + + bool TableFunctionSet::IsSelectionAtPoint( const Point& rPoint ) + { + m_pTableControl->getSelEngine()->AddAlways(false); + if ( !m_pTableControl->hasRowSelection() ) + return false; + else + { + RowPos curRow = m_pTableControl->getRowAtPoint( rPoint ); + m_pTableControl->setAnchor( ROW_INVALID ); + bool selected = m_pTableControl->isRowSelected( curRow ); + m_nCurrentRow = curRow; + return selected; + } + } + + void TableFunctionSet::DeselectAtPoint( const Point& ) + { + m_pTableControl->invalidateRow( m_nCurrentRow ); + m_pTableControl->markRowAsDeselected( m_nCurrentRow ); + } + + + void TableFunctionSet::DeselectAll() + { + if ( m_pTableControl->hasRowSelection() ) + { + for ( size_t i=0; i<m_pTableControl->getSelectedRowCount(); ++i ) + { + RowPos const rowIndex = m_pTableControl->getSelectedRowIndex(i); + m_pTableControl->invalidateRow( rowIndex ); + } + + m_pTableControl->markAllRowsAsDeselected(); + } + } + + +} // namespace svt::table + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/table/tablecontrol_impl.hxx b/svtools/source/table/tablecontrol_impl.hxx new file mode 100644 index 000000000..9e512e99a --- /dev/null +++ b/svtools/source/table/tablecontrol_impl.hxx @@ -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 <table/tablemodel.hxx> +#include <table/tablecontrolinterface.hxx> + +#include <vcl/svtaccessiblefactory.hxx> +#include <vcl/accessibletable.hxx> + +#include <vcl/seleng.hxx> + +#include <vector> + +class ScrollBar; +class ScrollBarBox; + +namespace svt::table +{ + struct MutableColumnMetrics : public ColumnMetrics + { + MutableColumnMetrics() + :ColumnMetrics() + { + } + + MutableColumnMetrics( long const i_startPixel, long const i_endPixel ) + :ColumnMetrics( i_startPixel, i_endPixel ) + { + } + + long getStart() const { return nStartPixel; } + long getEnd() const { return nEndPixel; } + + void move( long const i_offset ) { nStartPixel += i_offset; nEndPixel += i_offset; } + + long getWidth() const { return nEndPixel - nStartPixel; } + }; + + struct ColumnInfoPositionLess + { + bool operator()( MutableColumnMetrics const& i_lhs, MutableColumnMetrics const& i_rhs ) + { + return i_lhs.getEnd() < i_rhs.getStart(); + } + }; + + typedef ::std::vector< MutableColumnMetrics > ColumnPositions; + + class TableControl; + class TableDataWindow; + class TableFunctionSet; + + + //= TableControl_Impl + + class TableControl_Impl :public ITableControl + ,public ITableModelListener + { + friend class TableGeometry; + friend class TableRowGeometry; + friend class TableColumnGeometry; + friend class SuspendInvariants; + + private: + /// the control whose impl-instance we implement + TableControl& m_rAntiImpl; + /// the model of the table control + PTableModel m_pModel; + /// the input handler to use, usually the input handler as provided by ->m_pModel + PTableInputHandler m_pInputHandler; + /// info about the widths of our columns + ColumnPositions m_aColumnWidths; + + /// the height of a single row in the table, measured in pixels + long m_nRowHeightPixel; + /// the height of the column header row in the table, measured in pixels + long m_nColHeaderHeightPixel; + /// the width of the row header column in the table, measured in pixels + long m_nRowHeaderWidthPixel; + + /// the number of columns in the table control. Cached model value. + TableSize m_nColumnCount; + + /// the number of rows in the table control. Cached model value. + TableSize m_nRowCount; + + ColPos m_nCurColumn; + RowPos m_nCurRow; + ColPos m_nLeftColumn; + RowPos m_nTopRow; + + sal_Int32 m_nCursorHidden; + + /** the window to contain all data content, including header bars + + The window's upper left corner is at position (0,0), relative to the + table control, which is the direct parent of the data window. + */ + VclPtr<TableDataWindow> m_pDataWindow; + /// the vertical scrollbar, if any + VclPtr<ScrollBar> m_pVScroll; + /// the horizontal scrollbar, if any + VclPtr<ScrollBar> m_pHScroll; + VclPtr<ScrollBarBox> m_pScrollCorner; + //selection engine - for determining selection range, e.g. single, multiple + std::unique_ptr<SelectionEngine> m_pSelEngine; + //vector which contains the selected rows + std::vector<RowPos> m_aSelectedRows; + //part of selection engine + std::unique_ptr<TableFunctionSet> m_pTableFunctionSet; + //part of selection engine + RowPos m_nAnchor; + bool m_bUpdatingColWidths; + + vcl::AccessibleFactoryAccess m_aFactoryAccess; + vcl::table::IAccessibleTableControl* m_pAccessibleTable; + + public: + void setModel( const PTableModel& _pModel ); + + const PTableInputHandler& getInputHandler() const { return m_pInputHandler; } + + RowPos getCurRow() const { return m_nCurRow; } + + RowPos getAnchor() const { return m_nAnchor; } + void setAnchor( RowPos const i_anchor ) { m_nAnchor = i_anchor; } + + RowPos getTopRow() const { return m_nTopRow; } + ColPos getLeftColumn() const { return m_nLeftColumn; } + + const TableControl& getAntiImpl() const { return m_rAntiImpl; } + TableControl& getAntiImpl() { return m_rAntiImpl; } + + public: + explicit TableControl_Impl( TableControl& _rAntiImpl ); + virtual ~TableControl_Impl() override; + + /** to be called when the anti-impl instance has been resized + */ + void onResize(); + + /** paints the table control content which intersects with the given rectangle + */ + void doPaintContent(vcl::RenderContext& rRenderContext, const tools::Rectangle& _rUpdateRect); + + /** moves the cursor to the cell with the given coordinates + + To ease the caller's code, the coordinates must not necessarily denote a + valid position. If they don't, <FALSE/> will be returned. + */ + bool goTo( ColPos _nColumn, RowPos _nRow ); + + /** ensures that the given coordinate is visible + @param _nColumn + the column position which should be visible. Must be non-negative, and smaller + than the column count. + @param _nRow + the row position which should be visibleMust be non-negative, and smaller + than the row count. + */ + void ensureVisible( ColPos _nColumn, RowPos _nRow ); + + /** retrieves the content of the given cell, converted to a string + */ + OUString getCellContentAsString( RowPos const i_row, ColPos const i_col ); + + /** returns the position of the current row in the selection vector */ + static int getRowSelectedNumber(const ::std::vector<RowPos>& selectedRows, RowPos current); + + void invalidateRect(const tools::Rectangle &rInvalidateRect); + + /** ??? */ + void invalidateSelectedRegion( RowPos _nPrevRow, RowPos _nCurRow ); + + /** invalidates the part of the data window which is covered by the given rows + @param i_firstRow + the index of the first row to include in the invalidation + @param i_lastRow + the index of the last row to include in the invalidation, or ROW_INVALID if the invalidation + should happen down to the bottom of the data window. + */ + void invalidateRowRange( RowPos const i_firstRow, RowPos const i_lastRow ); + + /** invalidates the part of the data window which is covered by the given row + */ + void invalidateRow( RowPos const i_row ) { invalidateRowRange( i_row, i_row ); } + + /** invalidates all selected rows + */ + void invalidateSelectedRows(); + + void checkCursorPosition(); + + bool hasRowSelection() const { return !m_aSelectedRows.empty(); } + size_t getSelectedRowCount() const { return m_aSelectedRows.size(); } + RowPos getSelectedRowIndex( size_t const i_selectionIndex ) const; + + /** removes the given row index from m_aSelectedRows + + @return + <TRUE/> if and only if the row was previously marked as selected + */ + bool markRowAsDeselected( RowPos const i_rowIndex ); + + /** marks the given row as selected, by putting it into m_aSelectedRows + @return + <TRUE/> if and only if the row was previously <em>not</em> marked as selected + */ + bool markRowAsSelected( RowPos const i_rowIndex ); + + /** marks all rows as deselected + @return + <TRUE/> if and only if the selection actually changed by this operation + */ + bool markAllRowsAsDeselected(); + + /** marks all rows as selected + @return + <FALSE/> if and only if all rows were selected already. + */ + bool markAllRowsAsSelected(); + + void commitAccessibleEvent( sal_Int16 const i_eventID ); + void commitCellEvent( sal_Int16 const i_eventID, const css::uno::Any& i_newValue, const css::uno::Any& i_oldValue ); + void commitTableEvent( sal_Int16 const i_eventID, const css::uno::Any& i_newValue, const css::uno::Any& i_oldValue ); + + // ITableControl + virtual void hideCursor() override; + virtual void showCursor() override; + virtual bool dispatchAction( TableControlAction _eAction ) override; + virtual SelectionEngine* getSelEngine() override; + virtual PTableModel getModel() const override; + virtual ColPos getCurrentColumn() const override; + virtual RowPos getCurrentRow() const override; + virtual void activateCell( ColPos const i_col, RowPos const i_row ) override; + virtual ::Size getTableSizePixel() const override; + virtual void setPointer( PointerStyle i_pointer ) override; + virtual void captureMouse() override; + virtual void releaseMouse() override; + virtual void invalidate( TableArea const i_what ) override; + virtual long pixelWidthToAppFont( long const i_pixels ) const override; + virtual void hideTracking() override; + virtual void showTracking( tools::Rectangle const & i_location, ShowTrackFlags const i_flags ) override; + RowPos getRowAtPoint( const Point& rPoint ) const; + ColPos getColAtPoint( const Point& rPoint ) const; + virtual TableCell hitTest( const Point& rPoint ) const override; + virtual ColumnMetrics getColumnMetrics( ColPos const i_column ) const override; + virtual bool isRowSelected( RowPos i_row ) const override; + + + long appFontWidthToPixel( long const i_appFontUnits ) const; + + TableDataWindow& getDataWindow() { return *m_pDataWindow; } + const TableDataWindow& getDataWindow() const { return *m_pDataWindow; } + ScrollBar* getHorzScrollbar() { return m_pHScroll; } + ScrollBar* getVertScrollbar() { return m_pVScroll; } + + tools::Rectangle calcHeaderRect( bool bColHeader ); + tools::Rectangle calcHeaderCellRect( bool bColHeader, sal_Int32 nPos ); + tools::Rectangle calcTableRect(); + tools::Rectangle calcCellRect( sal_Int32 nRow, sal_Int32 nCol ); + + // A11Y + css::uno::Reference< css::accessibility::XAccessible > + getAccessible( vcl::Window& i_parentWindow ); + void disposeAccessible(); + + bool isAccessibleAlive() const { return impl_isAccessibleAlive(); } + + // ITableModelListener + virtual void rowsInserted( RowPos first, RowPos last ) override; + virtual void rowsRemoved( RowPos first, RowPos last ) override; + virtual void columnInserted() override; + virtual void columnRemoved() override; + virtual void allColumnsRemoved() override; + virtual void cellsUpdated( RowPos const i_firstRow, RowPos const i_lastRow ) override; + virtual void columnChanged( ColPos const i_column, ColumnAttributeGroup const i_attributeGroup ) override; + virtual void tableMetricsChanged() override; + + private: + bool impl_isAccessibleAlive() const; + void impl_commitAccessibleEvent( + sal_Int16 const i_eventID, + css::uno::Any const & i_newValue + ); + + /** toggles the cursor visibility + + The method is not bound to the classes public invariants, as it's used in + situations where the they must not necessarily be fulfilled. + */ + void impl_ni_doSwitchCursor( bool _bOn ); + + /** returns the number of visible rows. + + @param _bAcceptPartialRow + specifies whether a possible only partially visible last row is + counted, too. + */ + TableSize impl_getVisibleRows( bool _bAcceptPartialRow ) const; + + /** returns the number of visible columns + + The value may change with different horizontal scroll positions, as + different columns have different widths. For instance, if your control is + 100 pixels wide, and has three columns of width 50, 50, 100, respectively, + then this method will return either "2" or "1", depending on which column + is the first visible one. + + @param _bAcceptPartialRow + specifies whether a possible only partially visible last row is + counted, too. + */ + TableSize impl_getVisibleColumns( bool _bAcceptPartialCol ) const; + + /** determines the rectangle occupied by the given cell + */ + void impl_getCellRect( ColPos _nColumn, RowPos _nRow, tools::Rectangle& _rCellRect ) const; + + /** updates all cached model values + + The method is not bound to the classes public invariants, as it's used in + situations where the they must not necessarily be fulfilled. + */ + void impl_ni_updateCachedModelValues(); + + /** updates the cached table metrics (row height etc.) + */ + void impl_ni_updateCachedTableMetrics(); + + /** does a relayout of the table control + + Column widths, and consequently the availability of the vertical and horizontal scrollbar, are updated + with a call to this method. + + @param i_assumeInflexibleColumnsUpToIncluding + the index of a column up to which all columns should be considered as inflexible, or + <code>COL_INVALID</code>. + */ + void impl_ni_relayout( ColPos const i_assumeInflexibleColumnsUpToIncluding = COL_INVALID ); + + /** calculates the new width of our columns, taking into account their min and max widths, and their relative + flexibility. + + @param i_assumeInflexibleColumnsUpToIncluding + the index of a column up to which all columns should be considered as inflexible, or + <code>COL_INVALID</code>. + + @param i_assumeVerticalScrollbar + controls whether or not we should assume the presence of a vertical scrollbar. If <true/>, and + if the model has a VerticalScrollbarVisibility != ScrollbarShowNever, the method will leave + space for a vertical scrollbar. + + @return + the overall width of the grid, which is available for columns + */ + long impl_ni_calculateColumnWidths( + ColPos const i_assumeInflexibleColumnsUpToIncluding, + bool const i_assumeVerticalScrollbar, + ::std::vector< long >& o_newColWidthsPixel + ) const; + + /** positions all child windows, e.g. the both scrollbars, the corner window, and the data window + */ + void impl_ni_positionChildWindows( + tools::Rectangle const & i_dataCellPlayground, + bool const i_verticalScrollbar, + bool const i_horizontalScrollbar + ); + + /** scrolls the view by the given number of rows + + The method is not bound to the classes public invariants, as it's used in + situations where the they must not necessarily be fulfilled. + + @return + the number of rows by which the viewport was scrolled. This may differ + from the given numbers to scroll in case the begin or the end of the + row range were reached. + */ + TableSize impl_ni_ScrollRows( TableSize _nRowDelta ); + + /** equivalent to impl_ni_ScrollRows, but checks the instances invariants beforehand (in a non-product build only) + */ + TableSize impl_scrollRows( TableSize const i_rowDelta ); + + /** scrolls the view by the given number of columns + + The method is not bound to the classes public invariants, as it's used in + situations where the they must not necessarily be fulfilled. + + @return + the number of columns by which the viewport was scrolled. This may differ + from the given numbers to scroll in case the begin or the end of the + column range were reached. + */ + TableSize impl_ni_ScrollColumns( TableSize _nColumnDelta ); + + /** equivalent to impl_ni_ScrollColumns, but checks the instances invariants beforehand (in a non-product build only) + */ + TableSize impl_scrollColumns( TableSize const i_columnDelta ); + + /** retrieves the area occupied by the totality of (at least partially) visible cells + + The returned area includes row and column headers. Also, it takes into + account the fact that there might be less columns than would normally + find room in the control. + + As a result of respecting the partial visibility of rows and columns, + the returned area might be larger than the data window's output size. + */ + tools::Rectangle impl_getAllVisibleCellsArea() const; + + /** retrieves the area occupied by all (at least partially) visible data cells. + + Effectively, the returned area is the same as returned by ->impl_getAllVisibleCellsArea, + minus the row and column header areas. + */ + tools::Rectangle impl_getAllVisibleDataCellArea() const; + + /** retrieves the column which covers the given ordinate + */ + ColPos impl_getColumnForOrdinate( long const i_ordinate ) const; + + /** retrieves the row which covers the given abscissa + */ + RowPos impl_getRowForAbscissa( long const i_abscissa ) const; + + /// invalidates the window area occupied by the given column + void impl_invalidateColumn( ColPos const i_column ); + + DECL_LINK( OnScroll, ScrollBar*, void ); + DECL_LINK( OnUpdateScrollbars, void*, void ); + }; + + //see seleng.hxx, seleng.cxx, FunctionSet overridables, part of selection engine + class TableFunctionSet : public FunctionSet + { + private: + TableControl_Impl* m_pTableControl; + RowPos m_nCurrentRow; + + public: + explicit TableFunctionSet(TableControl_Impl* _pTableControl); + virtual ~TableFunctionSet() override; + + virtual void BeginDrag() override; + virtual void CreateAnchor() override; + virtual void DestroyAnchor() override; + virtual void SetCursorAtPoint(const Point& rPoint, bool bDontSelectAtCursor = false) override; + virtual bool IsSelectionAtPoint( const Point& rPoint ) override; + virtual void DeselectAtPoint( const Point& rPoint ) override; + virtual void DeselectAll() override; + }; + + +} // namespace svt::table + + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/table/tabledatawindow.cxx b/svtools/source/table/tabledatawindow.cxx new file mode 100644 index 000000000..837097516 --- /dev/null +++ b/svtools/source/table/tabledatawindow.cxx @@ -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 . + */ + +#include <table/tablecontrol.hxx> + +#include "tabledatawindow.hxx" +#include "tablecontrol_impl.hxx" +#include "tablegeometry.hxx" + +#include <vcl/help.hxx> +#include <vcl/settings.hxx> +#include <vcl/commandevent.hxx> + +namespace svt::table +{ + using css::uno::Any; + + TableDataWindow::TableDataWindow( TableControl_Impl& _rTableControl ) + :Window( &_rTableControl.getAntiImpl() ) + ,m_rTableControl( _rTableControl ) + { + // by default, use the background as determined by the style settings + const Color aWindowColor( GetSettings().GetStyleSettings().GetFieldColor() ); + SetBackground( Wallpaper( aWindowColor ) ); + SetFillColor( aWindowColor ); + } + + TableDataWindow::~TableDataWindow() + { + disposeOnce(); + } + + void TableDataWindow::dispose() + { + impl_hideTipWindow(); + Window::dispose(); + } + + void TableDataWindow::Paint( vcl::RenderContext& rRenderContext, const tools::Rectangle& rUpdateRect ) + { + m_rTableControl.doPaintContent(rRenderContext, rUpdateRect); + } + + void TableDataWindow::RequestHelp( const HelpEvent& rHEvt ) + { + HelpEventMode const nHelpMode = rHEvt.GetMode(); + if ( IsMouseCaptured() + || !( nHelpMode & HelpEventMode::QUICK ) + ) + { + Window::RequestHelp( rHEvt ); + return; + } + + OUString sHelpText; + QuickHelpFlags nHelpStyle = QuickHelpFlags::NONE; + + Point const aMousePos( ScreenToOutputPixel( rHEvt.GetMousePosPixel() ) ); + RowPos const hitRow = m_rTableControl.getRowAtPoint( aMousePos ); + ColPos const hitCol = m_rTableControl.getColAtPoint( aMousePos ); + + PTableModel const pTableModel( m_rTableControl.getModel() ); + if ( ( hitCol >= 0 ) && ( hitCol < pTableModel->getColumnCount() ) ) + { + if ( hitRow == ROW_COL_HEADERS ) + { + sHelpText = pTableModel->getColumnModel( hitCol )->getHelpText(); + } + else if ( ( hitRow >= 0 ) && ( hitRow < pTableModel->getRowCount() ) ) + { + Any aCellToolTip; + pTableModel->getCellToolTip( hitCol, hitRow, aCellToolTip ); + if ( !aCellToolTip.hasValue() ) + { + // use the cell content + pTableModel->getCellContent( hitCol, hitRow, aCellToolTip ); + + // use the cell content as tool tip only if it doesn't fit into the cell. + tools::Rectangle const aWindowRect( Point( 0, 0 ), GetOutputSizePixel() ); + TableCellGeometry const aCell( m_rTableControl, aWindowRect, hitCol, hitRow ); + tools::Rectangle const aCellRect( aCell.getRect() ); + + PTableRenderer const pRenderer = pTableModel->getRenderer(); + if ( pRenderer->FitsIntoCell( aCellToolTip, *this, aCellRect ) ) + aCellToolTip.clear(); + } + + pTableModel->getRenderer()->GetFormattedCellString( aCellToolTip, sHelpText ); + + if ( sHelpText.indexOf( '\n' ) >= 0 ) + nHelpStyle = QuickHelpFlags::TipStyleBalloon; + } + } + + if ( !sHelpText.isEmpty() ) + { + // hide the standard (singleton) help window, so we do not have two help windows open at the same time + Help::HideBalloonAndQuickHelp(); + + tools::Rectangle const aControlScreenRect( + OutputToScreenPixel( Point( 0, 0 ) ), + GetOutputSizePixel() + ); + + Help::ShowQuickHelp(this, aControlScreenRect, sHelpText, nHelpStyle); + } + else + { + impl_hideTipWindow(); + Window::RequestHelp( rHEvt ); + } + } + + void TableDataWindow::impl_hideTipWindow() + { + Help::HideBalloonAndQuickHelp(); + } + + void TableDataWindow::MouseMove( const MouseEvent& rMEvt ) + { + if ( rMEvt.IsLeaveWindow() ) + impl_hideTipWindow(); + + if ( !m_rTableControl.getInputHandler()->MouseMove( m_rTableControl, rMEvt ) ) + { + Window::MouseMove( rMEvt ); + } + } + + void TableDataWindow::MouseButtonDown( const MouseEvent& rMEvt ) + { + impl_hideTipWindow(); + + Point const aPoint = rMEvt.GetPosPixel(); + RowPos const hitRow = m_rTableControl.getRowAtPoint( aPoint ); + bool const wasRowSelected = m_rTableControl.isRowSelected( hitRow ); + size_t const nPrevSelRowCount = m_rTableControl.getSelectedRowCount(); + + if ( !m_rTableControl.getInputHandler()->MouseButtonDown( m_rTableControl, rMEvt ) ) + { + Window::MouseButtonDown( rMEvt ); + return; + } + + bool const isRowSelected = m_rTableControl.isRowSelected( hitRow ); + size_t const nCurSelRowCount = m_rTableControl.getSelectedRowCount(); + if ( isRowSelected != wasRowSelected || nCurSelRowCount != nPrevSelRowCount ) + { + m_aSelectHdl.Call( nullptr ); + } + } + + + void TableDataWindow::MouseButtonUp( const MouseEvent& rMEvt ) + { + if ( !m_rTableControl.getInputHandler()->MouseButtonUp( m_rTableControl, rMEvt ) ) + Window::MouseButtonUp( rMEvt ); + + m_rTableControl.getAntiImpl().GrabFocus(); + } + + + bool TableDataWindow::EventNotify(NotifyEvent& rNEvt ) + { + bool bDone = false; + if ( rNEvt.GetType() == MouseNotifyEvent::COMMAND ) + { + const CommandEvent& rCEvt = *rNEvt.GetCommandEvent(); + if ( rCEvt.GetCommand() == CommandEventId::Wheel ) + { + const CommandWheelData* pData = rCEvt.GetWheelData(); + if( !pData->GetModifier() && ( pData->GetMode() == CommandWheelMode::SCROLL ) ) + { + bDone = HandleScrollCommand( rCEvt, m_rTableControl.getHorzScrollbar(), m_rTableControl.getVertScrollbar() ); + } + } + } + return bDone || Window::EventNotify( rNEvt ); + } + +} // namespace svt::table + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/table/tabledatawindow.hxx b/svtools/source/table/tabledatawindow.hxx new file mode 100644 index 000000000..e42a05493 --- /dev/null +++ b/svtools/source/table/tabledatawindow.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 <vcl/window.hxx> + + +namespace svt::table +{ + class TableControl_Impl; + class TableFunctionSet; + + /** the window containing the content area (including headers) of + a table control + */ + class TableDataWindow : public vcl::Window + { + friend class TableFunctionSet; + private: + TableControl_Impl& m_rTableControl; + Link<LinkParamNone*,void> m_aSelectHdl; + + public: + explicit TableDataWindow( TableControl_Impl& _rTableControl ); + virtual ~TableDataWindow() override; + virtual void dispose() override; + + void SetSelectHdl(const Link<LinkParamNone*,void>& rLink) + { + m_aSelectHdl = rLink; + } + + // Window overridables + virtual void Paint(vcl::RenderContext& rRenderContext, const tools::Rectangle& rRect) override; + virtual void MouseMove( const MouseEvent& rMEvt) override; + virtual void MouseButtonDown( const MouseEvent& rMEvt) override; + virtual void MouseButtonUp( const MouseEvent& rMEvt) override; + virtual bool EventNotify(NotifyEvent& rNEvt) override; + virtual void RequestHelp( const HelpEvent& rHEvt ) override; + + private: + static void impl_hideTipWindow(); + }; + +} // namespace svt::table + + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/table/tablegeometry.cxx b/svtools/source/table/tablegeometry.cxx new file mode 100644 index 000000000..5b18826c5 --- /dev/null +++ b/svtools/source/table/tablegeometry.cxx @@ -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 . + */ + + +#include "tablegeometry.hxx" +#include "tablecontrol_impl.hxx" + + +namespace svt::table +{ + + + //= TableRowGeometry + + + TableRowGeometry::TableRowGeometry( TableControl_Impl const & _rControl, tools::Rectangle const & _rBoundaries, + RowPos const _nRow, bool const i_allowVirtualRows ) + :TableGeometry( _rControl, _rBoundaries ) + ,m_nRowPos( _nRow ) + ,m_bAllowVirtualRows( i_allowVirtualRows ) + { + if ( m_nRowPos == ROW_COL_HEADERS ) + { + m_aRect.SetTop( 0 ); + m_aRect.SetBottom( m_rControl.m_nColHeaderHeightPixel - 1 ); + } + else + { + impl_initRect(); + } + } + + + void TableRowGeometry::impl_initRect() + { + if ( ( m_nRowPos >= m_rControl.m_nTopRow ) && impl_isValidRow( m_nRowPos ) ) + { + m_aRect.SetTop( m_rControl.m_nColHeaderHeightPixel + ( m_nRowPos - m_rControl.m_nTopRow ) * m_rControl.m_nRowHeightPixel ); + m_aRect.SetBottom( m_aRect.Top() + m_rControl.m_nRowHeightPixel - 1 ); + } + else + m_aRect.SetEmpty(); + } + + + bool TableRowGeometry::impl_isValidRow( RowPos const i_row ) const + { + return m_bAllowVirtualRows || ( i_row < m_rControl.m_pModel->getRowCount() ); + } + + + bool TableRowGeometry::moveDown() + { + if ( m_nRowPos == ROW_COL_HEADERS ) + { + m_nRowPos = m_rControl.m_nTopRow; + impl_initRect(); + } + else + { + if ( impl_isValidRow( ++m_nRowPos ) ) + m_aRect.Move( 0, m_rControl.m_nRowHeightPixel ); + else + m_aRect.SetEmpty(); + } + return isValid(); + } + + + //= TableColumnGeometry + + + TableColumnGeometry::TableColumnGeometry( TableControl_Impl const & _rControl, tools::Rectangle const & _rBoundaries, + ColPos const _nCol ) + :TableGeometry( _rControl, _rBoundaries ) + ,m_nColPos( _nCol ) + { + if ( m_nColPos == COL_ROW_HEADERS ) + { + m_aRect.SetLeft( 0 ); + m_aRect.SetRight( m_rControl.m_nRowHeaderWidthPixel - 1 ); + } + else + { + impl_initRect(); + } + } + + + void TableColumnGeometry::impl_initRect() + { + ColPos nLeftColumn = m_rControl.m_nLeftColumn; + if ( ( m_nColPos >= nLeftColumn ) && impl_isValidColumn( m_nColPos ) ) + { + m_aRect.SetLeft( m_rControl.m_nRowHeaderWidthPixel ); + // TODO: take into account any possibly frozen columns + + for ( ColPos col = nLeftColumn; col < m_nColPos; ++col ) + m_aRect.AdjustLeft(m_rControl.m_aColumnWidths[ col ].getWidth() ); + m_aRect.SetRight( m_aRect.Left() + m_rControl.m_aColumnWidths[ m_nColPos ].getWidth() - 1 ); + } + else + m_aRect.SetEmpty(); + } + + + bool TableColumnGeometry::impl_isValidColumn( ColPos const i_column ) const + { + return i_column < ColPos( m_rControl.m_aColumnWidths.size() ); + } + + + bool TableColumnGeometry::moveRight() + { + if ( m_nColPos == COL_ROW_HEADERS ) + { + m_nColPos = m_rControl.m_nLeftColumn; + impl_initRect(); + } + else + { + if ( impl_isValidColumn( ++m_nColPos ) ) + { + m_aRect.SetLeft( m_aRect.Right() + 1 ); + m_aRect.AdjustRight(m_rControl.m_aColumnWidths[ m_nColPos ].getWidth() ); + } + else + m_aRect.SetEmpty(); + } + + return isValid(); + } + + +} // namespace svt::table + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/table/tablegeometry.hxx b/svtools/source/table/tablegeometry.hxx new file mode 100644 index 000000000..9fb6d03f0 --- /dev/null +++ b/svtools/source/table/tablegeometry.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 <table/tabletypes.hxx> + +#include <tools/gen.hxx> + + +namespace svt::table +{ + + + class TableControl_Impl; + + + //= TableGeometry + + class TableGeometry + { + protected: + const TableControl_Impl& m_rControl; + const tools::Rectangle& m_rBoundaries; + tools::Rectangle m_aRect; + + protected: + TableGeometry( + const TableControl_Impl& _rControl, + const tools::Rectangle& _rBoundaries + ) + :m_rControl( _rControl ) + ,m_rBoundaries( _rBoundaries ) + ,m_aRect( _rBoundaries ) + { + } + + public: + // attribute access + const TableControl_Impl& getControl() const { return m_rControl; } + + // status + const tools::Rectangle& getRect() const { return m_aRect; } + bool isValid() const { return !m_aRect.GetIntersection( m_rBoundaries ).IsEmpty(); } + }; + + + //= TableRowGeometry + + class TableRowGeometry final : public TableGeometry + { + public: + TableRowGeometry( + TableControl_Impl const & _rControl, + tools::Rectangle const & _rBoundaries, + RowPos const _nRow, + bool const i_allowVirtualRows = false + // allow rows >= getRowCount()? + ); + + // status + RowPos getRow() const { return m_nRowPos; } + // operations + bool moveDown(); + + private: + void impl_initRect(); + bool impl_isValidRow( RowPos const i_row ) const; + + RowPos m_nRowPos; + bool m_bAllowVirtualRows; + }; + + + //= TableColumnGeometry + + class TableColumnGeometry final : public TableGeometry + { + public: + TableColumnGeometry( + TableControl_Impl const & _rControl, + tools::Rectangle const & _rBoundaries, + ColPos const _nCol + ); + + // status + ColPos getCol() const { return m_nColPos; } + // operations + bool moveRight(); + + private: + void impl_initRect(); + bool impl_isValidColumn( ColPos const i_column ) const; + + ColPos m_nColPos; + }; + + + //= TableCellGeometry + + /** a helper representing geometry information of a cell + */ + class TableCellGeometry + { + private: + TableRowGeometry m_aRow; + TableColumnGeometry m_aCol; + + public: + TableCellGeometry( + TableControl_Impl const & _rControl, + tools::Rectangle const & _rBoundaries, + ColPos const _nCol, + RowPos const _nRow + ) + :m_aRow( _rControl, _rBoundaries, _nRow, false/*allowVirtualCells*/ ) + ,m_aCol( _rControl, _rBoundaries, _nCol ) + { + } + + TableCellGeometry( + const TableRowGeometry& _rRow, + ColPos _nCol + ) + :m_aRow( _rRow ) + ,m_aCol( _rRow.getControl(), _rRow.getRect(), _nCol ) + { + } + + tools::Rectangle getRect() const { return m_aRow.getRect().GetIntersection( m_aCol.getRect() ); } + ColPos getColumn() const { return m_aCol.getCol(); } + bool isValid() const { return !getRect().IsEmpty(); } + + bool moveRight() {return m_aCol.moveRight(); } + }; + + +} // namespace svt::table + + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/uno/addrtempuno.cxx b/svtools/source/uno/addrtempuno.cxx new file mode 100644 index 000000000..3d3a8c4a1 --- /dev/null +++ b/svtools/source/uno/addrtempuno.cxx @@ -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 . + */ + +#include <svtools/addresstemplate.hxx> +#include <svtools/genericunodialog.hxx> +#include <comphelper/proparrhlp.hxx> +#include <comphelper/propertysequence.hxx> +#include <com/sun/star/awt/XWindow.hpp> +#include <com/sun/star/beans/PropertyAttribute.hpp> +#include <com/sun/star/util/AliasProgrammaticPair.hpp> +#include <com/sun/star/sdbc/XDataSource.hpp> +#include <vcl/svapp.hxx> + +using namespace svt; + +namespace { + +#define UNODIALOG_PROPERTY_ID_ALIASES 100 +#define UNODIALOG_PROPERTY_ALIASES "FieldMapping" + + using namespace css::uno; + using namespace css::lang; + using namespace css::util; + using namespace css::beans; + using namespace css::sdbc; + + class OAddressBookSourceDialogUno + :public OGenericUnoDialog + ,public ::comphelper::OPropertyArrayUsageHelper< OAddressBookSourceDialogUno > + { + private: + Sequence< AliasProgrammaticPair > m_aAliases; + Reference< XDataSource > m_xDataSource; + OUString m_sDataSourceName; + OUString m_sTable; + + public: + explicit OAddressBookSourceDialogUno(const Reference< XComponentContext >& _rxORB); + + // XTypeProvider + virtual Sequence<sal_Int8> SAL_CALL getImplementationId( ) override; + + // XServiceInfo + virtual OUString SAL_CALL getImplementationName() override; + virtual css::uno::Sequence<OUString> SAL_CALL getSupportedServiceNames() override; + + // XPropertySet + virtual Reference< XPropertySetInfo> SAL_CALL getPropertySetInfo() override; + virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper() override; + + // OPropertyArrayUsageHelper + virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const override; + + virtual void SAL_CALL initialize(const Sequence< Any >& aArguments) override; + + protected: + // OGenericUnoDialog overridables + virtual std::unique_ptr<weld::DialogController> createDialog(const css::uno::Reference<css::awt::XWindow>& rParent) override; + + virtual void implInitialize(const css::uno::Any& _rValue) override; + + virtual void executedDialog(sal_Int16 _nExecutionResult) override; + }; + + + OAddressBookSourceDialogUno::OAddressBookSourceDialogUno(const Reference< XComponentContext >& _rxORB) + :OGenericUnoDialog(_rxORB) + { + registerProperty(UNODIALOG_PROPERTY_ALIASES, UNODIALOG_PROPERTY_ID_ALIASES, PropertyAttribute::READONLY, + &m_aAliases, cppu::UnoType<decltype(m_aAliases)>::get()); + } + + + Sequence<sal_Int8> SAL_CALL OAddressBookSourceDialogUno::getImplementationId( ) + { + return css::uno::Sequence<sal_Int8>(); + } + + + OUString SAL_CALL OAddressBookSourceDialogUno::getImplementationName() + { + return "com.sun.star.comp.svtools.OAddressBookSourceDialogUno"; + } + + + css::uno::Sequence<OUString> SAL_CALL OAddressBookSourceDialogUno::getSupportedServiceNames() + { + return { "com.sun.star.ui.AddressBookSourceDialog" }; + } + + + Reference<XPropertySetInfo> SAL_CALL OAddressBookSourceDialogUno::getPropertySetInfo() + { + Reference<XPropertySetInfo> xInfo( createPropertySetInfo( getInfoHelper() ) ); + return xInfo; + } + + ::cppu::IPropertyArrayHelper& OAddressBookSourceDialogUno::getInfoHelper() + { + return *getArrayHelper(); + } + + ::cppu::IPropertyArrayHelper* OAddressBookSourceDialogUno::createArrayHelper( ) const + { + Sequence< Property > aProps; + describeProperties(aProps); + return new ::cppu::OPropertyArrayHelper(aProps); + } + + void OAddressBookSourceDialogUno::executedDialog(sal_Int16 _nExecutionResult) + { + OGenericUnoDialog::executedDialog(_nExecutionResult); + + if ( _nExecutionResult && m_xDialog ) + static_cast<AddressBookSourceDialog*>(m_xDialog.get())->getFieldMapping(m_aAliases); + } + + void SAL_CALL OAddressBookSourceDialogUno::initialize(const Sequence< Any >& rArguments) + { + if( rArguments.getLength() == 5 ) + { + Reference<css::awt::XWindow> xParentWindow; + Reference<css::beans::XPropertySet> xDataSource; + OUString sDataSourceName; + OUString sCommand; + OUString sTitle; + if ( (rArguments[0] >>= xParentWindow) + && (rArguments[1] >>= xDataSource) + && (rArguments[2] >>= sDataSourceName) + && (rArguments[3] >>= sCommand) + && (rArguments[4] >>= sTitle) ) + { + + // convert the parameters for creating the dialog to PropertyValues + Sequence<Any> aArguments(comphelper::InitAnyPropertySequence( + { + {"ParentWindow", Any(xParentWindow)}, + {"DataSource", Any(xDataSource)}, + {"DataSourceName", Any(sDataSourceName)}, + {"Command", Any(sCommand)}, // the table to use + {"Title", Any(sTitle)} + })); + OGenericUnoDialog::initialize(aArguments); + return; + } + } + OGenericUnoDialog::initialize(rArguments); + } + + void OAddressBookSourceDialogUno::implInitialize(const css::uno::Any& _rValue) + { + PropertyValue aVal; + if (_rValue >>= aVal) + { + if (aVal.Name == "DataSource") + { + bool bSuccess = aVal.Value >>= m_xDataSource; + OSL_ENSURE( bSuccess, "OAddressBookSourceDialogUno::implInitialize: invalid type for DataSource!" ); + return; + } + + if (aVal.Name == "DataSourceName") + { + bool bSuccess = aVal.Value >>= m_sDataSourceName; + OSL_ENSURE( bSuccess, "OAddressBookSourceDialogUno::implInitialize: invalid type for DataSourceName!" ); + return; + } + + if (aVal.Name == "Command") + { + bool bSuccess = aVal.Value >>= m_sTable; + OSL_ENSURE( bSuccess, "OAddressBookSourceDialogUno::implInitialize: invalid type for Command!" ); + return; + } + } + + OGenericUnoDialog::implInitialize( _rValue ); + } + + std::unique_ptr<weld::DialogController> OAddressBookSourceDialogUno::createDialog(const css::uno::Reference<css::awt::XWindow>& rParent) + { + weld::Window* pParent = Application::GetFrameWeld(rParent); + if ( m_xDataSource.is() && !m_sTable.isEmpty() ) + return std::make_unique<AddressBookSourceDialog>(pParent, m_aContext, m_xDataSource, m_sDataSourceName, m_sTable, m_aAliases); + return std::make_unique<AddressBookSourceDialog>(pParent, m_aContext); + } +} + +extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface * +com_sun_star_comp_svtools_OAddressBookSourceDialogUno_get_implementation( + css::uno::XComponentContext * context, + css::uno::Sequence<css::uno::Any> const &) +{ + return cppu::acquire(new OAddressBookSourceDialogUno(context)); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/uno/fpicker.cxx b/svtools/source/uno/fpicker.cxx new file mode 100644 index 000000000..076f59a8d --- /dev/null +++ b/svtools/source/uno/fpicker.cxx @@ -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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <rtl/ustring.hxx> + +#include <com/sun/star/lang/XMultiComponentFactory.hpp> + +#include <svtools/miscopt.hxx> +#include <svl/pickerhistoryaccess.hxx> + +#include <vcl/svapp.hxx> + +#include "fpicker.hxx" + +using css::uno::Reference; +using css::uno::Sequence; + +/* + * FilePicker implementation. + */ +static OUString FilePicker_getSystemPickerServiceName() +{ +#ifdef UNX + OUString aDesktopEnvironment (Application::GetDesktopEnvironment()); + if (aDesktopEnvironment.equalsIgnoreAsciiCase("macosx")) + return "com.sun.star.ui.dialogs.AquaFilePicker"; + else + return "com.sun.star.ui.dialogs.SystemFilePicker"; +#endif +#ifdef _WIN32 + return "com.sun.star.ui.dialogs.Win32FilePicker"; +#endif +} + +Reference< css::uno::XInterface > FilePicker_CreateInstance ( + Reference< css::uno::XComponentContext > const & context) +{ + Reference< css::uno::XInterface > xResult; + + if (!context.is()) + return xResult; + + Reference< css::lang::XMultiComponentFactory > xFactory (context->getServiceManager()); + if (xFactory.is() && SvtMiscOptions().UseSystemFileDialog()) + { + xResult.set( Application::createFilePicker( context ) ); + + if (!xResult.is()) + { + try + { + xResult = xFactory->createInstanceWithContext ( + FilePicker_getSystemPickerServiceName(), + context); + } + catch (css::uno::Exception const &) + { + // Handled below (see @ fallback). + } + } + } + + + if (!xResult.is() && xFactory.is()) + { + // Always fall back to OfficeFilePicker. + xResult = xFactory->createInstanceWithContext ( + "com.sun.star.ui.dialogs.OfficeFilePicker", + context); + } + if (xResult.is()) + { + // Add to FilePicker history. + svt::addFilePicker (xResult); + } + return xResult; +} + +OUString FilePicker_getImplementationName() +{ + return "com.sun.star.comp.svt.FilePicker"; +} + +Sequence< OUString > FilePicker_getSupportedServiceNames() +{ + Sequence< OUString > aServiceNames { "com.sun.star.ui.dialogs.FilePicker" }; + return aServiceNames; +} + +/* + * FolderPicker implementation. + */ +static OUString FolderPicker_getSystemPickerServiceName() +{ +#ifdef UNX + OUString aDesktopEnvironment (Application::GetDesktopEnvironment()); + if (aDesktopEnvironment.equalsIgnoreAsciiCase("macosx")) + return "com.sun.star.ui.dialogs.AquaFolderPicker"; +#endif + return "com.sun.star.ui.dialogs.SystemFolderPicker"; +} + +Reference< css::uno::XInterface > FolderPicker_CreateInstance ( + Reference< css::uno::XComponentContext > const & context) +{ + Reference< css::uno::XInterface > xResult; + + if (!context.is()) + return xResult; + + Reference< css::lang::XMultiComponentFactory > xFactory (context->getServiceManager()); + if (xFactory.is() && SvtMiscOptions().UseSystemFileDialog()) + { + xResult.set( Application::createFolderPicker( context ) ); + if (!xResult.is()) + { + try + { + xResult = xFactory->createInstanceWithContext ( + FolderPicker_getSystemPickerServiceName(), + context); + } + catch (css::uno::Exception const &) + { + // Handled below (see @ fallback). + } + } + } + if (!xResult.is() && xFactory.is() ) + { + // Always fall back to OfficeFolderPicker. + xResult = xFactory->createInstanceWithContext ( + "com.sun.star.ui.dialogs.OfficeFolderPicker", + context); + } + if (xResult.is()) + { + // Add to FolderPicker history. + svt::addFolderPicker (xResult); + } + return xResult; +} + +OUString FolderPicker_getImplementationName() +{ + return "com.sun.star.comp.svt.FolderPicker"; +} + +Sequence< OUString > FolderPicker_getSupportedServiceNames() +{ + Sequence< OUString > aServiceNames { "com.sun.star.ui.dialogs.FolderPicker" }; + return aServiceNames; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/uno/fpicker.hxx b/svtools/source/uno/fpicker.hxx new file mode 100644 index 000000000..9fcbacd54 --- /dev/null +++ b/svtools/source/uno/fpicker.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 <sal/config.h> +#include <rtl/ustring.hxx> + +#include <com/sun/star/uno/Reference.hxx> +#include <com/sun/star/uno/Sequence.hxx> +#include <com/sun/star/uno/XComponentContext.hpp> + +namespace com::sun::star { + namespace lang { class XMultiServiceFactory; } + namespace uno { class XInterface; } +} + +css::uno::Reference<css::uno::XInterface> FilePicker_CreateInstance( + css::uno::Reference< css::uno::XComponentContext > const & context); +css::uno::Sequence<OUString> FilePicker_getSupportedServiceNames(); +OUString FilePicker_getImplementationName(); + +css::uno::Reference<css::uno::XInterface> FolderPicker_CreateInstance( + css::uno::Reference< css::uno::XComponentContext > const & context); +css::uno::Sequence<OUString> FolderPicker_getSupportedServiceNames(); +OUString FolderPicker_getImplementationName(); + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/uno/framestatuslistener.cxx b/svtools/source/uno/framestatuslistener.cxx new file mode 100644 index 000000000..ba158c2dd --- /dev/null +++ b/svtools/source/uno/framestatuslistener.cxx @@ -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 . + */ + +#include <svtools/framestatuslistener.hxx> +#include <com/sun/star/frame/XDispatchProvider.hpp> +#include <com/sun/star/lang/DisposedException.hpp> +#include <com/sun/star/util/URLTransformer.hpp> +#include <cppuhelper/queryinterface.hxx> +#include <vcl/svapp.hxx> + +using namespace ::cppu; +using namespace css::awt; +using namespace css::uno; +using namespace css::util; +using namespace css::beans; +using namespace css::lang; +using namespace css::frame; + +namespace svt +{ + +FrameStatusListener::FrameStatusListener( + const Reference< XComponentContext >& rxContext, + const Reference< XFrame >& xFrame ) : + OWeakObject() + , m_bDisposed( false ) + , m_xFrame( xFrame ) + , m_xContext( rxContext ) +{ +} + +FrameStatusListener::~FrameStatusListener() +{ +} + +// XInterface +Any SAL_CALL FrameStatusListener::queryInterface( const Type& rType ) +{ + Any a = ::cppu::queryInterface( + rType , + static_cast< XComponent* >( this ), + static_cast< XFrameActionListener* >( this ), + static_cast< XStatusListener* >( this ), + static_cast< XEventListener* >( static_cast< XStatusListener* >( this )), + static_cast< XEventListener* >( static_cast< XFrameActionListener* >( this ))); + + if ( a.hasValue() ) + return a; + + return OWeakObject::queryInterface( rType ); +} + +void SAL_CALL FrameStatusListener::acquire() throw () +{ + OWeakObject::acquire(); +} + +void SAL_CALL FrameStatusListener::release() throw () +{ + OWeakObject::release(); +} + +// XComponent +void SAL_CALL FrameStatusListener::dispose() +{ + Reference< XComponent > xThis = this; + + SolarMutexGuard aSolarMutexGuard; + if ( m_bDisposed ) + throw DisposedException(); + + for (auto const& listener : m_aListenerMap) + { + try + { + Reference< XDispatch > xDispatch( listener.second ); + Reference< XURLTransformer > xURLTransformer( css::util::URLTransformer::create( m_xContext ) ); + css::util::URL aTargetURL; + aTargetURL.Complete = listener.first; + xURLTransformer->parseStrict( aTargetURL ); + + if ( xDispatch.is() ) + xDispatch->removeStatusListener( this, aTargetURL ); + } + catch (const Exception&) + { + } + } + + m_bDisposed = true; +} + +void SAL_CALL FrameStatusListener::addEventListener( const Reference< XEventListener >& ) +{ + // helper class for status updates - no need to support listener +} + +void SAL_CALL FrameStatusListener::removeEventListener( const Reference< XEventListener >& ) +{ + // helper class for status updates - no need to support listener +} + +// XEventListener +void SAL_CALL FrameStatusListener::disposing( const EventObject& Source ) +{ + Reference< XInterface > xSource( Source.Source ); + + SolarMutexGuard aSolarMutexGuard; + + for (auto & listener : m_aListenerMap) + { + // Compare references and release dispatch references if they are equal. + Reference< XInterface > xIfac( listener.second, UNO_QUERY ); + if ( xSource == xIfac ) + listener.second.clear(); + } + + Reference< XInterface > xIfac( m_xFrame, UNO_QUERY ); + if ( xIfac == xSource ) + m_xFrame.clear(); +} + +void FrameStatusListener::frameAction( const FrameActionEvent& Action ) +{ + if ( Action.Action == FrameAction_CONTEXT_CHANGED ) + bindListener(); +} + +void FrameStatusListener::addStatusListener( const OUString& aCommandURL ) +{ + Reference< XDispatch > xDispatch; + Reference< XStatusListener > xStatusListener; + css::util::URL aTargetURL; + + { + SolarMutexGuard aSolarMutexGuard; + URLToDispatchMap::iterator pIter = m_aListenerMap.find( aCommandURL ); + + // Already in the list of status listener. Do nothing. + if ( pIter != m_aListenerMap.end() ) + return; + + Reference< XDispatchProvider > xDispatchProvider( m_xFrame, UNO_QUERY ); + if ( m_xContext.is() && xDispatchProvider.is() ) + { + Reference< XURLTransformer > xURLTransformer( css::util::URLTransformer::create( m_xContext ) ); + aTargetURL.Complete = aCommandURL; + xURLTransformer->parseStrict( aTargetURL ); + xDispatch = xDispatchProvider->queryDispatch( aTargetURL, OUString(), 0 ); + + xStatusListener = this; + URLToDispatchMap::iterator aIter = m_aListenerMap.find( aCommandURL ); + if ( aIter != m_aListenerMap.end() ) + { + Reference< XDispatch > xOldDispatch( aIter->second ); + aIter->second = xDispatch; + + try + { + if ( xOldDispatch.is() ) + xOldDispatch->removeStatusListener( xStatusListener, aTargetURL ); + } + catch (const Exception&) + { + } + } + else + m_aListenerMap.emplace( aCommandURL, xDispatch ); + } + } + + // Call without locked mutex as we are called back from dispatch implementation + try + { + if ( xDispatch.is() ) + xDispatch->addStatusListener( xStatusListener, aTargetURL ); + } + catch (const Exception&) + { + } +} + + +void FrameStatusListener::bindListener() +{ + std::vector< Listener > aDispatchVector; + Reference< XStatusListener > xStatusListener; + + { + SolarMutexGuard aSolarMutexGuard; + + // Collect all registered command URL's and store them temporary + Reference< XDispatchProvider > xDispatchProvider( m_xFrame, UNO_QUERY ); + if ( m_xContext.is() && xDispatchProvider.is() ) + { + xStatusListener = this; + for (auto & listener : m_aListenerMap) + { + Reference< XURLTransformer > xURLTransformer( css::util::URLTransformer::create( m_xContext ) ); + css::util::URL aTargetURL; + aTargetURL.Complete = listener.first; + xURLTransformer->parseStrict( aTargetURL ); + + Reference< XDispatch > xDispatch( listener.second ); + if ( xDispatch.is() ) + { + // We already have a dispatch object => we have to requery. + // Release old dispatch object and remove it as listener + try + { + xDispatch->removeStatusListener( xStatusListener, aTargetURL ); + } + catch (const Exception&) + { + } + } + + // Query for dispatch object. Old dispatch will be released with this, too. + try + { + xDispatch = xDispatchProvider->queryDispatch( aTargetURL, OUString(), 0 ); + } + catch (const Exception&) + { + } + listener.second = xDispatch; + + Listener aListener( aTargetURL, xDispatch ); + aDispatchVector.push_back( aListener ); + } + } + } + + // Call without locked mutex as we are called back from dispatch implementation + if ( !xStatusListener.is() ) + return; + + try + { + for (Listener & rListener : aDispatchVector) + { + if ( rListener.xDispatch.is() ) + rListener.xDispatch->addStatusListener( xStatusListener, rListener.aURL ); + } + } + catch (const Exception&) + { + } +} + +} // svt + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/uno/generictoolboxcontroller.cxx b/svtools/source/uno/generictoolboxcontroller.cxx new file mode 100644 index 000000000..570805632 --- /dev/null +++ b/svtools/source/uno/generictoolboxcontroller.cxx @@ -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 . + */ + +#include <svtools/generictoolboxcontroller.hxx> + +#include <com/sun/star/util/XURLTransformer.hpp> +#include <com/sun/star/beans/PropertyValue.hpp> +#include <com/sun/star/lang/DisposedException.hpp> +#include <com/sun/star/frame/status/ItemStatus.hpp> +#include <com/sun/star/frame/XDispatch.hpp> + +#include <vcl/svapp.hxx> +#include <vcl/weld.hxx> + +using namespace css::awt; +using namespace css::uno; +using namespace css::beans; +using namespace css::lang; +using namespace css::frame; +using namespace css::frame::status; +using namespace css::util; + +namespace svt +{ + +namespace { + +struct ExecuteInfo +{ + css::uno::Reference< css::frame::XDispatch > xDispatch; + css::util::URL aTargetURL; + css::uno::Sequence< css::beans::PropertyValue > aArgs; +}; + +} + +GenericToolboxController::GenericToolboxController( const Reference< XComponentContext >& rxContext, + const Reference< XFrame >& rFrame, + ToolBox* pToolbox, + sal_uInt16 nID, + const OUString& aCommand ) + : svt::ToolboxController( rxContext, rFrame, aCommand ) + , m_xToolbox( pToolbox ) + , m_nID( nID ) + , m_pToolbox(nullptr) +{ + // Initialization is done through ctor + m_bInitialized = true; + + // insert main command to our listener map + if ( !m_aCommandURL.isEmpty() ) + m_aListenerMap.emplace( aCommand, Reference< XDispatch >() ); +} + +GenericToolboxController::GenericToolboxController( const Reference< XComponentContext >& rxContext, + const Reference< XFrame >& rFrame, + weld::Toolbar& rToolbar, + const OUString& aCommand ) + : svt::ToolboxController( rxContext, rFrame, aCommand ) + , m_xToolbox( nullptr ) + , m_nID( 0 ) + , m_pToolbox(&rToolbar) +{ + // Initialization is done through ctor + m_bInitialized = true; + + // insert main command to our listener map + if ( !m_aCommandURL.isEmpty() ) + m_aListenerMap.emplace( aCommand, Reference< XDispatch >() ); +} + +GenericToolboxController::~GenericToolboxController() +{ +} + +void SAL_CALL GenericToolboxController::dispose() +{ + SolarMutexGuard aSolarMutexGuard; + m_xToolbox.clear(); + m_nID = 0; + m_pToolbox = nullptr; + svt::ToolboxController::dispose(); +} + +void SAL_CALL GenericToolboxController::execute( sal_Int16 /*KeyModifier*/ ) +{ + Reference< XDispatch > xDispatch; + OUString aCommandURL; + + { + SolarMutexGuard aSolarMutexGuard; + + if ( m_bDisposed ) + throw DisposedException(); + + if ( m_bInitialized && + m_xFrame.is() && + !m_aCommandURL.isEmpty() ) + { + aCommandURL = m_aCommandURL; + URLToDispatchMap::iterator pIter = m_aListenerMap.find( m_aCommandURL ); + if ( pIter != m_aListenerMap.end() ) + xDispatch = pIter->second; + } + } + + if ( !xDispatch.is() ) + return; + + css::util::URL aTargetURL; + Sequence<PropertyValue> aArgs; + + aTargetURL.Complete = aCommandURL; + if ( m_xUrlTransformer.is() ) + m_xUrlTransformer->parseStrict( aTargetURL ); + + // Execute dispatch asynchronously + ExecuteInfo* pExecuteInfo = new ExecuteInfo; + pExecuteInfo->xDispatch = xDispatch; + pExecuteInfo->aTargetURL = aTargetURL; + pExecuteInfo->aArgs = aArgs; + Application::PostUserEvent( LINK(nullptr, GenericToolboxController , ExecuteHdl_Impl), pExecuteInfo ); +} + +void GenericToolboxController::statusChanged( const FeatureStateEvent& Event ) +{ + SolarMutexGuard aSolarMutexGuard; + + if ( m_bDisposed ) + return; + + if (m_xToolbox) + { + m_xToolbox->EnableItem( m_nID, Event.IsEnabled ); + + ToolBoxItemBits nItemBits = m_xToolbox->GetItemBits( m_nID ); + nItemBits &= ~ToolBoxItemBits::CHECKABLE; + TriState eTri = TRISTATE_FALSE; + + bool bValue; + OUString aStrValue; + ItemStatus aItemState; + + if ( Event.State >>= bValue ) + { + // Boolean, treat it as checked/unchecked + m_xToolbox->SetItemBits( m_nID, nItemBits ); + m_xToolbox->CheckItem( m_nID, bValue ); + if ( bValue ) + eTri = TRISTATE_TRUE; + nItemBits |= ToolBoxItemBits::CHECKABLE; + } + else if ( Event.State >>= aStrValue ) + { + m_xToolbox->SetItemText( m_nID, aStrValue ); + } + else if ( Event.State >>= aItemState ) + { + eTri = TRISTATE_INDET; + nItemBits |= ToolBoxItemBits::CHECKABLE; + } + + m_xToolbox->SetItemState( m_nID, eTri ); + m_xToolbox->SetItemBits( m_nID, nItemBits ); + } + + if (m_pToolbox) + { + OString sId = m_aCommandURL.toUtf8(); + + m_pToolbox->set_item_sensitive(sId, Event.IsEnabled); + + bool bValue; + OUString aStrValue; + + if ( Event.State >>= bValue ) + { + // Boolean, treat it as checked/unchecked + m_pToolbox->set_item_active(sId, bValue); + } + else if ( Event.State >>= aStrValue ) + { + m_pToolbox->set_item_label(sId, aStrValue); + } + else + m_pToolbox->set_item_active(sId, false); + } +} + +IMPL_STATIC_LINK( GenericToolboxController, ExecuteHdl_Impl, void*, p, void ) +{ + ExecuteInfo* pExecuteInfo = static_cast<ExecuteInfo*>(p); + try + { + // Asynchronous execution as this can lead to our own destruction! + // Framework can recycle our current frame and the layout manager disposes all user interface + // elements if a component gets detached from its frame! + pExecuteInfo->xDispatch->dispatch( pExecuteInfo->aTargetURL, pExecuteInfo->aArgs ); + } + catch ( Exception& ) + { + } + delete pExecuteInfo; +} + +} // namespace + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/uno/genericunodialog.cxx b/svtools/source/uno/genericunodialog.cxx new file mode 100644 index 000000000..8157fd390 --- /dev/null +++ b/svtools/source/uno/genericunodialog.cxx @@ -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 . + */ + +#include <svtools/genericunodialog.hxx> + +#include <com/sun/star/awt/XWindow.hpp> +#include <com/sun/star/beans/NamedValue.hpp> +#include <com/sun/star/beans/PropertyValue.hpp> +#include <com/sun/star/beans/PropertyAttribute.hpp> +#include <com/sun/star/ucb/AlreadyInitializedException.hpp> + +#include <cppuhelper/supportsservice.hxx> +#include <cppuhelper/queryinterface.hxx> +#include <osl/diagnose.h> +#include <tools/diagnose_ex.h> +#include <osl/mutex.hxx> +#include <vcl/svapp.hxx> + +using namespace css::uno; +using namespace css::lang; +using namespace css::beans; +using namespace css::ucb; + + +namespace svt +{ + + +OGenericUnoDialog::OGenericUnoDialog(const Reference< XComponentContext >& _rxContext) + :OPropertyContainer(GetBroadcastHelper()) + ,m_bExecuting(false) + ,m_bTitleAmbiguous(true) + ,m_bInitialized( false ) + ,m_aContext(_rxContext) +{ + registerProperty(UNODIALOG_PROPERTY_TITLE, UNODIALOG_PROPERTY_ID_TITLE, PropertyAttribute::TRANSIENT, + &m_sTitle, cppu::UnoType<decltype(m_sTitle)>::get()); + registerProperty(UNODIALOG_PROPERTY_PARENT, UNODIALOG_PROPERTY_ID_PARENT, PropertyAttribute::TRANSIENT, + &m_xParent, cppu::UnoType<decltype(m_xParent)>::get()); +} + + +OGenericUnoDialog::~OGenericUnoDialog() +{ + if (m_xDialog) + { + SolarMutexGuard aSolarGuard; + ::osl::MutexGuard aGuard( m_aMutex ); + if (m_xDialog) + destroyDialog(); + } +} + + +Any SAL_CALL OGenericUnoDialog::queryInterface(const Type& _rType) +{ + Any aReturn = OGenericUnoDialogBase::queryInterface(_rType); + + if (!aReturn.hasValue()) + aReturn = ::cppu::queryInterface(_rType + ,static_cast<XPropertySet*>(this) + ,static_cast<XMultiPropertySet*>(this) + ,static_cast<XFastPropertySet*>(this) + ); + + return aReturn; +} + + +Sequence<Type> SAL_CALL OGenericUnoDialog::getTypes( ) +{ + return ::comphelper::concatSequences( + OGenericUnoDialogBase::getTypes(), + getBaseTypes() + ); +} + +sal_Bool SAL_CALL OGenericUnoDialog::supportsService(const OUString& ServiceName) +{ + return cppu::supportsService(this, ServiceName); +} + + +void OGenericUnoDialog::setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const Any& rValue ) +{ + // TODO: need some handling if we're currently executing ... + + OPropertyContainer::setFastPropertyValue_NoBroadcast(nHandle, rValue); + + if (UNODIALOG_PROPERTY_ID_TITLE == nHandle) + { + // from now on m_sTitle is valid + m_bTitleAmbiguous = false; + + if (m_xDialog) + m_xDialog->set_title(m_sTitle); + } +} + + +sal_Bool OGenericUnoDialog::convertFastPropertyValue( Any& rConvertedValue, Any& rOldValue, sal_Int32 nHandle, const Any& rValue) +{ + switch (nHandle) + { + case UNODIALOG_PROPERTY_ID_PARENT: + { + Reference<css::awt::XWindow> xNew(rValue, css::uno::UNO_QUERY); + if (xNew != m_xParent) + { + rConvertedValue <<= xNew; + rOldValue <<= m_xParent; + return true; + } + return false; + } + } + return OPropertyContainer::convertFastPropertyValue(rConvertedValue, rOldValue, nHandle, rValue); +} + + +void SAL_CALL OGenericUnoDialog::setTitle( const OUString& _rTitle ) +{ + UnoDialogEntryGuard aGuard( *this ); + + try + { + setPropertyValue(UNODIALOG_PROPERTY_TITLE, makeAny(_rTitle)); + } + catch(RuntimeException&) + { + // allowed to pass + throw; + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION("svtools.uno"); + // not allowed to pass + } +} + + +bool OGenericUnoDialog::impl_ensureDialog_lck() +{ + if (m_xDialog) + return true; + + // get the parameters for the dialog from the current settings + + // the title + OUString sTitle = m_sTitle; + + auto xDialog(createDialog(m_xParent)); + OSL_ENSURE(xDialog, "OGenericUnoDialog::impl_ensureDialog_lck: createDialog returned nonsense!"); + if (!xDialog) + return false; + + // do some initialisations + if (!m_bTitleAmbiguous) + xDialog->set_title(sTitle); + + m_xDialog = std::move(xDialog); + + return true; +} + +sal_Int16 SAL_CALL OGenericUnoDialog::execute() +{ + // both creation and execution of the dialog must be guarded with the SolarMutex, so be generous here + SolarMutexGuard aSolarGuard; + + // create the dialog, if necessary + { + UnoDialogEntryGuard aGuard( *this ); + + if (m_bExecuting) + throw RuntimeException( + "already executing the dialog (recursive call)", + *this + ); + + m_bExecuting = true; + + if ( !impl_ensureDialog_lck() ) + return 0; + } + + // start execution + sal_Int16 nReturn(0); + if (m_xDialog) + nReturn = m_xDialog->run(); + + { + ::osl::MutexGuard aGuard(m_aMutex); + + // get the settings of the dialog + executedDialog( nReturn ); + + m_bExecuting = false; + } + + // outta here + return nReturn; +} + +void OGenericUnoDialog::implInitialize(const Any& _rValue) +{ + try + { + PropertyValue aProperty; + NamedValue aValue; + if ( _rValue >>= aProperty ) + { + setPropertyValue( aProperty.Name, aProperty.Value ); + } + else if ( _rValue >>= aValue ) + { + setPropertyValue( aValue.Name, aValue.Value ); + } + } + catch(const Exception&) + { + DBG_UNHANDLED_EXCEPTION("svtools.uno"); + } +} + +void SAL_CALL OGenericUnoDialog::initialize( const Sequence< Any >& aArguments ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + if ( m_bInitialized ) + throw AlreadyInitializedException( OUString(), *this ); + + for (const Any& rArgument : aArguments) + implInitialize(rArgument); + + m_bInitialized = true; +} + +void OGenericUnoDialog::destroyDialog() +{ + SolarMutexGuard aSolarGuard; + m_xDialog.reset(); +} + +} // namespace svt + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/uno/miscservices.cxx b/svtools/source/uno/miscservices.cxx new file mode 100644 index 000000000..bf6385352 --- /dev/null +++ b/svtools/source/uno/miscservices.cxx @@ -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 . + */ + +#include <sal/types.h> + +#include <cppuhelper/factory.hxx> +#include <cppuhelper/implementationentry.hxx> +#include <com/sun/star/lang/XMultiServiceFactory.hpp> + +#include "fpicker.hxx" + +using namespace ::com::sun::star; +using namespace css::uno; +using namespace css::lang; + +namespace +{ + static const struct ::cppu::ImplementationEntry s_aServiceEntries[] = + { + { + // FilePicker should not use a constructor, it is only a + // trampoline to a real impl. + FilePicker_CreateInstance, + FilePicker_getImplementationName, + FilePicker_getSupportedServiceNames, + ::cppu::createSingleComponentFactory, nullptr, 0 + }, + { + // FolderPicker should not use a constructor, it is only a + // trampoline to a real impl. + FolderPicker_CreateInstance, + FolderPicker_getImplementationName, + FolderPicker_getSupportedServiceNames, + ::cppu::createSingleComponentFactory, nullptr, 0 + }, + { nullptr, nullptr, nullptr, nullptr, nullptr, 0 } + }; +} + +extern "C" +{ + +SAL_DLLPUBLIC_EXPORT void * svt_component_getFactory( + const char * pImplementationName, void * _pServiceManager, void * pRegistryKey) +{ + void * pResult = nullptr; + if (_pServiceManager) + { + Reference< XMultiServiceFactory > xHoldAlive(static_cast< XMultiServiceFactory * >(_pServiceManager)); + + pResult = cppu::component_getFactoryHelper(pImplementationName, + _pServiceManager, + pRegistryKey, + s_aServiceEntries); + } + return pResult; +} + +} // extern "C" + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/uno/popupmenucontrollerbase.cxx b/svtools/source/uno/popupmenucontrollerbase.cxx new file mode 100644 index 000000000..9ce0bda33 --- /dev/null +++ b/svtools/source/uno/popupmenucontrollerbase.cxx @@ -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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <svtools/popupmenucontrollerbase.hxx> + +#include <com/sun/star/beans/PropertyValue.hpp> +#include <com/sun/star/frame/XDispatchProvider.hpp> +#include <com/sun/star/frame/XFrame.hpp> +#include <com/sun/star/lang/DisposedException.hpp> +#include <com/sun/star/util/URLTransformer.hpp> + +#include <vcl/svapp.hxx> +#include <osl/mutex.hxx> +#include <cppuhelper/supportsservice.hxx> + +using namespace com::sun::star; +using namespace css::uno; +using namespace css::lang; +using namespace css::frame; +using namespace css::beans; +using namespace css::util; + +namespace svt +{ + +namespace { + +struct PopupMenuControllerBaseDispatchInfo +{ + Reference< XDispatch > mxDispatch; + const URL maURL; + const Sequence< PropertyValue > maArgs; + + PopupMenuControllerBaseDispatchInfo( const Reference< XDispatch >& xDispatch, const URL& rURL, const Sequence< PropertyValue >& rArgs ) + : mxDispatch( xDispatch ), maURL( rURL ), maArgs( rArgs ) {} +}; + +} + +PopupMenuControllerBase::PopupMenuControllerBase( const Reference< XComponentContext >& xContext ) : + ::cppu::BaseMutex(), + PopupMenuControllerBaseType(m_aMutex), + m_bInitialized( false ) +{ + if ( xContext.is() ) + m_xURLTransformer.set( util::URLTransformer::create( xContext ) ); +} + +PopupMenuControllerBase::~PopupMenuControllerBase() +{ +} + +// protected function +void PopupMenuControllerBase::throwIfDisposed() +{ + if (rBHelper.bDisposed || rBHelper.bInDispose) + throw css::lang::DisposedException(); +} + +// protected function +void PopupMenuControllerBase::resetPopupMenu( css::uno::Reference< css::awt::XPopupMenu > const & rPopupMenu ) +{ + if ( rPopupMenu.is() && rPopupMenu->getItemCount() > 0 ) + { + rPopupMenu->clear(); + } +} + +void SAL_CALL PopupMenuControllerBase::disposing() +{ + // Reset our members and set disposed flag + osl::MutexGuard aLock( m_aMutex ); + m_xFrame.clear(); + m_xDispatch.clear(); + m_xPopupMenu.clear(); +} + +// XServiceInfo +sal_Bool SAL_CALL PopupMenuControllerBase::supportsService( const OUString& ServiceName ) +{ + return cppu::supportsService(this, ServiceName); +} + +// XEventListener +void SAL_CALL PopupMenuControllerBase::disposing( const EventObject& ) +{ + osl::MutexGuard aLock( m_aMutex ); + m_xFrame.clear(); + m_xDispatch.clear(); + m_xPopupMenu.clear(); +} + +// XMenuListener +void SAL_CALL PopupMenuControllerBase::itemHighlighted( const awt::MenuEvent& ) +{ +} + +void SAL_CALL PopupMenuControllerBase::itemSelected( const awt::MenuEvent& rEvent ) +{ + throwIfDisposed(); + + osl::MutexGuard aLock( m_aMutex ); + + if( m_xPopupMenu.is() ) + { + Sequence<PropertyValue> aArgs; + dispatchCommand( m_xPopupMenu->getCommand( rEvent.MenuId ), aArgs ); + } +} + +void PopupMenuControllerBase::dispatchCommand( const OUString& sCommandURL, + const css::uno::Sequence< css::beans::PropertyValue >& rArgs, + const OUString& sTarget ) +{ + osl::MutexGuard aLock( m_aMutex ); + + throwIfDisposed(); + + try + { + Reference< XDispatchProvider > xDispatchProvider( m_xFrame, UNO_QUERY_THROW ); + URL aURL; + aURL.Complete = sCommandURL; + m_xURLTransformer->parseStrict( aURL ); + + Reference< XDispatch > xDispatch( xDispatchProvider->queryDispatch( aURL, sTarget, 0 ), UNO_SET_THROW ); + + Application::PostUserEvent( LINK(nullptr, PopupMenuControllerBase, ExecuteHdl_Impl), new PopupMenuControllerBaseDispatchInfo( xDispatch, aURL, rArgs ) ); + + } + catch( Exception& ) + { + } + +} + +IMPL_STATIC_LINK( PopupMenuControllerBase, ExecuteHdl_Impl, void*, p, void ) +{ + PopupMenuControllerBaseDispatchInfo* pDispatchInfo = static_cast<PopupMenuControllerBaseDispatchInfo*>(p); + pDispatchInfo->mxDispatch->dispatch( pDispatchInfo->maURL, pDispatchInfo->maArgs ); + delete pDispatchInfo; +} + +void SAL_CALL PopupMenuControllerBase::itemActivated( const awt::MenuEvent& ) +{ +} + +void SAL_CALL PopupMenuControllerBase::itemDeactivated( const awt::MenuEvent& ) +{ +} + +void SAL_CALL PopupMenuControllerBase::updatePopupMenu() +{ + { + osl::MutexGuard aLock(m_aMutex); + throwIfDisposed(); + } + + updateCommand( m_aCommandURL ); +} + +void PopupMenuControllerBase::updateCommand( const OUString& rCommandURL ) +{ + osl::ClearableMutexGuard aLock( m_aMutex ); + Reference< XStatusListener > xStatusListener( static_cast< OWeakObject* >( this ), UNO_QUERY ); + Reference< XDispatch > xDispatch( m_xDispatch ); + URL aTargetURL; + aTargetURL.Complete = rCommandURL; + m_xURLTransformer->parseStrict( aTargetURL ); + aLock.clear(); + + // Add/remove status listener to get a status update once + if ( xDispatch.is() ) + { + xDispatch->addStatusListener( xStatusListener, aTargetURL ); + xDispatch->removeStatusListener( xStatusListener, aTargetURL ); + } +} + + +// XDispatchProvider +Reference< XDispatch > SAL_CALL +PopupMenuControllerBase::queryDispatch( + const URL& /*aURL*/, + const OUString& /*sTarget*/, + sal_Int32 /*nFlags*/ ) +{ + // must be implemented by subclass + osl::MutexGuard aLock( m_aMutex ); + throwIfDisposed(); + + return Reference< XDispatch >(); +} + +Sequence< Reference< XDispatch > > SAL_CALL PopupMenuControllerBase::queryDispatches( const Sequence< DispatchDescriptor >& lDescriptor ) +{ + // Create return list - which must have same size then the given descriptor + // It's not allowed to pack it! + { + osl::MutexGuard aLock(m_aMutex); + throwIfDisposed(); + } + + sal_Int32 nCount = lDescriptor.getLength(); + uno::Sequence< uno::Reference< frame::XDispatch > > lDispatcher( nCount ); + + // Step over all descriptors and try to get any dispatcher for it. + std::transform(lDescriptor.begin(), lDescriptor.end(), lDispatcher.begin(), + [this](const DispatchDescriptor& rDesc) -> uno::Reference< frame::XDispatch > { + return queryDispatch(rDesc.FeatureURL, rDesc.FrameName, rDesc.SearchFlags); }); + + return lDispatcher; +} + +// XDispatch +void SAL_CALL +PopupMenuControllerBase::dispatch( + const URL& /*aURL*/, + const Sequence< PropertyValue >& /*seqProperties*/ ) +{ + // must be implemented by subclass + osl::MutexGuard aLock( m_aMutex ); + throwIfDisposed(); +} + +void SAL_CALL +PopupMenuControllerBase::addStatusListener( + const Reference< XStatusListener >& xControl, + const URL& aURL ) +{ + osl::ResettableMutexGuard aLock( m_aMutex ); + throwIfDisposed(); + aLock.clear(); + + bool bStatusUpdate( false ); + rBHelper.addListener( cppu::UnoType<decltype(xControl)>::get(), xControl ); + + aLock.reset(); + if ( aURL.Complete.startsWith( m_aBaseURL ) ) + bStatusUpdate = true; + aLock.clear(); + + if ( bStatusUpdate ) + { + // Dummy update for popup menu controllers + FeatureStateEvent aEvent; + aEvent.FeatureURL = aURL; + aEvent.IsEnabled = true; + aEvent.Requery = false; + aEvent.State = Any(); + xControl->statusChanged( aEvent ); + } +} + +void SAL_CALL PopupMenuControllerBase::removeStatusListener( + const Reference< XStatusListener >& xControl, + const URL& /*aURL*/ ) +{ + rBHelper.removeListener( cppu::UnoType<decltype(xControl)>::get(), xControl ); +} + +OUString PopupMenuControllerBase::determineBaseURL( const OUString& aURL ) +{ + // Just use the main part of the URL for popup menu controllers + sal_Int32 nQueryPart( 0 ); + sal_Int32 nSchemePart( 0 ); + OUString aMainURL( "vnd.sun.star.popup:" ); + + nSchemePart = aURL.indexOf( ':' ); + if (( nSchemePart > 0 ) && + ( aURL.getLength() > ( nSchemePart+1 ))) + { + nQueryPart = aURL.indexOf( '?', nSchemePart ); + if ( nQueryPart > 0 ) + aMainURL += aURL.copy( nSchemePart, nQueryPart-nSchemePart ); + else if ( nQueryPart == -1 ) + aMainURL += aURL.copy( nSchemePart+1 ); + } + + return aMainURL; +} + +// XInitialization +void SAL_CALL PopupMenuControllerBase::initialize( const Sequence< Any >& aArguments ) +{ + osl::MutexGuard aLock( m_aMutex ); + + bool bInitalized( m_bInitialized ); + if ( bInitalized ) + return; + + PropertyValue aPropValue; + OUString aCommandURL; + Reference< XFrame > xFrame; + + for ( const auto& rArgument : aArguments ) + { + if ( rArgument >>= aPropValue ) + { + if ( aPropValue.Name == "Frame" ) + aPropValue.Value >>= xFrame; + else if ( aPropValue.Name == "CommandURL" ) + aPropValue.Value >>= aCommandURL; + else if ( aPropValue.Name == "ModuleIdentifier" ) + aPropValue.Value >>= m_aModuleName; + } + } + + if ( xFrame.is() && !aCommandURL.isEmpty() ) + { + m_xFrame = xFrame; + m_aCommandURL = aCommandURL; + m_aBaseURL = determineBaseURL( aCommandURL ); + m_bInitialized = true; + } +} +// XPopupMenuController +void SAL_CALL PopupMenuControllerBase::setPopupMenu( const Reference< awt::XPopupMenu >& xPopupMenu ) +{ + osl::MutexGuard aLock( m_aMutex ); + throwIfDisposed(); + + if ( !(m_xFrame.is() && !m_xPopupMenu.is()) ) + return; + + // Create popup menu on demand + SolarMutexGuard aSolarMutexGuard; + + m_xPopupMenu = xPopupMenu; + m_xPopupMenu->addMenuListener( Reference< awt::XMenuListener >( static_cast<OWeakObject*>(this), UNO_QUERY )); + + Reference< XDispatchProvider > xDispatchProvider( m_xFrame, UNO_QUERY ); + + URL aTargetURL; + aTargetURL.Complete = m_aCommandURL; + m_xURLTransformer->parseStrict( aTargetURL ); + m_xDispatch = xDispatchProvider->queryDispatch( aTargetURL, OUString(), 0 ); + + impl_setPopupMenu(); + + updatePopupMenu(); +} +void PopupMenuControllerBase::impl_setPopupMenu() +{ +} +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/uno/popupwindowcontroller.cxx b/svtools/source/uno/popupwindowcontroller.cxx new file mode 100644 index 000000000..66986be60 --- /dev/null +++ b/svtools/source/uno/popupwindowcontroller.cxx @@ -0,0 +1,275 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <cppuhelper/supportsservice.hxx> +#include <toolkit/helper/vclunohelper.hxx> + +#include <vcl/svapp.hxx> +#include <vcl/toolbox.hxx> +#include <vcl/weldutils.hxx> + +#include <svtools/framestatuslistener.hxx> +#include <svtools/popupwindowcontroller.hxx> +#include <svtools/toolbarmenu.hxx> + +using namespace ::com::sun::star; +using namespace css::uno; +using namespace css::lang; + + +namespace svt +{ + +class PopupWindowControllerImpl +{ +public: + PopupWindowControllerImpl(); + ~PopupWindowControllerImpl() COVERITY_NOEXCEPT_FALSE; + + void SetPopupWindow( vcl::Window* pPopupWindow, ToolBox* pToolBox ); + void SetFloatingWindow(); + DECL_LINK( WindowEventListener, VclWindowEvent&, void ); + +private: + VclPtr<vcl::Window> mpPopupWindow, mpFloatingWindow; + VclPtr<ToolBox> mpToolBox; +}; + +PopupWindowControllerImpl::PopupWindowControllerImpl() +{ +} + +PopupWindowControllerImpl::~PopupWindowControllerImpl() COVERITY_NOEXCEPT_FALSE +{ + SetPopupWindow(nullptr,nullptr); + SetFloatingWindow(); +} + +void PopupWindowControllerImpl::SetPopupWindow( vcl::Window* pPopupWindow, ToolBox* pToolBox ) +{ + if( mpPopupWindow ) + { + mpPopupWindow->RemoveEventListener( LINK( this, PopupWindowControllerImpl, WindowEventListener ) ); + mpPopupWindow.disposeAndClear(); + } + mpPopupWindow = pPopupWindow; + mpToolBox = pToolBox; + + if( mpPopupWindow ) + { + mpPopupWindow->AddEventListener( LINK( this, PopupWindowControllerImpl, WindowEventListener )); + } +} + +void PopupWindowControllerImpl::SetFloatingWindow() +{ + if( mpFloatingWindow ) + { + mpFloatingWindow->RemoveEventListener( LINK( this, PopupWindowControllerImpl, WindowEventListener ) ); + // tdf#119390 reparent the window, so focus is restored + // to the last focused control of the application window. + mpFloatingWindow->SetParentToDefaultWindow(); + mpFloatingWindow.disposeAndClear(); + } + mpFloatingWindow = mpPopupWindow; + mpPopupWindow.clear(); +} + +IMPL_LINK( PopupWindowControllerImpl, WindowEventListener, VclWindowEvent&, rWindowEvent, void ) +{ + switch( rWindowEvent.GetId() ) + { + case VclEventId::WindowEndPopupMode: + { + EndPopupModeData* pData = static_cast< EndPopupModeData* >( rWindowEvent.GetData() ); + if( pData && pData->mbTearoff ) + { + vcl::Window::GetDockingManager()->SetFloatingMode( mpPopupWindow.get(), true ); + vcl::Window::GetDockingManager()->SetPosSizePixel( mpPopupWindow.get(), + pData->maFloatingPos.X(), + pData->maFloatingPos.Y(), + 0, 0, + PosSizeFlags::Pos ); + SetFloatingWindow(); + mpFloatingWindow->Show( true, ShowFlags::NoFocusChange | ShowFlags::NoActivate ); + } + SetPopupWindow(nullptr,nullptr); + break; + } + case VclEventId::WindowPrepareToggleFloating: + { + if ( mpFloatingWindow && rWindowEvent.GetWindow() == mpFloatingWindow.get() ) + { + bool* pData = static_cast< bool* >( rWindowEvent.GetData() ); + *pData = false; + } + break; + } + case VclEventId::WindowClose: + { + SetPopupWindow(nullptr,nullptr); + SetFloatingWindow(); + break; + } + case VclEventId::WindowShow: + { + if( mpPopupWindow ) + { + if( mpToolBox ) + mpToolBox->CallEventListeners( VclEventId::DropdownOpen, static_cast<void*>(mpPopupWindow) ); + mpPopupWindow->CallEventListeners( VclEventId::WindowGetFocus ); + break; + } + break; + } + case VclEventId::WindowHide: + { + if( mpPopupWindow ) + { + mpPopupWindow->CallEventListeners( VclEventId::WindowLoseFocus ); + if( mpToolBox ) + mpToolBox->CallEventListeners( VclEventId::DropdownClose, static_cast<void*>(mpPopupWindow) ); + } + break; + } + default: break; + } +} + + + + +PopupWindowController::PopupWindowController( const Reference< uno::XComponentContext >& rxContext, + const Reference< frame::XFrame >& xFrame, + const OUString& aCommandURL ) +: PopupWindowController_Base( rxContext, xFrame, aCommandURL ) +, mxImpl( new PopupWindowControllerImpl() ) +{ +} + +PopupWindowController::~PopupWindowController() +{ +} + +// XServiceInfo +sal_Bool SAL_CALL PopupWindowController::supportsService( const OUString& ServiceName ) +{ + return cppu::supportsService(this, ServiceName); +} + +// XComponent +void SAL_CALL PopupWindowController::dispose() +{ + mxInterimPopover.clear(); + mxPopoverContainer.reset(); + mxImpl.reset(); + svt::ToolboxController::dispose(); +} + +// XStatusListener +void SAL_CALL PopupWindowController::statusChanged( const frame::FeatureStateEvent& rEvent ) +{ + SolarMutexGuard aSolarLock; + + bool bValue = false; + rEvent.State >>= bValue; + + if (m_pToolbar) + { + OString sId = m_aCommandURL.toUtf8(); + m_pToolbar->set_item_active(sId, bValue); + m_pToolbar->set_item_sensitive(sId, rEvent.IsEnabled); + return; + } + + ToolBox* pToolBox = nullptr; + sal_uInt16 nItemId = 0; + if ( getToolboxId( nItemId, &pToolBox ) ) + { + pToolBox->CheckItem( nItemId, bValue ); + pToolBox->EnableItem( nItemId, rEvent.IsEnabled ); + } +} + +std::unique_ptr<WeldToolbarPopup> PopupWindowController::weldPopupWindow() +{ + return nullptr; +} + +Reference< awt::XWindow > SAL_CALL PopupWindowController::createPopupWindow() +{ + if (m_pToolbar) + { + mxPopoverContainer->unsetPopover(); + mxPopoverContainer->setPopover(weldPopupWindow()); + return Reference<awt::XWindow>(); + } + + VclPtr< ToolBox > pToolBox = dynamic_cast< ToolBox* >( VCLUnoHelper::GetWindow( getParent() ).get() ); + if( pToolBox ) + { + vcl::Window* pItemWindow = pToolBox->GetItemWindow( pToolBox->GetDownItemId() ); + VclPtr<vcl::Window> pWin = createVclPopupWindow( pItemWindow ? pItemWindow : pToolBox ); + if( pWin ) + { + FloatWinPopupFlags eFloatFlags = FloatWinPopupFlags::GrabFocus | + FloatWinPopupFlags::AllMouseButtonClose | + FloatWinPopupFlags::NoMouseUpClose; + + WinBits nWinBits; + if ( pWin->GetType() == WindowType::DOCKINGWINDOW ) + nWinBits = static_cast< DockingWindow* >( pWin.get() )->GetFloatStyle(); + else + nWinBits = pWin->GetStyle(); + + if ( nWinBits & ( WB_SIZEABLE | WB_CLOSEABLE ) ) + eFloatFlags |= FloatWinPopupFlags::AllowTearOff; + + pWin->EnableDocking(); + mxImpl->SetPopupWindow(pWin,pToolBox); + vcl::Window::GetDockingManager()->StartPopupMode( pToolBox, pWin, eFloatFlags ); + } + } + return Reference< awt::XWindow >(); +} + +void SAL_CALL PopupWindowController::click() +{ + if (m_pToolbar) + { + if (m_pToolbar->get_menu_item_active(m_aCommandURL.toUtf8())) + createPopupWindow(); + else + mxPopoverContainer->unsetPopover(); + } + + svt::ToolboxController::click(); +} + +void PopupWindowController::EndPopupMode() +{ + if (m_pToolbar) + m_pToolbar->set_menu_item_active(m_aCommandURL.toUtf8(), false); + else if (mxInterimPopover) + mxInterimPopover->EndPopupMode(); +} + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/uno/statusbarcontroller.cxx b/svtools/source/uno/statusbarcontroller.cxx new file mode 100644 index 000000000..57f0ddc8c --- /dev/null +++ b/svtools/source/uno/statusbarcontroller.cxx @@ -0,0 +1,594 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <svtools/statusbarcontroller.hxx> +#include <com/sun/star/beans/PropertyValue.hpp> +#include <com/sun/star/frame/XDispatchProvider.hpp> +#include <com/sun/star/frame/XFrame.hpp> +#include <com/sun/star/lang/DisposedException.hpp> +#include <com/sun/star/lang/XMultiServiceFactory.hpp> +#include <com/sun/star/util/URLTransformer.hpp> +#include <com/sun/star/ui/XStatusbarItem.hpp> +#include <cppuhelper/queryinterface.hxx> +#include <vcl/svapp.hxx> +#include <vcl/window.hxx> +#include <vcl/status.hxx> +#include <toolkit/helper/vclunohelper.hxx> +#include <comphelper/processfactory.hxx> + +using namespace ::cppu; +using namespace css::awt; +using namespace css::uno; +using namespace css::util; +using namespace css::beans; +using namespace css::lang; +using namespace css::frame; + +namespace svt +{ + +StatusbarController::StatusbarController( + const Reference< XComponentContext >& rxContext, + const Reference< XFrame >& xFrame, + const OUString& aCommandURL, + unsigned short nID ) : + OWeakObject() + , m_bInitialized( false ) + , m_bDisposed( false ) + , m_nID( nID ) + , m_xFrame( xFrame ) + , m_xContext( rxContext ) + , m_aCommandURL( aCommandURL ) + , m_aListenerContainer( m_aMutex ) +{ +} + +StatusbarController::StatusbarController() : + OWeakObject() + , m_bInitialized( false ) + , m_bDisposed( false ) + , m_nID( 0 ) + , m_aListenerContainer( m_aMutex ) +{ +} + +StatusbarController::~StatusbarController() +{ +} + +Reference< XFrame > StatusbarController::getFrameInterface() const +{ + SolarMutexGuard aSolarMutexGuard; + return m_xFrame; +} + +Reference< XURLTransformer > StatusbarController::getURLTransformer() const +{ + SolarMutexGuard aSolarMutexGuard; + if ( !m_xURLTransformer.is() && m_xContext.is() ) + { + m_xURLTransformer = css::util::URLTransformer::create( m_xContext ); + } + + return m_xURLTransformer; +} + +// XInterface +Any SAL_CALL StatusbarController::queryInterface( const Type& rType ) +{ + Any a = ::cppu::queryInterface( + rType , + static_cast< XStatusbarController* >( this ), + static_cast< XStatusListener* >( this ), + static_cast< XEventListener* >( this ), + static_cast< XInitialization* >( this ), + static_cast< XComponent* >( this ), + static_cast< XUpdatable* >( this )); + + if ( a.hasValue() ) + return a; + + return OWeakObject::queryInterface( rType ); +} + +void SAL_CALL StatusbarController::acquire() throw () +{ + OWeakObject::acquire(); +} + +void SAL_CALL StatusbarController::release() throw () +{ + OWeakObject::release(); +} + +void SAL_CALL StatusbarController::initialize( const Sequence< Any >& aArguments ) +{ + bool bInitialized( true ); + + { + SolarMutexGuard aSolarMutexGuard; + + if ( m_bDisposed ) + throw DisposedException(); + + bInitialized = m_bInitialized; + } + + if ( bInitialized ) + return; + + SolarMutexGuard aSolarMutexGuard; + m_bInitialized = true; + + PropertyValue aPropValue; + for ( const auto& rArgument : aArguments ) + { + if ( rArgument >>= aPropValue ) + { + if ( aPropValue.Name == "Frame" ) + aPropValue.Value >>= m_xFrame; + else if ( aPropValue.Name == "CommandURL" ) + aPropValue.Value >>= m_aCommandURL; + else if ( aPropValue.Name == "ServiceManager" ) + { + Reference<XMultiServiceFactory> xMSF; + aPropValue.Value >>= xMSF; + if( xMSF.is() ) + m_xContext = comphelper::getComponentContext(xMSF); + } + else if ( aPropValue.Name == "ParentWindow" ) + aPropValue.Value >>= m_xParentWindow; + else if ( aPropValue.Name == "Identifier" ) + aPropValue.Value >>= m_nID; + else if ( aPropValue.Name == "StatusbarItem" ) + aPropValue.Value >>= m_xStatusbarItem; + } + } + + if ( !m_aCommandURL.isEmpty() ) + m_aListenerMap.emplace( m_aCommandURL, Reference< XDispatch >() ); +} + +void SAL_CALL StatusbarController::update() +{ + { + SolarMutexGuard aSolarMutexGuard; + if ( m_bDisposed ) + throw DisposedException(); + } + + // Bind all registered listeners to their dispatch objects + bindListener(); +} + +// XComponent +void SAL_CALL StatusbarController::dispose() +{ + Reference< XComponent > xThis = this; + + { + SolarMutexGuard aSolarMutexGuard; + if ( m_bDisposed ) + throw DisposedException(); + } + + css::lang::EventObject aEvent( xThis ); + m_aListenerContainer.disposeAndClear( aEvent ); + + SolarMutexGuard aSolarMutexGuard; + Reference< XStatusListener > xStatusListener = this; + Reference< XURLTransformer > xURLTransformer = getURLTransformer(); + css::util::URL aTargetURL; + for (auto const& listener : m_aListenerMap) + { + try + { + Reference< XDispatch > xDispatch(listener.second); + aTargetURL.Complete = listener.first; + xURLTransformer->parseStrict( aTargetURL ); + + if ( xDispatch.is() && xStatusListener.is() ) + xDispatch->removeStatusListener( xStatusListener, aTargetURL ); + } + catch ( Exception& ) + { + } + } + + // clear hash map + m_aListenerMap.clear(); + + // release references + m_xURLTransformer.clear(); + m_xContext.clear(); + m_xFrame.clear(); + m_xParentWindow.clear(); + m_xStatusbarItem.clear(); + + m_bDisposed = true; +} + +void SAL_CALL StatusbarController::addEventListener( const Reference< XEventListener >& xListener ) +{ + m_aListenerContainer.addInterface( cppu::UnoType<XEventListener>::get(), xListener ); +} + +void SAL_CALL StatusbarController::removeEventListener( const Reference< XEventListener >& aListener ) +{ + m_aListenerContainer.removeInterface( cppu::UnoType<XEventListener>::get(), aListener ); +} + +// XEventListener +void SAL_CALL StatusbarController::disposing( const EventObject& Source ) +{ + SolarMutexGuard aSolarMutexGuard; + + if ( m_bDisposed ) + return; + + Reference< XFrame > xFrame( Source.Source, UNO_QUERY ); + if ( xFrame.is() ) + { + if ( xFrame == m_xFrame ) + m_xFrame.clear(); + return; + } + + Reference< XDispatch > xDispatch( Source.Source, UNO_QUERY ); + if ( !xDispatch.is() ) + return; + + for (auto & listener : m_aListenerMap) + { + // Compare references and release dispatch references if they are equal. + if ( xDispatch == listener.second ) + listener.second.clear(); + } +} + +// XStatusListener +void SAL_CALL StatusbarController::statusChanged( const FeatureStateEvent& Event ) +{ + SolarMutexGuard aSolarMutexGuard; + + if ( m_bDisposed ) + return; + + VclPtr<vcl::Window> pWindow = VCLUnoHelper::GetWindow( m_xParentWindow ); + if ( pWindow && pWindow->GetType() == WindowType::STATUSBAR && m_nID != 0 ) + { + OUString aStrValue; + StatusBar* pStatusBar = static_cast<StatusBar *>(pWindow.get()); + + if ( Event.State >>= aStrValue ) + pStatusBar->SetItemText( m_nID, aStrValue ); + else if ( !Event.State.hasValue() ) + pStatusBar->SetItemText( m_nID, "" ); + } +} + +// XStatusbarController +sal_Bool SAL_CALL StatusbarController::mouseButtonDown( + const css::awt::MouseEvent& ) +{ + return false; +} + +sal_Bool SAL_CALL StatusbarController::mouseMove( + const css::awt::MouseEvent& ) +{ + return false; +} + +sal_Bool SAL_CALL StatusbarController::mouseButtonUp( + const css::awt::MouseEvent& ) +{ + return false; +} + +void SAL_CALL StatusbarController::command( + const css::awt::Point&, + ::sal_Int32, + sal_Bool, + const css::uno::Any& ) +{ +} + +void SAL_CALL StatusbarController::paint( + const css::uno::Reference< css::awt::XGraphics >&, + const css::awt::Rectangle&, + ::sal_Int32 ) +{ +} + +void SAL_CALL StatusbarController::click( const css::awt::Point& ) +{ +} + +void SAL_CALL StatusbarController::doubleClick( const css::awt::Point& ) +{ + SolarMutexGuard aSolarMutexGuard; + + if ( m_bDisposed ) + return; + + Sequence< PropertyValue > aArgs; + execute( aArgs ); +} + +void StatusbarController::addStatusListener( const OUString& aCommandURL ) +{ + Reference< XDispatch > xDispatch; + Reference< XStatusListener > xStatusListener; + css::util::URL aTargetURL; + + { + SolarMutexGuard aSolarMutexGuard; + URLToDispatchMap::iterator pIter = m_aListenerMap.find( aCommandURL ); + + // Already in the list of status listener. Do nothing. + if ( pIter != m_aListenerMap.end() ) + return; + + // Check if we are already initialized. Implementation starts adding itself as status listener when + // initialize is called. + if ( !m_bInitialized ) + { + // Put into the unordered_map of status listener. Will be activated when initialized is called + m_aListenerMap.emplace( aCommandURL, Reference< XDispatch >() ); + return; + } + else + { + // Add status listener directly as initialize has already been called. + Reference< XDispatchProvider > xDispatchProvider( m_xFrame, UNO_QUERY ); + if ( m_xContext.is() && xDispatchProvider.is() ) + { + Reference< XURLTransformer > xURLTransformer = getURLTransformer(); + aTargetURL.Complete = aCommandURL; + xURLTransformer->parseStrict( aTargetURL ); + xDispatch = xDispatchProvider->queryDispatch( aTargetURL, OUString(), 0 ); + + xStatusListener = this; + URLToDispatchMap::iterator aIter = m_aListenerMap.find( aCommandURL ); + if ( aIter != m_aListenerMap.end() ) + { + Reference< XDispatch > xOldDispatch( aIter->second ); + aIter->second = xDispatch; + + try + { + if ( xOldDispatch.is() ) + xOldDispatch->removeStatusListener( xStatusListener, aTargetURL ); + } + catch ( Exception& ) + { + } + } + else + m_aListenerMap.emplace( aCommandURL, xDispatch ); + } + } + } + + // Call without locked mutex as we are called back from dispatch implementation + try + { + if ( xDispatch.is() ) + xDispatch->addStatusListener( xStatusListener, aTargetURL ); + } + catch ( Exception& ) + { + } +} + +void StatusbarController::bindListener() +{ + std::vector< Listener > aDispatchVector; + Reference< XStatusListener > xStatusListener; + + { + SolarMutexGuard aSolarMutexGuard; + + if ( !m_bInitialized ) + return; + + // Collect all registered command URL's and store them temporary + Reference< XDispatchProvider > xDispatchProvider( m_xFrame, UNO_QUERY ); + if ( m_xContext.is() && xDispatchProvider.is() ) + { + xStatusListener = this; + for (auto & listener : m_aListenerMap) + { + Reference< XURLTransformer > xURLTransformer = getURLTransformer(); + css::util::URL aTargetURL; + aTargetURL.Complete = listener.first; + xURLTransformer->parseStrict( aTargetURL ); + + Reference< XDispatch > xDispatch(listener.second); + if ( xDispatch.is() ) + { + // We already have a dispatch object => we have to requery. + // Release old dispatch object and remove it as listener + try + { + xDispatch->removeStatusListener( xStatusListener, aTargetURL ); + } + catch ( Exception& ) + { + } + } + + listener.second.clear(); + xDispatch.clear(); + + // Query for dispatch object. Old dispatch will be released with this, too. + try + { + xDispatch = xDispatchProvider->queryDispatch( aTargetURL, OUString(), 0 ); + } + catch ( Exception& ) + { + } + listener.second = xDispatch; + + Listener aListener( aTargetURL, xDispatch ); + aDispatchVector.push_back( aListener ); + } + } + } + + // Call without locked mutex as we are called back from dispatch implementation + if ( !xStatusListener.is() ) + return; + + for (Listener & rListener : aDispatchVector) + { + try + { + if ( rListener.xDispatch.is() ) + rListener.xDispatch->addStatusListener( xStatusListener, rListener.aURL ); + else if ( rListener.aURL.Complete == m_aCommandURL ) + { + // Send status changed for the main URL, if we cannot get a valid dispatch object. + // UI disables the button. Catch exception as we release our mutex, it is possible + // that someone else already disposed this instance! + FeatureStateEvent aFeatureStateEvent; + aFeatureStateEvent.IsEnabled = false; + aFeatureStateEvent.FeatureURL = rListener.aURL; + aFeatureStateEvent.State = Any(); + xStatusListener->statusChanged( aFeatureStateEvent ); + } + } + catch ( ... ){} + } +} + +::tools::Rectangle StatusbarController::getControlRect() const +{ + ::tools::Rectangle aRect; + + { + SolarMutexGuard aSolarMutexGuard; + + if ( m_bDisposed ) + throw DisposedException(); + + if ( m_xParentWindow.is() ) + { + VclPtr< StatusBar > pStatusBar = dynamic_cast< StatusBar* >( VCLUnoHelper::GetWindow( m_xParentWindow ).get() ); + if ( pStatusBar && pStatusBar->GetType() == WindowType::STATUSBAR ) + aRect = pStatusBar->GetItemRect( m_nID ); + } + } + + return aRect; +} + +void StatusbarController::execute( const css::uno::Sequence< css::beans::PropertyValue >& aArgs ) +{ + Reference< XDispatch > xDispatch; + Reference< XURLTransformer > xURLTransformer; + OUString aCommandURL; + + { + SolarMutexGuard aSolarMutexGuard; + + if ( m_bDisposed ) + throw DisposedException(); + + if ( m_bInitialized && + m_xFrame.is() && + m_xContext.is() && + !m_aCommandURL.isEmpty() ) + { + xURLTransformer = getURLTransformer(); + aCommandURL = m_aCommandURL; + URLToDispatchMap::iterator pIter = m_aListenerMap.find( m_aCommandURL ); + if ( pIter != m_aListenerMap.end() ) + xDispatch = pIter->second; + } + } + + if ( !(xDispatch.is() && xURLTransformer.is()) ) + return; + + try + { + css::util::URL aTargetURL; + + aTargetURL.Complete = aCommandURL; + xURLTransformer->parseStrict( aTargetURL ); + xDispatch->dispatch( aTargetURL, aArgs ); + } + catch ( DisposedException& ) + { + } +} + +void StatusbarController::execute( + const OUString& aCommandURL, + const Sequence< css::beans::PropertyValue >& aArgs ) +{ + Reference< XDispatch > xDispatch; + css::util::URL aTargetURL; + + { + SolarMutexGuard aSolarMutexGuard; + + if ( m_bDisposed ) + throw DisposedException(); + + if ( m_bInitialized && + m_xFrame.is() && + m_xContext.is() && + !m_aCommandURL.isEmpty() ) + { + Reference< XURLTransformer > xURLTransformer( getURLTransformer() ); + aTargetURL.Complete = aCommandURL; + xURLTransformer->parseStrict( aTargetURL ); + + URLToDispatchMap::iterator pIter = m_aListenerMap.find( aCommandURL ); + if ( pIter != m_aListenerMap.end() ) + xDispatch = pIter->second; + else + { + Reference< css::frame::XDispatchProvider > xDispatchProvider( + m_xFrame->getController(), UNO_QUERY ); + if ( xDispatchProvider.is() ) + xDispatch = xDispatchProvider->queryDispatch( aTargetURL, OUString(), 0 ); + } + } + } + + if ( xDispatch.is() ) + { + try + { + xDispatch->dispatch( aTargetURL, aArgs ); + } + catch ( DisposedException& ) + { + } + } +} + +} // svt + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/uno/svtxgridcontrol.cxx b/svtools/source/uno/svtxgridcontrol.cxx new file mode 100644 index 000000000..91fd08ac1 --- /dev/null +++ b/svtools/source/uno/svtxgridcontrol.cxx @@ -0,0 +1,908 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 "svtxgridcontrol.hxx" +#include <com/sun/star/view/SelectionType.hpp> +#include <table/tablecontrolinterface.hxx> +#include <table/gridtablerenderer.hxx> +#include <table/tablecontrol.hxx> +#include "unocontroltablemodel.hxx" +#include <sal/log.hxx> +#include <tools/diagnose_ex.h> +#include <toolkit/helper/property.hxx> +#include <com/sun/star/awt/grid/XGridColumn.hpp> +#include <com/sun/star/awt/grid/GridInvalidDataException.hpp> +#include <com/sun/star/awt/grid/GridInvalidModelException.hpp> +#include <com/sun/star/accessibility/AccessibleEventId.hpp> +#include <com/sun/star/accessibility/AccessibleStateType.hpp> +#include <com/sun/star/util/Color.hpp> +#include <com/sun/star/lang/IndexOutOfBoundsException.hpp> + +#include <vcl/svapp.hxx> + +using css::uno::Reference; +using css::uno::Exception; +using css::uno::UNO_QUERY; +using css::uno::UNO_QUERY_THROW; +using css::uno::Any; +using css::uno::makeAny; +using css::uno::Sequence; +using css::awt::grid::XGridSelectionListener; +using css::style::VerticalAlignment; +using css::style::VerticalAlignment_TOP; +using css::view::SelectionType; +using css::view::SelectionType_NONE; +using css::view::SelectionType_RANGE; +using css::view::SelectionType_SINGLE; +using css::view::SelectionType_MULTI; +using css::awt::grid::XGridDataModel; +using css::awt::grid::GridInvalidDataException; +using css::lang::EventObject; +using css::lang::IndexOutOfBoundsException; +using css::awt::grid::XGridColumnModel; +using css::awt::grid::GridSelectionEvent; +using css::awt::grid::XGridColumn; +using css::container::ContainerEvent; +using css::awt::grid::GridDataEvent; +using css::awt::grid::GridInvalidModelException; + +namespace AccessibleEventId = css::accessibility::AccessibleEventId; +namespace AccessibleStateType = css::accessibility::AccessibleStateType; + +using namespace ::svt::table; + + +SVTXGridControl::SVTXGridControl() + :m_xTableModel( std::make_shared<UnoControlTableModel>() ) + ,m_bTableModelInitCompleted( false ) + ,m_aSelectionListeners( *this ) +{ +} + + +SVTXGridControl::~SVTXGridControl() +{ +} + + +void SVTXGridControl::SetWindow( const VclPtr< vcl::Window > &pWindow ) +{ + SVTXGridControl_Base::SetWindow( pWindow ); + impl_checkTableModelInit(); +} + + +void SVTXGridControl::impl_checkColumnIndex_throw( ::svt::table::TableControl const & i_table, sal_Int32 const i_columnIndex ) const +{ + if ( ( i_columnIndex < 0 ) || ( i_columnIndex >= i_table.GetColumnCount() ) ) + throw IndexOutOfBoundsException( OUString(), *const_cast< SVTXGridControl* >( this ) ); +} + + +void SVTXGridControl::impl_checkRowIndex_throw( ::svt::table::TableControl const & i_table, sal_Int32 const i_rowIndex ) const +{ + if ( ( i_rowIndex < 0 ) || ( i_rowIndex >= i_table.GetRowCount() ) ) + throw IndexOutOfBoundsException( OUString(), *const_cast< SVTXGridControl* >( this ) ); +} + + +sal_Int32 SAL_CALL SVTXGridControl::getRowAtPoint(::sal_Int32 x, ::sal_Int32 y) +{ + SolarMutexGuard aGuard; + + VclPtr< TableControl > pTable = GetAsDynamic< TableControl >(); + ENSURE_OR_RETURN( pTable, "SVTXGridControl::getRowAtPoint: no control (anymore)!", -1 ); + + TableCell const tableCell = pTable->getTableControlInterface().hitTest( Point( x, y ) ); + return ( tableCell.nRow >= 0 ) ? tableCell.nRow : -1; +} + + +sal_Int32 SAL_CALL SVTXGridControl::getColumnAtPoint(::sal_Int32 x, ::sal_Int32 y) +{ + SolarMutexGuard aGuard; + + VclPtr< TableControl > pTable = GetAsDynamic< TableControl >(); + ENSURE_OR_RETURN( pTable, "SVTXGridControl::getColumnAtPoint: no control (anymore)!", -1 ); + + TableCell const tableCell = pTable->getTableControlInterface().hitTest( Point( x, y ) ); + return ( tableCell.nColumn >= 0 ) ? tableCell.nColumn : -1; +} + + +sal_Int32 SAL_CALL SVTXGridControl::getCurrentColumn( ) +{ + SolarMutexGuard aGuard; + + VclPtr< TableControl > pTable = GetAsDynamic< TableControl >(); + ENSURE_OR_RETURN( pTable, "SVTXGridControl::getCurrentColumn: no control (anymore)!", -1 ); + + sal_Int32 const nColumn = pTable->GetCurrentColumn(); + return ( nColumn >= 0 ) ? nColumn : -1; +} + + +sal_Int32 SAL_CALL SVTXGridControl::getCurrentRow( ) +{ + SolarMutexGuard aGuard; + + VclPtr< TableControl > pTable = GetAsDynamic< TableControl >(); + ENSURE_OR_RETURN( pTable, "SVTXGridControl::getCurrentRow: no control (anymore)!", -1 ); + + sal_Int32 const nRow = pTable->GetCurrentRow(); + return ( nRow >= 0 ) ? nRow : -1; +} + + +void SAL_CALL SVTXGridControl::goToCell( ::sal_Int32 i_columnIndex, ::sal_Int32 i_rowIndex ) +{ + SolarMutexGuard aGuard; + + VclPtr< TableControl > pTable = GetAsDynamic< TableControl >(); + ENSURE_OR_RETURN_VOID( pTable, "SVTXGridControl::getCurrentRow: no control (anymore)!" ); + + impl_checkColumnIndex_throw( *pTable, i_columnIndex ); + impl_checkRowIndex_throw( *pTable, i_rowIndex ); + + pTable->GoTo( i_columnIndex, i_rowIndex ); +} + + +void SAL_CALL SVTXGridControl::addSelectionListener(const Reference< XGridSelectionListener > & listener) +{ + m_aSelectionListeners.addInterface(listener); +} + + +void SAL_CALL SVTXGridControl::removeSelectionListener(const Reference< XGridSelectionListener > & listener) +{ + m_aSelectionListeners.removeInterface(listener); +} + + +void SVTXGridControl::setProperty( const OUString& PropertyName, const Any& aValue) +{ + SolarMutexGuard aGuard; + + VclPtr< TableControl > pTable = GetAsDynamic< TableControl >(); + ENSURE_OR_RETURN_VOID( pTable, "SVTXGridControl::setProperty: no control (anymore)!" ); + + switch( GetPropertyId( PropertyName ) ) + { + case BASEPROPERTY_ROW_HEADER_WIDTH: + { + sal_Int32 rowHeaderWidth( -1 ); + aValue >>= rowHeaderWidth; + if ( rowHeaderWidth <= 0 ) + { + SAL_WARN( "svtools.uno", "SVTXGridControl::setProperty: illegal row header width!" ); + break; + } + + m_xTableModel->setRowHeaderWidth( rowHeaderWidth ); + // TODO: the model should broadcast this change itself, and the table should invalidate itself as needed + pTable->Invalidate(); + } + break; + + case BASEPROPERTY_COLUMN_HEADER_HEIGHT: + { + sal_Int32 columnHeaderHeight = 0; + if ( !aValue.hasValue() ) + { + columnHeaderHeight = pTable->PixelToLogic(Size(0, pTable->GetTextHeight() + 3), MapMode(MapUnit::MapAppFont)).Height(); + } + else + { + aValue >>= columnHeaderHeight; + } + if ( columnHeaderHeight <= 0 ) + { + SAL_WARN( "svtools.uno", "SVTXGridControl::setProperty: illegal column header width!" ); + break; + } + + m_xTableModel->setColumnHeaderHeight( columnHeaderHeight ); + // TODO: the model should broadcast this change itself, and the table should invalidate itself as needed + pTable->Invalidate(); + } + break; + + case BASEPROPERTY_USE_GRID_LINES: + { + GridTableRenderer* pGridRenderer = dynamic_cast< GridTableRenderer* >( + m_xTableModel->getRenderer().get() ); + if ( !pGridRenderer ) + { + SAL_WARN( "svtools.uno", "SVTXGridControl::setProperty(UseGridLines): invalid renderer!" ); + break; + } + + bool bUseGridLines = false; + OSL_VERIFY( aValue >>= bUseGridLines ); + pGridRenderer->useGridLines( bUseGridLines ); + pTable->Invalidate(); + } + break; + + case BASEPROPERTY_ROW_HEIGHT: + { + sal_Int32 rowHeight = 0; + if ( !aValue.hasValue() ) + { + rowHeight = pTable->PixelToLogic(Size(0, pTable->GetTextHeight() + 3), MapMode(MapUnit::MapAppFont)).Height(); + } + else + { + aValue >>= rowHeight; + } + m_xTableModel->setRowHeight( rowHeight ); + if ( rowHeight <= 0 ) + { + SAL_WARN( "svtools.uno", "SVTXGridControl::setProperty: illegal row height!" ); + break; + } + + // TODO: the model should broadcast this change itself, and the table should invalidate itself as needed + pTable->Invalidate(); + } + break; + + case BASEPROPERTY_BACKGROUNDCOLOR: + { + // let the base class handle this for the TableControl + VCLXWindow::setProperty( PropertyName, aValue ); + // and forward to the grid control's data window + if ( pTable->IsBackground() ) + pTable->getDataWindow().SetBackground( pTable->GetBackground() ); + else + pTable->getDataWindow().SetBackground(); + } + break; + + case BASEPROPERTY_GRID_SELECTIONMODE: + { + SelectionType eSelectionType; + if( aValue >>= eSelectionType ) + { + SelectionMode eSelMode; + switch( eSelectionType ) + { + case SelectionType_SINGLE: eSelMode = SelectionMode::Single; break; + case SelectionType_RANGE: eSelMode = SelectionMode::Range; break; + case SelectionType_MULTI: eSelMode = SelectionMode::Multiple; break; + default: eSelMode = SelectionMode::NONE; break; + } + if( pTable->getSelEngine()->GetSelectionMode() != eSelMode ) + pTable->getSelEngine()->SetSelectionMode( eSelMode ); + } + break; + } + case BASEPROPERTY_HSCROLL: + { + bool bHScroll = true; + if( aValue >>= bHScroll ) + m_xTableModel->setHorizontalScrollbarVisibility( bHScroll ? ScrollbarShowAlways : ScrollbarShowSmart ); + break; + } + + case BASEPROPERTY_VSCROLL: + { + bool bVScroll = true; + if( aValue >>= bVScroll ) + { + m_xTableModel->setVerticalScrollbarVisibility( bVScroll ? ScrollbarShowAlways : ScrollbarShowSmart ); + } + break; + } + + case BASEPROPERTY_GRID_SHOWROWHEADER: + { + bool rowHeader = true; + if( aValue >>= rowHeader ) + { + m_xTableModel->setRowHeaders(rowHeader); + } + break; + } + + case BASEPROPERTY_GRID_ROW_BACKGROUND_COLORS: + m_xTableModel->setRowBackgroundColors( aValue ); + pTable->Invalidate(); + break; + + case BASEPROPERTY_GRID_LINE_COLOR: + m_xTableModel->setLineColor( aValue ); + pTable->Invalidate(); + break; + + case BASEPROPERTY_GRID_HEADER_BACKGROUND: + m_xTableModel->setHeaderBackgroundColor( aValue ); + pTable->Invalidate(); + break; + + case BASEPROPERTY_GRID_HEADER_TEXT_COLOR: + m_xTableModel->setHeaderTextColor( aValue ); + pTable->Invalidate(); + break; + + case BASEPROPERTY_ACTIVE_SEL_BACKGROUND_COLOR: + m_xTableModel->setActiveSelectionBackColor( aValue ); + pTable->Invalidate(); + break; + + case BASEPROPERTY_INACTIVE_SEL_BACKGROUND_COLOR: + m_xTableModel->setInactiveSelectionBackColor( aValue ); + pTable->Invalidate(); + break; + + case BASEPROPERTY_ACTIVE_SEL_TEXT_COLOR: + m_xTableModel->setActiveSelectionTextColor( aValue ); + pTable->Invalidate(); + break; + + case BASEPROPERTY_INACTIVE_SEL_TEXT_COLOR: + m_xTableModel->setInactiveSelectionTextColor( aValue ); + pTable->Invalidate(); + break; + + + case BASEPROPERTY_TEXTCOLOR: + m_xTableModel->setTextColor( aValue ); + pTable->Invalidate(); + break; + + case BASEPROPERTY_TEXTLINECOLOR: + m_xTableModel->setTextLineColor( aValue ); + pTable->Invalidate(); + break; + + case BASEPROPERTY_VERTICALALIGN: + { + VerticalAlignment eAlign( VerticalAlignment_TOP ); + if ( aValue >>= eAlign ) + m_xTableModel->setVerticalAlign( eAlign ); + break; + } + + case BASEPROPERTY_GRID_SHOWCOLUMNHEADER: + { + bool colHeader = true; + if( aValue >>= colHeader ) + { + m_xTableModel->setColumnHeaders(colHeader); + } + break; + } + case BASEPROPERTY_GRID_DATAMODEL: + { + Reference< XGridDataModel > const xDataModel( aValue, UNO_QUERY ); + if ( !xDataModel.is() ) + throw GridInvalidDataException("Invalid data model.", *this ); + + m_xTableModel->setDataModel( xDataModel ); + impl_checkTableModelInit(); + } + break; + + case BASEPROPERTY_GRID_COLUMNMODEL: + { + // obtain new col model + Reference< XGridColumnModel > const xColumnModel( aValue, UNO_QUERY ); + if ( !xColumnModel.is() ) + throw GridInvalidModelException("Invalid column model.", *this ); + + // remove all old columns + m_xTableModel->removeAllColumns(); + + // announce to the TableModel + m_xTableModel->setColumnModel( xColumnModel ); + impl_checkTableModelInit(); + + // add new columns + impl_updateColumnsFromModel_nothrow(); + break; + } + default: + VCLXWindow::setProperty( PropertyName, aValue ); + break; + } +} + + +void SVTXGridControl::impl_checkTableModelInit() +{ + if ( !(!m_bTableModelInitCompleted && m_xTableModel->hasColumnModel() && m_xTableModel->hasDataModel()) ) + return; + + VclPtr< TableControl > pTable = GetAsDynamic< TableControl >(); + if ( !pTable ) + return; + + pTable->SetModel( PTableModel( m_xTableModel ) ); + + m_bTableModelInitCompleted = true; + + // ensure default columns exist, if they have not previously been added + Reference< XGridDataModel > const xDataModel( m_xTableModel->getDataModel(), css::uno::UNO_SET_THROW ); + Reference< XGridColumnModel > const xColumnModel( m_xTableModel->getColumnModel(), css::uno::UNO_SET_THROW ); + + sal_Int32 const nDataColumnCount = xDataModel->getColumnCount(); + if ( ( nDataColumnCount > 0 ) && ( xColumnModel->getColumnCount() == 0 ) ) + xColumnModel->setDefaultColumns( nDataColumnCount ); + // this will trigger notifications, which in turn will let us update our m_xTableModel +} + +namespace +{ + void lcl_convertColor( ::std::optional< ::Color > const & i_color, Any & o_colorValue ) + { + if ( !i_color ) + o_colorValue.clear(); + else + o_colorValue <<= sal_Int32(*i_color); + } +} + +Any SVTXGridControl::getProperty( const OUString& PropertyName ) +{ + SolarMutexGuard aGuard; + + VclPtr< TableControl > pTable = GetAsDynamic< TableControl >(); + ENSURE_OR_RETURN( pTable, "SVTXGridControl::getProperty: no control (anymore)!", Any() ); + + Any aPropertyValue; + + const sal_uInt16 nPropId = GetPropertyId( PropertyName ); + switch(nPropId) + { + case BASEPROPERTY_GRID_SELECTIONMODE: + { + SelectionType eSelectionType; + + SelectionMode eSelMode = pTable->getSelEngine()->GetSelectionMode(); + switch( eSelMode ) + { + case SelectionMode::Single: eSelectionType = SelectionType_SINGLE; break; + case SelectionMode::Range: eSelectionType = SelectionType_RANGE; break; + case SelectionMode::Multiple:eSelectionType = SelectionType_MULTI; break; + default: eSelectionType = SelectionType_NONE; break; + } + aPropertyValue <<= eSelectionType; + break; + } + + case BASEPROPERTY_GRID_SHOWROWHEADER: + aPropertyValue <<= m_xTableModel->hasRowHeaders(); + break; + + case BASEPROPERTY_GRID_SHOWCOLUMNHEADER: + aPropertyValue <<= m_xTableModel->hasColumnHeaders(); + break; + + case BASEPROPERTY_GRID_DATAMODEL: + aPropertyValue <<= m_xTableModel->getDataModel(); + break; + + case BASEPROPERTY_GRID_COLUMNMODEL: + aPropertyValue <<= m_xTableModel->getColumnModel(); + break; + + case BASEPROPERTY_HSCROLL: + { + bool const bHasScrollbar = ( m_xTableModel->getHorizontalScrollbarVisibility() != ScrollbarShowNever ); + aPropertyValue <<= bHasScrollbar; + break; + } + + case BASEPROPERTY_VSCROLL: + { + bool const bHasScrollbar = ( m_xTableModel->getVerticalScrollbarVisibility() != ScrollbarShowNever ); + aPropertyValue <<= bHasScrollbar; + break; + } + + case BASEPROPERTY_USE_GRID_LINES: + { + GridTableRenderer* pGridRenderer = dynamic_cast< GridTableRenderer* >( + m_xTableModel->getRenderer().get() ); + if ( !pGridRenderer ) + { + SAL_WARN( "svtools.uno", "SVTXGridControl::getProperty(UseGridLines): invalid renderer!" ); + break; + } + + aPropertyValue <<= pGridRenderer->useGridLines(); + } + break; + + case BASEPROPERTY_GRID_ROW_BACKGROUND_COLORS: + { + ::std::optional< ::std::vector< ::Color > > aColors( m_xTableModel->getRowBackgroundColors() ); + if ( !aColors ) + aPropertyValue.clear(); + else + { + Sequence< css::util::Color > aAPIColors( aColors->size() ); + for ( size_t i=0; i<aColors->size(); ++i ) + { + aAPIColors[i] = sal_Int32(aColors->at(i)); + } + aPropertyValue <<= aAPIColors; + } + } + break; + + case BASEPROPERTY_GRID_LINE_COLOR: + lcl_convertColor( m_xTableModel->getLineColor(), aPropertyValue ); + break; + + case BASEPROPERTY_GRID_HEADER_BACKGROUND: + lcl_convertColor( m_xTableModel->getHeaderBackgroundColor(), aPropertyValue ); + break; + + case BASEPROPERTY_GRID_HEADER_TEXT_COLOR: + lcl_convertColor( m_xTableModel->getHeaderTextColor(), aPropertyValue ); + break; + + case BASEPROPERTY_ACTIVE_SEL_BACKGROUND_COLOR: + lcl_convertColor( m_xTableModel->getActiveSelectionBackColor(), aPropertyValue ); + break; + + case BASEPROPERTY_INACTIVE_SEL_BACKGROUND_COLOR: + lcl_convertColor( m_xTableModel->getInactiveSelectionBackColor(), aPropertyValue ); + break; + + case BASEPROPERTY_ACTIVE_SEL_TEXT_COLOR: + lcl_convertColor( m_xTableModel->getActiveSelectionTextColor(), aPropertyValue ); + break; + + case BASEPROPERTY_INACTIVE_SEL_TEXT_COLOR: + lcl_convertColor( m_xTableModel->getInactiveSelectionTextColor(), aPropertyValue ); + break; + + case BASEPROPERTY_TEXTCOLOR: + lcl_convertColor( m_xTableModel->getTextColor(), aPropertyValue ); + break; + + case BASEPROPERTY_TEXTLINECOLOR: + lcl_convertColor( m_xTableModel->getTextLineColor(), aPropertyValue ); + break; + + default: + aPropertyValue = VCLXWindow::getProperty( PropertyName ); + break; + } + + return aPropertyValue; +} + + +void SAL_CALL SVTXGridControl::rowsInserted( const GridDataEvent& i_event ) +{ + SolarMutexGuard aGuard; + m_xTableModel->notifyRowsInserted( i_event ); +} + + +void SAL_CALL + SVTXGridControl::rowsRemoved( const GridDataEvent& i_event ) +{ + SolarMutexGuard aGuard; + m_xTableModel->notifyRowsRemoved( i_event ); +} + + +void SAL_CALL SVTXGridControl::dataChanged( const GridDataEvent& i_event ) +{ + SolarMutexGuard aGuard; + + m_xTableModel->notifyDataChanged( i_event ); + + // if the data model is sortable, a dataChanged event is also fired in case the sort order changed. + // So, just in case, invalidate the column header area, too. + VclPtr< TableControl > pTable = GetAsDynamic< TableControl >(); + ENSURE_OR_RETURN_VOID( pTable, "SVTXGridControl::dataChanged: no control (anymore)!" ); + pTable->getTableControlInterface().invalidate( TableArea::ColumnHeaders ); +} + + +void SAL_CALL SVTXGridControl::rowHeadingChanged( const GridDataEvent& ) +{ + SolarMutexGuard aGuard; + + VclPtr< TableControl > pTable = GetAsDynamic< TableControl >(); + ENSURE_OR_RETURN_VOID( pTable, "SVTXGridControl::rowHeadingChanged: no control (anymore)!" ); + + // TODO: we could do better than this - invalidate the header area only + pTable->getTableControlInterface().invalidate( TableArea::RowHeaders ); +} + + +void SAL_CALL SVTXGridControl::elementInserted( const ContainerEvent& i_event ) +{ + SolarMutexGuard aGuard; + + Reference< XGridColumn > const xGridColumn( i_event.Element, UNO_QUERY_THROW ); + + sal_Int32 nIndex( m_xTableModel->getColumnCount() ); + OSL_VERIFY( i_event.Accessor >>= nIndex ); + m_xTableModel->insertColumn( nIndex, xGridColumn ); +} + + +void SAL_CALL SVTXGridControl::elementRemoved( const ContainerEvent& i_event ) +{ + SolarMutexGuard aGuard; + + sal_Int32 nIndex( -1 ); + OSL_VERIFY( i_event.Accessor >>= nIndex ); + m_xTableModel->removeColumn( nIndex ); +} + + +void SAL_CALL SVTXGridControl::elementReplaced( const ContainerEvent& ) +{ + OSL_ENSURE( false, "SVTXGridControl::elementReplaced: not implemented!" ); + // at the moment, the XGridColumnModel API does not allow replacing columns + // TODO: replace the respective column in our table model +} + + +void SAL_CALL SVTXGridControl::disposing( const EventObject& Source ) +{ + VCLXWindow::disposing( Source ); +} + + +void SAL_CALL SVTXGridControl::selectRow( ::sal_Int32 i_rowIndex ) +{ + SolarMutexGuard aGuard; + + VclPtr< TableControl > pTable = GetAsDynamic< TableControl >(); + ENSURE_OR_RETURN_VOID( pTable, "SVTXGridControl::selectRow: no control (anymore)!" ); + + impl_checkRowIndex_throw( *pTable, i_rowIndex ); + + pTable->SelectRow( i_rowIndex, true ); +} + + +void SAL_CALL SVTXGridControl::selectAllRows() +{ + SolarMutexGuard aGuard; + + VclPtr< TableControl > pTable = GetAsDynamic< TableControl >(); + ENSURE_OR_RETURN_VOID( pTable, "SVTXGridControl::selectAllRows: no control (anymore)!" ); + + pTable->SelectAllRows( true ); +} + + +void SAL_CALL SVTXGridControl::deselectRow( ::sal_Int32 i_rowIndex ) +{ + SolarMutexGuard aGuard; + + VclPtr< TableControl > pTable = GetAsDynamic< TableControl >(); + ENSURE_OR_RETURN_VOID( pTable, "SVTXGridControl::deselectRow: no control (anymore)!" ); + + impl_checkRowIndex_throw( *pTable, i_rowIndex ); + + pTable->SelectRow( i_rowIndex, false ); +} + + +void SAL_CALL SVTXGridControl::deselectAllRows() +{ + SolarMutexGuard aGuard; + + VclPtr< TableControl > pTable = GetAsDynamic< TableControl >(); + ENSURE_OR_RETURN_VOID( pTable, "SVTXGridControl::deselectAllRows: no control (anymore)!" ); + + pTable->SelectAllRows( false ); +} + + +Sequence< ::sal_Int32 > SAL_CALL SVTXGridControl::getSelectedRows() +{ + SolarMutexGuard aGuard; + + VclPtr< TableControl > pTable = GetAsDynamic< TableControl >(); + ENSURE_OR_RETURN( pTable, "SVTXGridControl::getSelectedRows: no control (anymore)!", Sequence< sal_Int32 >() ); + + sal_Int32 selectionCount = pTable->GetSelectedRowCount(); + Sequence< sal_Int32 > selectedRows( selectionCount ); + for ( sal_Int32 i=0; i<selectionCount; ++i ) + selectedRows[i] = pTable->GetSelectedRowIndex(i); + return selectedRows; +} + + +sal_Bool SAL_CALL SVTXGridControl::hasSelectedRows() +{ + SolarMutexGuard aGuard; + + VclPtr< TableControl > pTable = GetAsDynamic< TableControl >(); + ENSURE_OR_RETURN( pTable, "SVTXGridControl::hasSelectedRows: no control (anymore)!", true ); + + return pTable->GetSelectedRowCount() > 0; +} + + +sal_Bool SAL_CALL SVTXGridControl::isRowSelected( ::sal_Int32 index ) +{ + SolarMutexGuard aGuard; + + VclPtr< TableControl > pTable = GetAsDynamic< TableControl >(); + ENSURE_OR_RETURN( pTable, "SVTXGridControl::isRowSelected: no control (anymore)!", false ); + + return pTable->IsRowSelected( index ); +} + + +void SVTXGridControl::dispose() +{ + EventObject aObj; + aObj.Source = static_cast<cppu::OWeakObject*>(this); + m_aSelectionListeners.disposeAndClear( aObj ); + VCLXWindow::dispose(); +} + + +void SVTXGridControl::ProcessWindowEvent( const VclWindowEvent& rVclWindowEvent ) +{ + SolarMutexGuard aGuard; + + Reference< XWindow > xKeepAlive( this ); + + VclPtr< TableControl > pTable = GetAsDynamic< TableControl >(); + ENSURE_OR_RETURN_VOID( pTable, "SVTXGridControl::ProcessWindowEvent: no control (anymore)!" ); + + bool handled = false; + switch ( rVclWindowEvent.GetId() ) + { + case VclEventId::TableRowSelect: + { + if ( m_aSelectionListeners.getLength() ) + ImplCallItemListeners(); + handled = true; + } + break; + + case VclEventId::ControlGetFocus: + { + // TODO: this doesn't belong here. It belongs into the TableControl/_Impl, so A11Y also + // works when the control is used outside the UNO context + if ( pTable->GetRowCount()>0 ) + { + pTable->commitCellEventIfAccessibleAlive( + AccessibleEventId::STATE_CHANGED, + makeAny( AccessibleStateType::FOCUSED ), + Any() + ); + pTable->commitTableEventIfAccessibleAlive( + AccessibleEventId::ACTIVE_DESCENDANT_CHANGED, + Any(), + Any() + ); + } + else + { + pTable->commitTableEventIfAccessibleAlive( + AccessibleEventId::STATE_CHANGED, + makeAny( AccessibleStateType::FOCUSED ), + Any() + ); + } + } + break; + + case VclEventId::ControlLoseFocus: + { + // TODO: this doesn't belong here. It belongs into the TableControl/_Impl, so A11Y also + // works when the control is used outside the UNO context + if ( pTable->GetRowCount()>0 ) + { + pTable->commitCellEventIfAccessibleAlive( + AccessibleEventId::STATE_CHANGED, + Any(), + makeAny( AccessibleStateType::FOCUSED ) + ); + } + else + { + pTable->commitTableEventIfAccessibleAlive( + AccessibleEventId::STATE_CHANGED, + Any(), + makeAny( AccessibleStateType::FOCUSED ) + ); + } + } + break; + + default: break; + } + + if ( !handled ) + VCLXWindow::ProcessWindowEvent( rVclWindowEvent ); +} + + +void SVTXGridControl::setEnable( sal_Bool bEnable ) +{ + SolarMutexGuard aGuard; + + m_xTableModel->setEnabled( bEnable ); + VclPtr<vcl::Window> pWindow = GetWindow(); + if ( pWindow ) + { + pWindow->Enable( bEnable ); + pWindow->EnableInput( bEnable ); + pWindow->Invalidate(); + } +} + + +void SVTXGridControl::ImplCallItemListeners() +{ + VclPtr< TableControl > pTable = GetAsDynamic< TableControl >(); + ENSURE_OR_RETURN_VOID( pTable, "SVTXGridControl::ImplCallItemListeners: no control (anymore)!" ); + + if ( m_aSelectionListeners.getLength() ) + { + GridSelectionEvent aEvent; + aEvent.Source = static_cast<cppu::OWeakObject*>(this); + + sal_Int32 const nSelectedRowCount( pTable->GetSelectedRowCount() ); + aEvent.SelectedRowIndexes.realloc( nSelectedRowCount ); + for ( sal_Int32 i=0; i<nSelectedRowCount; ++i ) + aEvent.SelectedRowIndexes[i] = pTable->GetSelectedRowIndex( i ); + m_aSelectionListeners.selectionChanged( aEvent ); + } +} + + +void SVTXGridControl::impl_updateColumnsFromModel_nothrow() +{ + Reference< XGridColumnModel > const xColumnModel( m_xTableModel->getColumnModel() ); + ENSURE_OR_RETURN_VOID( xColumnModel.is(), "no model!" ); + VclPtr< TableControl > pTable = GetAsDynamic< TableControl >(); + ENSURE_OR_RETURN_VOID( pTable, "no table!" ); + + try + { + const Sequence< Reference< XGridColumn > > columns = xColumnModel->getColumns(); + for ( auto const & colRef : columns ) + { + if ( !colRef.is() ) + { + SAL_WARN( "svtools.uno", "illegal column!" ); + continue; + } + + m_xTableModel->appendColumn( colRef ); + } + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION("svtools.uno"); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/uno/svtxgridcontrol.hxx b/svtools/source/uno/svtxgridcontrol.hxx new file mode 100644 index 000000000..9e4fd85fe --- /dev/null +++ b/svtools/source/uno/svtxgridcontrol.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 + +#include "unocontroltablemodel.hxx" +#include <table/tablecontrol.hxx> +#include <com/sun/star/awt/grid/XGridControl.hpp> +#include <com/sun/star/awt/grid/XGridRowSelection.hpp> +#include <com/sun/star/awt/grid/XGridDataListener.hpp> +#include <com/sun/star/awt/grid/GridDataEvent.hpp> +#include <com/sun/star/awt/grid/XGridSelectionListener.hpp> +#include <com/sun/star/container/XContainerListener.hpp> +#include <toolkit/awt/vclxwindow.hxx> +#include <cppuhelper/implbase.hxx> +#include <toolkit/helper/listenermultiplexer.hxx> + + +namespace svt::table { + class TableControl; +} + +typedef ::cppu::ImplInheritanceHelper < VCLXWindow + , css::awt::grid::XGridControl + , css::awt::grid::XGridRowSelection + , css::awt::grid::XGridDataListener + , css::container::XContainerListener + > SVTXGridControl_Base; +class SVTXGridControl final : public SVTXGridControl_Base +{ +public: + SVTXGridControl(); + virtual ~SVTXGridControl() override; + + // XGridDataListener + virtual void SAL_CALL rowsInserted( const css::awt::grid::GridDataEvent& Event ) override; + virtual void SAL_CALL rowsRemoved( const css::awt::grid::GridDataEvent& Event ) override; + virtual void SAL_CALL dataChanged( const css::awt::grid::GridDataEvent& Event ) override; + virtual void SAL_CALL rowHeadingChanged( const css::awt::grid::GridDataEvent& Event ) 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; + + // XEventListener + virtual void SAL_CALL disposing( const css::lang::EventObject& Source ) override; + + // XGridControl + virtual ::sal_Int32 SAL_CALL getRowAtPoint(::sal_Int32 x, ::sal_Int32 y) override; + virtual ::sal_Int32 SAL_CALL getColumnAtPoint(::sal_Int32 x, ::sal_Int32 y) override; + virtual ::sal_Int32 SAL_CALL getCurrentColumn( ) override; + virtual ::sal_Int32 SAL_CALL getCurrentRow( ) override; + virtual void SAL_CALL goToCell( ::sal_Int32 i_columnIndex, ::sal_Int32 i_rowIndex ) override; + + // XGridRowSelection + virtual void SAL_CALL selectRow( ::sal_Int32 i_rowIndex ) override; + virtual void SAL_CALL selectAllRows() override; + virtual void SAL_CALL deselectRow( ::sal_Int32 i_rowIndex ) override; + virtual void SAL_CALL deselectAllRows() override; + virtual css::uno::Sequence< ::sal_Int32 > SAL_CALL getSelectedRows() override; + virtual sal_Bool SAL_CALL hasSelectedRows() override; + virtual sal_Bool SAL_CALL isRowSelected(::sal_Int32 index) override; + virtual void SAL_CALL addSelectionListener(const css::uno::Reference< css::awt::grid::XGridSelectionListener > & listener) override; + virtual void SAL_CALL removeSelectionListener(const css::uno::Reference< css::awt::grid::XGridSelectionListener > & listener) override; + + void SAL_CALL setProperty( const OUString& PropertyName, const css::uno::Any& Value ) override; + css::uno::Any SAL_CALL getProperty( const OUString& PropertyName ) override; + + // css::lang::XComponent + void SAL_CALL dispose( ) override; + + // XWindow + void SAL_CALL setEnable( sal_Bool bEnable ) override; + +private: + // VCLXWindow + virtual void SetWindow( const VclPtr< vcl::Window > &pWindow ) override; + + void impl_updateColumnsFromModel_nothrow(); + void impl_checkTableModelInit(); + + void impl_checkColumnIndex_throw( ::svt::table::TableControl const & i_table, sal_Int32 const i_columnIndex ) const; + void impl_checkRowIndex_throw( ::svt::table::TableControl const & i_table, sal_Int32 const i_rowIndex ) const; + + virtual void ProcessWindowEvent( const VclWindowEvent& rVclWindowEvent ) override; + void ImplCallItemListeners(); + + std::shared_ptr< ::svt::table::UnoControlTableModel > m_xTableModel; + bool m_bTableModelInitCompleted; + SelectionListenerMultiplexer m_aSelectionListeners; +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/uno/toolboxcontroller.cxx b/svtools/source/uno/toolboxcontroller.cxx new file mode 100644 index 000000000..b8c9ba9b4 --- /dev/null +++ b/svtools/source/uno/toolboxcontroller.cxx @@ -0,0 +1,774 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <svtools/toolboxcontroller.hxx> +#include <com/sun/star/beans/PropertyAttribute.hpp> +#include <com/sun/star/beans/PropertyValue.hpp> +#include <com/sun/star/beans/XPropertySet.hpp> +#include <com/sun/star/frame/XDispatchProvider.hpp> +#include <com/sun/star/lang/DisposedException.hpp> +#include <com/sun/star/lang/XMultiServiceFactory.hpp> +#include <com/sun/star/frame/XLayoutManager.hpp> +#include <com/sun/star/util/URLTransformer.hpp> +#include <vcl/svapp.hxx> +#include <toolkit/helper/vclunohelper.hxx> +#include <vcl/toolbox.hxx> +#include <vcl/weldutils.hxx> +#include <comphelper/processfactory.hxx> + +const int TOOLBARCONTROLLER_PROPHANDLE_SUPPORTSVISIBLE = 1; +const char TOOLBARCONTROLLER_PROPNAME_SUPPORTSVISIBLE[] = "SupportsVisible"; + + +using namespace ::cppu; +using namespace css::awt; +using namespace css::uno; +using namespace css::util; +using namespace css::beans; +using namespace css::lang; +using namespace css::frame; + +namespace svt +{ + +ToolboxController::ToolboxController( + const Reference< XComponentContext >& rxContext, + const Reference< XFrame >& xFrame, + const OUString& aCommandURL ) : + OPropertyContainer( GetBroadcastHelper() ) + , m_bSupportVisible( false ) + , m_bInitialized( false ) + , m_bDisposed( false ) + , m_bSidebar( false ) + , m_nToolBoxId( SAL_MAX_UINT16 ) + , m_xFrame( xFrame ) + , m_xContext( rxContext ) + , m_aCommandURL( aCommandURL ) + , m_aListenerContainer( m_aMutex ) + , m_pToolbar(nullptr) + , m_pBuilder(nullptr) +{ + OSL_ASSERT( m_xContext.is() ); + registerProperty( TOOLBARCONTROLLER_PROPNAME_SUPPORTSVISIBLE, + TOOLBARCONTROLLER_PROPHANDLE_SUPPORTSVISIBLE, + css::beans::PropertyAttribute::TRANSIENT | css::beans::PropertyAttribute::READONLY, + &m_bSupportVisible, cppu::UnoType<decltype(m_bSupportVisible)>::get()); + + try + { + m_xUrlTransformer = URLTransformer::create( rxContext ); + } + catch(const Exception&) + { + } +} + +ToolboxController::ToolboxController() : + OPropertyContainer(GetBroadcastHelper()) + , m_bSupportVisible(false) + , m_bInitialized( false ) + , m_bDisposed( false ) + , m_bSidebar( false ) + , m_nToolBoxId( SAL_MAX_UINT16 ) + , m_aListenerContainer( m_aMutex ) + , m_pToolbar(nullptr) + , m_pBuilder(nullptr) +{ + registerProperty( TOOLBARCONTROLLER_PROPNAME_SUPPORTSVISIBLE, + TOOLBARCONTROLLER_PROPHANDLE_SUPPORTSVISIBLE, + css::beans::PropertyAttribute::TRANSIENT | css::beans::PropertyAttribute::READONLY, + &m_bSupportVisible, cppu::UnoType<decltype(m_bSupportVisible)>::get()); +} + +ToolboxController::~ToolboxController() +{ +} + +Reference< XFrame > ToolboxController::getFrameInterface() const +{ + SolarMutexGuard aSolarMutexGuard; + return m_xFrame; +} + +const Reference< XComponentContext > & ToolboxController::getContext() const +{ + SolarMutexGuard aSolarMutexGuard; + return m_xContext; +} + +Reference< XLayoutManager > ToolboxController::getLayoutManager() const +{ + Reference< XLayoutManager > xLayoutManager; + Reference< XPropertySet > xPropSet; + { + SolarMutexGuard aSolarMutexGuard; + xPropSet.set( m_xFrame, UNO_QUERY ); + } + + if ( xPropSet.is() ) + { + try + { + xLayoutManager.set(xPropSet->getPropertyValue("LayoutManager"),UNO_QUERY); + } + catch ( Exception& ) + { + } + } + + return xLayoutManager; +} + +// XInterface +Any SAL_CALL ToolboxController::queryInterface( const Type& rType ) +{ + css::uno::Any a(ToolboxController_Base::queryInterface(rType)); + return a.hasValue() ? a : OPropertyContainer::queryInterface(rType); +} + +void SAL_CALL ToolboxController::acquire() throw () +{ + ToolboxController_Base::acquire(); +} + +void SAL_CALL ToolboxController::release() throw () +{ + ToolboxController_Base::release(); +} + +css::uno::Sequence<css::uno::Type> ToolboxController::getTypes() +{ + return comphelper::concatSequences(ToolboxController_Base::getTypes(), + getBaseTypes()); +} + +void SAL_CALL ToolboxController::initialize( const Sequence< Any >& aArguments ) +{ + bool bInitialized( true ); + + { + SolarMutexGuard aSolarMutexGuard; + + if ( m_bDisposed ) + throw DisposedException(); + + bInitialized = m_bInitialized; + } + + if ( bInitialized ) + return; + + SolarMutexGuard aSolarMutexGuard; + m_bInitialized = true; + m_bSupportVisible = false; + PropertyValue aPropValue; + for ( const auto& rArgument : aArguments ) + { + if ( rArgument >>= aPropValue ) + { + if ( aPropValue.Name == "Frame" ) + m_xFrame.set(aPropValue.Value,UNO_QUERY); + else if ( aPropValue.Name == "CommandURL" ) + aPropValue.Value >>= m_aCommandURL; + else if ( aPropValue.Name == "ServiceManager" ) + { + Reference<XMultiServiceFactory> xMSF(aPropValue.Value, UNO_QUERY); + if (xMSF.is()) + m_xContext = comphelper::getComponentContext(xMSF); + } + else if ( aPropValue.Name == "ParentWindow" ) + m_xParentWindow.set(aPropValue.Value,UNO_QUERY); + else if ( aPropValue.Name == "ModuleIdentifier" ) + aPropValue.Value >>= m_sModuleName; + else if ( aPropValue.Name == "Identifier" ) + aPropValue.Value >>= m_nToolBoxId; + else if ( aPropValue.Name == "IsSidebar" ) + aPropValue.Value >>= m_bSidebar; + } + } + + try + { + if ( !m_xUrlTransformer.is() && m_xContext.is() ) + m_xUrlTransformer = URLTransformer::create( m_xContext ); + } + catch(const Exception&) + { + } + + if ( !m_aCommandURL.isEmpty() ) + m_aListenerMap.emplace( m_aCommandURL, Reference< XDispatch >() ); + + if (weld::TransportAsXWindow* pTunnel = dynamic_cast<weld::TransportAsXWindow*>(getParent().get())) + { + m_pToolbar = dynamic_cast<weld::Toolbar*>(pTunnel->getWidget()); + assert(m_pToolbar && "must be a toolbar"); + m_pBuilder = pTunnel->getBuilder(); + } +} + +void SAL_CALL ToolboxController::update() +{ + { + SolarMutexGuard aSolarMutexGuard; + if ( m_bDisposed ) + throw DisposedException(); + } + + // Bind all registered listeners to their dispatch objects + bindListener(); +} + +// XComponent +void SAL_CALL ToolboxController::dispose() +{ + Reference< XComponent > xThis( static_cast< OWeakObject* >(this), UNO_QUERY ); + + { + SolarMutexGuard aSolarMutexGuard; + if ( m_bDisposed ) + throw DisposedException(); + } + + css::lang::EventObject aEvent( xThis ); + m_aListenerContainer.disposeAndClear( aEvent ); + + SolarMutexGuard aSolarMutexGuard; + Reference< XStatusListener > xStatusListener( static_cast< OWeakObject* >( this ), UNO_QUERY ); + for (auto const& listener : m_aListenerMap) + { + try + { + Reference< XDispatch > xDispatch( listener.second ); + + css::util::URL aTargetURL; + aTargetURL.Complete = listener.first; + if ( m_xUrlTransformer.is() ) + m_xUrlTransformer->parseStrict( aTargetURL ); + + if ( xDispatch.is() && xStatusListener.is() ) + xDispatch->removeStatusListener( xStatusListener, aTargetURL ); + } + catch ( Exception& ) + { + } + + } + + m_bDisposed = true; +} + +void SAL_CALL ToolboxController::addEventListener( const Reference< XEventListener >& xListener ) +{ + m_aListenerContainer.addInterface( cppu::UnoType<XEventListener>::get(), xListener ); +} + +void SAL_CALL ToolboxController::removeEventListener( const Reference< XEventListener >& aListener ) +{ + m_aListenerContainer.removeInterface( cppu::UnoType<XEventListener>::get(), aListener ); +} + +// XEventListener +void SAL_CALL ToolboxController::disposing( const EventObject& Source ) +{ + Reference< XInterface > xSource( Source.Source ); + + SolarMutexGuard aSolarMutexGuard; + + if ( m_bDisposed ) + return; + + for (auto & listener : m_aListenerMap) + { + // Compare references and release dispatch references if they are equal. + Reference< XInterface > xIfac(listener.second, UNO_QUERY); + if ( xSource == xIfac ) + listener.second.clear(); + } + + Reference< XInterface > xIfac( m_xFrame, UNO_QUERY ); + if ( xIfac == xSource ) + m_xFrame.clear(); +} + +// XStatusListener +void SAL_CALL ToolboxController::statusChanged( const FeatureStateEvent& ) +{ + // must be implemented by sub class +} + +// XToolbarController +void SAL_CALL ToolboxController::execute( sal_Int16 KeyModifier ) +{ + Reference< XDispatch > xDispatch; + OUString aCommandURL; + + { + SolarMutexGuard aSolarMutexGuard; + + if ( m_bDisposed ) + throw DisposedException(); + + if ( m_bInitialized && + m_xFrame.is() && + !m_aCommandURL.isEmpty() ) + { + aCommandURL = m_aCommandURL; + URLToDispatchMap::iterator pIter = m_aListenerMap.find( m_aCommandURL ); + if ( pIter != m_aListenerMap.end() ) + xDispatch = pIter->second; + } + } + + if ( !xDispatch.is() ) + return; + + try + { + css::util::URL aTargetURL; + Sequence<PropertyValue> aArgs( 1 ); + + // Provide key modifier information to dispatch function + aArgs[0].Name = "KeyModifier"; + aArgs[0].Value <<= KeyModifier; + + aTargetURL.Complete = aCommandURL; + if ( m_xUrlTransformer.is() ) + m_xUrlTransformer->parseStrict( aTargetURL ); + xDispatch->dispatch( aTargetURL, aArgs ); + } + catch ( DisposedException& ) + { + } +} + +void SAL_CALL ToolboxController::click() +{ +} + +void SAL_CALL ToolboxController::doubleClick() +{ +} + +Reference< XWindow > SAL_CALL ToolboxController::createPopupWindow() +{ + return Reference< XWindow >(); +} + +Reference< XWindow > SAL_CALL ToolboxController::createItemWindow( const Reference< XWindow >& ) +{ + return Reference< XWindow >(); +} + +void ToolboxController::addStatusListener( const OUString& aCommandURL ) +{ + Reference< XDispatch > xDispatch; + Reference< XStatusListener > xStatusListener; + css::util::URL aTargetURL; + + { + SolarMutexGuard aSolarMutexGuard; + URLToDispatchMap::iterator pIter = m_aListenerMap.find( aCommandURL ); + + // Already in the list of status listener. Do nothing. + if ( pIter != m_aListenerMap.end() ) + return; + + // Check if we are already initialized. Implementation starts adding itself as status listener when + // initialize is called. + if ( !m_bInitialized ) + { + // Put into the unordered_map of status listener. Will be activated when initialized is called + m_aListenerMap.emplace( aCommandURL, Reference< XDispatch >() ); + return; + } + else + { + // Add status listener directly as initialize has already been called. + Reference< XDispatchProvider > xDispatchProvider( m_xFrame, UNO_QUERY ); + if ( m_xContext.is() && xDispatchProvider.is() ) + { + aTargetURL.Complete = aCommandURL; + if ( m_xUrlTransformer.is() ) + m_xUrlTransformer->parseStrict( aTargetURL ); + xDispatch = xDispatchProvider->queryDispatch( aTargetURL, OUString(), 0 ); + + xStatusListener.set( static_cast< OWeakObject* >( this ), UNO_QUERY ); + URLToDispatchMap::iterator aIter = m_aListenerMap.find( aCommandURL ); + if ( aIter != m_aListenerMap.end() ) + { + Reference< XDispatch > xOldDispatch( aIter->second ); + aIter->second = xDispatch; + + try + { + if ( xOldDispatch.is() ) + xOldDispatch->removeStatusListener( xStatusListener, aTargetURL ); + } + catch ( Exception& ) + { + } + } + else + m_aListenerMap.emplace( aCommandURL, xDispatch ); + } + } + } + + // Call without locked mutex as we are called back from dispatch implementation + try + { + if ( xDispatch.is() ) + xDispatch->addStatusListener( xStatusListener, aTargetURL ); + } + catch ( Exception& ) + { + } +} + +void ToolboxController::removeStatusListener( const OUString& aCommandURL ) +{ + SolarMutexGuard aSolarMutexGuard; + + URLToDispatchMap::iterator pIter = m_aListenerMap.find( aCommandURL ); + if ( pIter == m_aListenerMap.end() ) + return; + + Reference< XDispatch > xDispatch( pIter->second ); + Reference< XStatusListener > xStatusListener( static_cast< OWeakObject* >( this ), UNO_QUERY ); + m_aListenerMap.erase( pIter ); + + try + { + css::util::URL aTargetURL; + aTargetURL.Complete = aCommandURL; + if ( m_xUrlTransformer.is() ) + m_xUrlTransformer->parseStrict( aTargetURL ); + + if ( xDispatch.is() && xStatusListener.is() ) + xDispatch->removeStatusListener( xStatusListener, aTargetURL ); + } + catch ( Exception& ) + { + } +} + +void ToolboxController::bindListener() +{ + std::vector< Listener > aDispatchVector; + Reference< XStatusListener > xStatusListener; + + { + SolarMutexGuard aSolarMutexGuard; + + if ( !m_bInitialized ) + return; + + // Collect all registered command URL's and store them temporary + Reference< XDispatchProvider > xDispatchProvider( m_xFrame, UNO_QUERY ); + if ( m_xContext.is() && xDispatchProvider.is() ) + { + xStatusListener.set( static_cast< OWeakObject* >( this ), UNO_QUERY ); + for (auto & listener : m_aListenerMap) + { + css::util::URL aTargetURL; + aTargetURL.Complete = listener.first; + if ( m_xUrlTransformer.is() ) + m_xUrlTransformer->parseStrict( aTargetURL ); + + Reference< XDispatch > xDispatch(listener.second); + if ( xDispatch.is() ) + { + // We already have a dispatch object => we have to requery. + // Release old dispatch object and remove it as listener + try + { + xDispatch->removeStatusListener( xStatusListener, aTargetURL ); + } + catch ( Exception& ) + { + } + } + + listener.second.clear(); + xDispatch.clear(); + + // Query for dispatch object. Old dispatch will be released with this, too. + try + { + xDispatch = xDispatchProvider->queryDispatch( aTargetURL, OUString(), 0 ); + } + catch ( Exception& ) + { + } + listener.second = xDispatch; + + Listener aListener( aTargetURL, xDispatch ); + aDispatchVector.push_back( aListener ); + } + } + } + + // Call without locked mutex as we are called back from dispatch implementation + if ( !xStatusListener.is() ) + return; + + try + { + for (Listener & rListener : aDispatchVector) + { + if ( rListener.xDispatch.is() ) + rListener.xDispatch->addStatusListener( xStatusListener, rListener.aURL ); + else if ( rListener.aURL.Complete == m_aCommandURL ) + { + try + { + // Send status changed for the main URL, if we cannot get a valid dispatch object. + // UI disables the button. Catch exception as we release our mutex, it is possible + // that someone else already disposed this instance! + FeatureStateEvent aFeatureStateEvent; + aFeatureStateEvent.IsEnabled = false; + aFeatureStateEvent.FeatureURL = rListener.aURL; + aFeatureStateEvent.State = Any(); + xStatusListener->statusChanged( aFeatureStateEvent ); + } + catch ( Exception& ) + { + } + } + } + } + catch ( Exception& ) + { + } +} + +void ToolboxController::unbindListener() +{ + SolarMutexGuard aSolarMutexGuard; + + if ( !m_bInitialized ) + return; + + // Collect all registered command URL's and store them temporary + Reference< XDispatchProvider > xDispatchProvider( m_xFrame, UNO_QUERY ); + if ( !(m_xContext.is() && xDispatchProvider.is()) ) + return; + + Reference< XStatusListener > xStatusListener( static_cast< OWeakObject* >( this ), UNO_QUERY ); + for (auto & listener : m_aListenerMap) + { + css::util::URL aTargetURL; + aTargetURL.Complete = listener.first; + if ( m_xUrlTransformer.is() ) + m_xUrlTransformer->parseStrict( aTargetURL ); + + Reference< XDispatch > xDispatch(listener.second); + if ( xDispatch.is() ) + { + // We already have a dispatch object => we have to requery. + // Release old dispatch object and remove it as listener + try + { + xDispatch->removeStatusListener( xStatusListener, aTargetURL ); + } + catch ( Exception& ) + { + } + } + listener.second.clear(); + } +} + +void ToolboxController::updateStatus() +{ + bindListener(); +} + +void ToolboxController::updateStatus( const OUString& aCommandURL ) +{ + Reference< XDispatch > xDispatch; + Reference< XStatusListener > xStatusListener; + css::util::URL aTargetURL; + + { + SolarMutexGuard aSolarMutexGuard; + + if ( !m_bInitialized ) + return; + + // Try to find a dispatch object for the requested command URL + Reference< XDispatchProvider > xDispatchProvider( m_xFrame, UNO_QUERY ); + xStatusListener.set( static_cast< OWeakObject* >( this ), UNO_QUERY ); + if ( m_xContext.is() && xDispatchProvider.is() ) + { + aTargetURL.Complete = aCommandURL; + if ( m_xUrlTransformer.is() ) + m_xUrlTransformer->parseStrict( aTargetURL ); + xDispatch = xDispatchProvider->queryDispatch( aTargetURL, OUString(), 0 ); + } + } + + if ( !(xDispatch.is() && xStatusListener.is()) ) + return; + + // Catch exception as we release our mutex, it is possible that someone else + // has already disposed this instance! + // Add/remove status listener to get an update status information from the + // requested command. + try + { + xDispatch->addStatusListener( xStatusListener, aTargetURL ); + xDispatch->removeStatusListener( xStatusListener, aTargetURL ); + } + catch ( Exception& ) + { + } +} + + +void ToolboxController::dispatchCommand( const OUString& sCommandURL, const Sequence< PropertyValue >& rArgs, const OUString &sTarget ) +{ + try + { + Reference< XDispatchProvider > xDispatchProvider( m_xFrame, UNO_QUERY_THROW ); + URL aURL; + aURL.Complete = sCommandURL; + getURLTransformer()->parseStrict( aURL ); + + Reference< XDispatch > xDispatch( xDispatchProvider->queryDispatch( aURL, sTarget, 0 ), UNO_SET_THROW ); + + std::unique_ptr<DispatchInfo> pDispatchInfo(new DispatchInfo( xDispatch, aURL, rArgs )); + if ( Application::PostUserEvent( LINK(nullptr, ToolboxController, ExecuteHdl_Impl), + pDispatchInfo.get() ) ) + pDispatchInfo.release(); + + } + catch( Exception& ) + { + } +} + + +css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL ToolboxController::getPropertySetInfo() +{ + Reference<XPropertySetInfo> xInfo( createPropertySetInfo( getInfoHelper() ) ); + return xInfo; +} + +::cppu::IPropertyArrayHelper& ToolboxController::getInfoHelper() +{ + return *getArrayHelper(); +} + + +::cppu::IPropertyArrayHelper* ToolboxController::createArrayHelper( ) const +{ + css::uno::Sequence< Property > aProps; + describeProperties(aProps); + return new ::cppu::OPropertyArrayHelper(aProps); +} + +sal_Bool SAL_CALL ToolboxController::convertFastPropertyValue( css::uno::Any& aConvertedValue , + css::uno::Any& aOldValue , + sal_Int32 nHandle , + const css::uno::Any& aValue ) +{ + switch (nHandle) + { + case TOOLBARCONTROLLER_PROPHANDLE_SUPPORTSVISIBLE: + { + bool aNewValue(false); + aValue >>= aNewValue; + if (aNewValue != m_bSupportVisible) + { + aConvertedValue <<= aNewValue; + aOldValue <<= m_bSupportVisible; + return true; + } + return false; + } + } + return OPropertyContainer::convertFastPropertyValue(aConvertedValue, aOldValue, nHandle, aValue); +} + +void SAL_CALL ToolboxController::setFastPropertyValue_NoBroadcast( + sal_Int32 nHandle, + const css::uno::Any& aValue ) +{ + OPropertyContainer::setFastPropertyValue_NoBroadcast(nHandle, aValue); + if (TOOLBARCONTROLLER_PROPHANDLE_SUPPORTSVISIBLE == nHandle) + { + bool rValue(false); + if (( aValue >>= rValue ) && m_bInitialized) + m_bSupportVisible = rValue; + } +} + + +IMPL_STATIC_LINK( ToolboxController, ExecuteHdl_Impl, void*, p, void ) +{ + DispatchInfo* pDispatchInfo = static_cast<DispatchInfo*>(p); + pDispatchInfo->mxDispatch->dispatch( pDispatchInfo->maURL, pDispatchInfo->maArgs ); + delete pDispatchInfo; +} + +void ToolboxController::enable( bool bEnable ) +{ + ToolBox* pToolBox = nullptr; + sal_uInt16 nItemId = 0; + if( getToolboxId( nItemId, &pToolBox ) ) + { + pToolBox->EnableItem( nItemId, bEnable ); + } +} + +bool ToolboxController::getToolboxId( sal_uInt16& rItemId, ToolBox** ppToolBox ) +{ + if( (m_nToolBoxId != SAL_MAX_UINT16) && (ppToolBox == nullptr) ) + return m_nToolBoxId; + + ToolBox* pToolBox = static_cast< ToolBox* >( VCLUnoHelper::GetWindow( getParent() ).get() ); + + if( (m_nToolBoxId == SAL_MAX_UINT16) && pToolBox ) + { + const ToolBox::ImplToolItems::size_type nCount = pToolBox->GetItemCount(); + for ( ToolBox::ImplToolItems::size_type nPos = 0; nPos < nCount; ++nPos ) + { + const sal_uInt16 nItemId = pToolBox->GetItemId( nPos ); + if ( pToolBox->GetItemCommand( nItemId ) == m_aCommandURL ) + { + m_nToolBoxId = nItemId; + break; + } + } + } + + if( ppToolBox ) + *ppToolBox = pToolBox; + + rItemId = m_nToolBoxId; + + return (rItemId != SAL_MAX_UINT16) && (( ppToolBox == nullptr) || (*ppToolBox != nullptr) ); +} +//end + +} // svt + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/uno/unocontroltablemodel.cxx b/svtools/source/uno/unocontroltablemodel.cxx new file mode 100644 index 000000000..e1adde725 --- /dev/null +++ b/svtools/source/uno/unocontroltablemodel.cxx @@ -0,0 +1,877 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 "unocontroltablemodel.hxx" +#include "unogridcolumnfacade.hxx" + +#include <table/defaultinputhandler.hxx> +#include <table/gridtablerenderer.hxx> + +#include <com/sun/star/awt/grid/XGridColumn.hpp> +#include <com/sun/star/awt/grid/XSortableGridData.hpp> +#include <com/sun/star/util/Color.hpp> +#include <o3tl/safeint.hxx> +#include <sal/log.hxx> +#include <cppuhelper/weakref.hxx> +#include <tools/debug.hxx> +#include <tools/diagnose_ex.h> + + +namespace svt::table +{ + + + using css::uno::Reference; + using css::uno::Sequence; + using css::uno::UNO_QUERY_THROW; + using css::uno::UNO_QUERY; + using css::awt::grid::XGridColumn; + using css::uno::Exception; + using css::awt::grid::XGridDataModel; + using css::awt::grid::XGridColumnModel; + using css::uno::Any; + using css::style::VerticalAlignment_TOP; + using css::style::VerticalAlignment; + using css::uno::WeakReference; + using css::awt::grid::GridDataEvent; + using css::awt::grid::XSortableGridData; + using css::beans::Pair; + + + //= UnoControlTableModel_Impl + + typedef ::std::vector< PTableModelListener > ModellListeners; + typedef ::std::vector< PColumnModel > ColumnModels; + struct UnoControlTableModel_Impl + { + ColumnModels aColumns; + bool bHasColumnHeaders; + bool bHasRowHeaders; + ScrollbarVisibility eVScrollMode; + ScrollbarVisibility eHScrollMode; + PTableRenderer pRenderer; + PTableInputHandler pInputHandler; + TableMetrics nRowHeight; + TableMetrics nColumnHeaderHeight; + TableMetrics nRowHeaderWidth; + ::std::optional< ::Color > m_aGridLineColor; + ::std::optional< ::Color > m_aHeaderBackgroundColor; + ::std::optional< ::Color > m_aHeaderTextColor; + ::std::optional< ::Color > m_aActiveSelectionBackColor; + ::std::optional< ::Color > m_aInactiveSelectionBackColor; + ::std::optional< ::Color > m_aActiveSelectionTextColor; + ::std::optional< ::Color > m_aInactiveSelectionTextColor; + ::std::optional< ::Color > m_aTextColor; + ::std::optional< ::Color > m_aTextLineColor; + ::std::optional< ::std::vector< ::Color > > m_aRowColors; + VerticalAlignment m_eVerticalAlign; + bool bEnabled; + ModellListeners m_aListeners; + WeakReference< XGridDataModel > m_aDataModel; + WeakReference< XGridColumnModel > m_aColumnModel; + + UnoControlTableModel_Impl() + :aColumns ( ) + ,bHasColumnHeaders ( true ) + ,bHasRowHeaders ( false ) + ,eVScrollMode ( ScrollbarShowNever ) + ,eHScrollMode ( ScrollbarShowNever ) + ,pRenderer ( ) + ,pInputHandler ( ) + ,nRowHeight ( 10 ) + ,nColumnHeaderHeight ( 10 ) + ,nRowHeaderWidth ( 10 ) + ,m_aGridLineColor ( ) + ,m_aHeaderBackgroundColor ( ) + ,m_aHeaderTextColor ( ) + ,m_aActiveSelectionBackColor ( ) + ,m_aInactiveSelectionBackColor ( ) + ,m_aActiveSelectionTextColor ( ) + ,m_aInactiveSelectionTextColor ( ) + ,m_aTextColor ( ) + ,m_aTextLineColor ( ) + ,m_aRowColors ( ) + ,m_eVerticalAlign ( VerticalAlignment_TOP ) + ,bEnabled ( true ) + { + } + }; + + //= UnoControlTableModel +#define DBG_CHECK_ME() \ + DBG_TESTSOLARMUTEX(); \ + + UnoControlTableModel::UnoControlTableModel() + :m_pImpl( new UnoControlTableModel_Impl ) + { + m_pImpl->bHasColumnHeaders = true; + m_pImpl->bHasRowHeaders = false; + m_pImpl->bEnabled = true; + m_pImpl->pRenderer = std::make_shared<GridTableRenderer>( *this ); + m_pImpl->pInputHandler = std::make_shared<DefaultInputHandler>(); + } + + + UnoControlTableModel::~UnoControlTableModel() + { + } + + + TableSize UnoControlTableModel::getColumnCount() const + { + DBG_CHECK_ME(); + return static_cast<TableSize>(m_pImpl->aColumns.size()); + } + + + TableSize UnoControlTableModel::getRowCount() const + { + DBG_CHECK_ME(); + + TableSize nRowCount = 0; + try + { + Reference< XGridDataModel > const xDataModel( m_pImpl->m_aDataModel ); + ENSURE_OR_THROW( xDataModel.is(), "no data model anymore!" ); + nRowCount = xDataModel->getRowCount(); + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION("svtools.uno"); + } + return nRowCount; + } + + + bool UnoControlTableModel::hasColumnHeaders() const + { + DBG_CHECK_ME(); + return m_pImpl->bHasColumnHeaders; + } + + + bool UnoControlTableModel::hasRowHeaders() const + { + DBG_CHECK_ME(); + return m_pImpl->bHasRowHeaders; + } + + + void UnoControlTableModel::setRowHeaders(bool _bRowHeaders) + { + DBG_CHECK_ME(); + if ( m_pImpl->bHasRowHeaders == _bRowHeaders ) + return; + + m_pImpl->bHasRowHeaders = _bRowHeaders; + impl_notifyTableMetricsChanged(); + } + + + void UnoControlTableModel::setColumnHeaders(bool _bColumnHeaders) + { + DBG_CHECK_ME(); + if ( m_pImpl->bHasColumnHeaders == _bColumnHeaders ) + return; + + m_pImpl->bHasColumnHeaders = _bColumnHeaders; + impl_notifyTableMetricsChanged(); + } + + + PColumnModel UnoControlTableModel::getColumnModel( ColPos column ) + { + DBG_CHECK_ME(); + ENSURE_OR_RETURN( ( column >= 0 ) && ( column < getColumnCount() ), + "DefaultTableModel::getColumnModel: invalid index!", PColumnModel() ); + return m_pImpl->aColumns[ column ]; + } + + + void UnoControlTableModel::appendColumn( Reference< XGridColumn > const & i_column ) + { + DBG_CHECK_ME(); + insertColumn( m_pImpl->aColumns.size(), i_column ); + } + + + void UnoControlTableModel::insertColumn( ColPos const i_position, Reference< XGridColumn > const & i_column ) + { + DBG_CHECK_ME(); + ENSURE_OR_RETURN_VOID( ( i_position >= 0 ) && ( o3tl::make_unsigned( i_position ) <= m_pImpl->aColumns.size() ), + "UnoControlTableModel::insertColumn: illegal position!" ); + + const PColumnModel pColumn = std::make_shared<UnoGridColumnFacade>( *this, i_column ); + m_pImpl->aColumns.insert( m_pImpl->aColumns.begin() + i_position, pColumn ); + + // notify listeners + ModellListeners aListeners( m_pImpl->m_aListeners ); + for (auto const& listener : aListeners) + { + listener->columnInserted(); + } + } + + + void UnoControlTableModel::removeColumn( ColPos const i_position ) + { + DBG_CHECK_ME(); + ENSURE_OR_RETURN_VOID( ( i_position >= 0 ) && ( o3tl::make_unsigned( i_position ) <= m_pImpl->aColumns.size() ), + "UnoControlTableModel::removeColumn: illegal position!" ); + + // remove the column + ColumnModels::iterator pos = m_pImpl->aColumns.begin() + i_position; + const PColumnModel pColumn = *pos; + m_pImpl->aColumns.erase( pos ); + + // notify listeners + ModellListeners aListeners( m_pImpl->m_aListeners ); + for (auto const& listener : aListeners) + { + listener->columnRemoved(); + } + + // dispose the column + UnoGridColumnFacade* pColumnImpl = dynamic_cast< UnoGridColumnFacade* >( pColumn.get() ); + OSL_ENSURE( pColumnImpl != nullptr, "UnoControlTableModel::removeColumn: illegal column implementation!" ); + if ( pColumnImpl ) + pColumnImpl->dispose(); + } + + + void UnoControlTableModel::removeAllColumns() + { + DBG_CHECK_ME(); + if ( m_pImpl->aColumns.empty() ) + return; + + // dispose the column instances + for (auto const& col : m_pImpl->aColumns) + { + UnoGridColumnFacade* pColumn = dynamic_cast< UnoGridColumnFacade* >( col.get() ); + if ( !pColumn ) + { + SAL_WARN( "svtools.uno", "UnoControlTableModel::removeAllColumns: illegal column implementation!" ); + continue; + } + + pColumn->dispose(); + } + m_pImpl->aColumns.clear(); + + // notify listeners + ModellListeners aListeners( m_pImpl->m_aListeners ); + for (auto const& listener : aListeners) + { + listener->allColumnsRemoved(); + } + } + + + void UnoControlTableModel::impl_notifyTableMetricsChanged() const + { + ModellListeners aListeners( m_pImpl->m_aListeners ); + for (auto const& listener : aListeners) + { + listener->tableMetricsChanged(); + } + } + + + PTableRenderer UnoControlTableModel::getRenderer() const + { + DBG_CHECK_ME(); + return m_pImpl->pRenderer; + } + + + PTableInputHandler UnoControlTableModel::getInputHandler() const + { + DBG_CHECK_ME(); + return m_pImpl->pInputHandler; + } + + + TableMetrics UnoControlTableModel::getRowHeight() const + { + DBG_CHECK_ME(); + return m_pImpl->nRowHeight; + } + + + void UnoControlTableModel::setRowHeight(TableMetrics _nRowHeight) + { + DBG_CHECK_ME(); + if ( m_pImpl->nRowHeight == _nRowHeight ) + return; + + m_pImpl->nRowHeight = _nRowHeight; + impl_notifyTableMetricsChanged(); + } + + + TableMetrics UnoControlTableModel::getColumnHeaderHeight() const + { + DBG_CHECK_ME(); + DBG_ASSERT( hasColumnHeaders(), "DefaultTableModel::getColumnHeaderHeight: invalid call!" ); + return m_pImpl->nColumnHeaderHeight; + } + + + TableMetrics UnoControlTableModel::getRowHeaderWidth() const + { + DBG_CHECK_ME(); + DBG_ASSERT( hasRowHeaders(), "DefaultTableModel::getRowHeaderWidth: invalid call!" ); + return m_pImpl->nRowHeaderWidth; + } + + void UnoControlTableModel::setColumnHeaderHeight(TableMetrics _nHeight) + { + DBG_CHECK_ME(); + if ( m_pImpl->nColumnHeaderHeight == _nHeight ) + return; + + m_pImpl->nColumnHeaderHeight = _nHeight; + impl_notifyTableMetricsChanged(); + } + + + void UnoControlTableModel::setRowHeaderWidth(TableMetrics _nWidth) + { + DBG_CHECK_ME(); + if ( m_pImpl->nRowHeaderWidth == _nWidth ) + return; + + m_pImpl->nRowHeaderWidth = _nWidth; + impl_notifyTableMetricsChanged(); + } + + + ScrollbarVisibility UnoControlTableModel::getVerticalScrollbarVisibility() const + { + DBG_CHECK_ME(); + return m_pImpl->eVScrollMode; + } + + + ScrollbarVisibility UnoControlTableModel::getHorizontalScrollbarVisibility() const + { + DBG_CHECK_ME(); + return m_pImpl->eHScrollMode; + } + + + void UnoControlTableModel::addTableModelListener( const PTableModelListener& i_listener ) + { + DBG_CHECK_ME(); + ENSURE_OR_RETURN_VOID( !!i_listener, "illegal NULL listener" ); + m_pImpl->m_aListeners.push_back( i_listener ); + } + + + void UnoControlTableModel::removeTableModelListener( const PTableModelListener& i_listener ) + { + DBG_CHECK_ME(); + auto lookup = std::find(m_pImpl->m_aListeners.begin(), m_pImpl->m_aListeners.end(), i_listener); + if (lookup != m_pImpl->m_aListeners.end()) + { + m_pImpl->m_aListeners.erase( lookup ); + return; + } + OSL_ENSURE( false, "UnoControlTableModel::removeTableModelListener: listener is not registered - sure you're doing the right thing here?" ); + } + + + void UnoControlTableModel::setVerticalScrollbarVisibility( ScrollbarVisibility const i_visibility ) const + { + DBG_CHECK_ME(); + m_pImpl->eVScrollMode = i_visibility; + } + + + void UnoControlTableModel::setHorizontalScrollbarVisibility( ScrollbarVisibility const i_visibility ) const + { + DBG_CHECK_ME(); + m_pImpl->eHScrollMode = i_visibility; + } + + + void UnoControlTableModel::setDataModel( Reference< XGridDataModel > const & i_gridDataModel ) + { + DBG_CHECK_ME(); + m_pImpl->m_aDataModel = i_gridDataModel; + // TODO: register as listener, so we're notified of row/data changes, and can multiplex them to our + // own listeners + } + + + Reference< XGridDataModel > UnoControlTableModel::getDataModel() const + { + Reference< XGridDataModel > const xDataModel( m_pImpl->m_aDataModel ); + return xDataModel; + } + + + bool UnoControlTableModel::hasDataModel() const + { + return getDataModel().is(); + } + + + void UnoControlTableModel::setColumnModel( Reference< XGridColumnModel > const & i_gridColumnModel ) + { + DBG_CHECK_ME(); + m_pImpl->m_aColumnModel = i_gridColumnModel; + } + + + Reference< XGridColumnModel > UnoControlTableModel::getColumnModel() const + { + Reference< XGridColumnModel > const xColumnModel( m_pImpl->m_aColumnModel ); + return xColumnModel; + } + + + bool UnoControlTableModel::hasColumnModel() const + { + return getColumnModel().is(); + } + + + void UnoControlTableModel::getCellContent( ColPos const i_col, RowPos const i_row, Any& o_cellContent ) + { + DBG_CHECK_ME(); + + o_cellContent.clear(); + try + { + Reference< XGridDataModel > const xDataModel( m_pImpl->m_aDataModel ); + ENSURE_OR_RETURN_VOID( xDataModel.is(), "UnoControlTableModel::getCellContent: no data model anymore!" ); + + PColumnModel const pColumn = getColumnModel( i_col ); + UnoGridColumnFacade* pColumnImpl = dynamic_cast< UnoGridColumnFacade* >( pColumn.get() ); + ENSURE_OR_RETURN_VOID( pColumnImpl != nullptr, "UnoControlTableModel::getCellContent: no (valid) column at this position!" ); + sal_Int32 const nDataColumnIndex = pColumnImpl->getDataColumnIndex() >= 0 ? pColumnImpl->getDataColumnIndex() : i_col; + + if ( nDataColumnIndex >= xDataModel->getColumnCount() ) + { + // this is allowed, in case the column model has been dynamically extended, but the data model does + // not (yet?) know about it. + // So, handle it gracefully. + #if OSL_DEBUG_LEVEL > 0 + Reference< XGridColumnModel > const xColumnModel( m_pImpl->m_aColumnModel ); + OSL_ENSURE( xColumnModel.is() && i_col < xColumnModel->getColumnCount(), + "UnoControlTableModel::getCellContent: request a column's value which the ColumnModel doesn't know about!" ); + #endif + } + else + { + o_cellContent = xDataModel->getCellData( nDataColumnIndex, i_row ); + } + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION("svtools.uno"); + } + } + + + void UnoControlTableModel::getCellToolTip( ColPos const i_col, RowPos const i_row, Any& o_cellToolTip ) + { + DBG_CHECK_ME(); + try + { + Reference< XGridDataModel > const xDataModel( m_pImpl->m_aDataModel ); + ENSURE_OR_THROW( xDataModel.is(), "no data model anymore!" ); + + o_cellToolTip = xDataModel->getCellToolTip( i_col, i_row ); + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION("svtools.uno"); + } + } + + + Any UnoControlTableModel::getRowHeading( RowPos const i_rowPos ) const + { + DBG_CHECK_ME(); + + Any aRowHeading; + + Reference< XGridDataModel > const xDataModel( m_pImpl->m_aDataModel ); + ENSURE_OR_RETURN( xDataModel.is(), "UnoControlTableModel::getRowHeading: no data model anymore!", aRowHeading ); + + try + { + aRowHeading = xDataModel->getRowHeading( i_rowPos ); + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION("svtools.uno"); + } + return aRowHeading; + } + + + namespace + { + void lcl_setColor( Any const & i_color, ::std::optional< ::Color > & o_convertedColor ) + { + if ( !i_color.hasValue() ) + o_convertedColor.reset(); + else + { + Color nColor = COL_TRANSPARENT; + if ( i_color >>= nColor ) + { + o_convertedColor = nColor; + } + else + { + OSL_ENSURE( false, "lcl_setColor: could not extract color value!" ); + } + } + } + } + + + ::std::optional< ::Color > UnoControlTableModel::getLineColor() const + { + DBG_CHECK_ME(); + return m_pImpl->m_aGridLineColor; + } + + + void UnoControlTableModel::setLineColor( Any const & i_color ) + { + DBG_CHECK_ME(); + lcl_setColor( i_color, m_pImpl->m_aGridLineColor ); + } + + + ::std::optional< ::Color > UnoControlTableModel::getHeaderBackgroundColor() const + { + DBG_CHECK_ME(); + return m_pImpl->m_aHeaderBackgroundColor; + } + + + void UnoControlTableModel::setHeaderBackgroundColor( Any const & i_color ) + { + DBG_CHECK_ME(); + lcl_setColor( i_color, m_pImpl->m_aHeaderBackgroundColor ); + } + + + ::std::optional< ::Color > UnoControlTableModel::getHeaderTextColor() const + { + DBG_CHECK_ME(); + return m_pImpl->m_aHeaderTextColor; + } + + + ::std::optional< ::Color > UnoControlTableModel::getActiveSelectionBackColor() const + { + DBG_CHECK_ME(); + return m_pImpl->m_aActiveSelectionBackColor; + } + + + ::std::optional< ::Color > UnoControlTableModel::getInactiveSelectionBackColor() const + { + DBG_CHECK_ME(); + return m_pImpl->m_aInactiveSelectionBackColor; + } + + + ::std::optional< ::Color > UnoControlTableModel::getActiveSelectionTextColor() const + { + DBG_CHECK_ME(); + return m_pImpl->m_aActiveSelectionTextColor; + } + + + ::std::optional< ::Color > UnoControlTableModel::getInactiveSelectionTextColor() const + { + DBG_CHECK_ME(); + return m_pImpl->m_aInactiveSelectionTextColor; + } + + + void UnoControlTableModel::setHeaderTextColor( Any const & i_color ) + { + DBG_CHECK_ME(); + lcl_setColor( i_color, m_pImpl->m_aHeaderTextColor ); + } + + + void UnoControlTableModel::setActiveSelectionBackColor( Any const & i_color ) + { + DBG_CHECK_ME(); + lcl_setColor( i_color, m_pImpl->m_aActiveSelectionBackColor ); + } + + + void UnoControlTableModel::setInactiveSelectionBackColor( Any const & i_color ) + { + DBG_CHECK_ME(); + lcl_setColor( i_color, m_pImpl->m_aInactiveSelectionBackColor ); + } + + + void UnoControlTableModel::setActiveSelectionTextColor( Any const & i_color ) + { + DBG_CHECK_ME(); + lcl_setColor( i_color, m_pImpl->m_aActiveSelectionTextColor ); + } + + + void UnoControlTableModel::setInactiveSelectionTextColor( Any const & i_color ) + { + DBG_CHECK_ME(); + lcl_setColor( i_color, m_pImpl->m_aInactiveSelectionTextColor ); + } + + + ::std::optional< ::Color > UnoControlTableModel::getTextColor() const + { + DBG_CHECK_ME(); + return m_pImpl->m_aTextColor; + } + + + void UnoControlTableModel::setTextColor( Any const & i_color ) + { + DBG_CHECK_ME(); + lcl_setColor( i_color, m_pImpl->m_aTextColor ); + } + + + ::std::optional< ::Color > UnoControlTableModel::getTextLineColor() const + { + DBG_CHECK_ME(); + return m_pImpl->m_aTextColor; + } + + + void UnoControlTableModel::setTextLineColor( Any const & i_color ) + { + DBG_CHECK_ME(); + lcl_setColor( i_color, m_pImpl->m_aTextLineColor ); + } + + + ::std::optional< ::std::vector< ::Color > > UnoControlTableModel::getRowBackgroundColors() const + { + DBG_CHECK_ME(); + return m_pImpl->m_aRowColors; + } + + + void UnoControlTableModel::setRowBackgroundColors( css::uno::Any const & i_APIValue ) + { + DBG_CHECK_ME(); + Sequence< css::util::Color > aAPIColors; + if ( !( i_APIValue >>= aAPIColors ) ) + m_pImpl->m_aRowColors.reset(); + else + { + ::std::vector< ::Color > aColors( aAPIColors.getLength() ); + std::transform(aAPIColors.begin(), aAPIColors.end(), aColors.begin(), + [](const css::util::Color& rAPIColor) -> ::Color { return Color(rAPIColor); }); + m_pImpl->m_aRowColors = aColors; + } + } + + + VerticalAlignment UnoControlTableModel::getVerticalAlign() const + { + DBG_CHECK_ME(); + return m_pImpl->m_eVerticalAlign; + } + + + void UnoControlTableModel::setVerticalAlign( VerticalAlignment _xAlign ) + { + DBG_CHECK_ME(); + m_pImpl->m_eVerticalAlign = _xAlign; + } + + + ColPos UnoControlTableModel::getColumnPos( UnoGridColumnFacade const & i_column ) const + { + DBG_CHECK_ME(); + ColPos nPos = 0; + for (auto const& col : m_pImpl->aColumns) + { + if ( &i_column == col.get() ) + return nPos; + ++nPos; + } + OSL_ENSURE( false, "UnoControlTableModel::getColumnPos: column not found!" ); + return COL_INVALID; + } + + + ITableDataSort* UnoControlTableModel::getSortAdapter() + { + DBG_CHECK_ME(); + + Reference< XSortableGridData > const xSortAccess( getDataModel(), UNO_QUERY ); + if ( xSortAccess.is() ) + return this; + return nullptr; + } + + + bool UnoControlTableModel::isEnabled() const + { + DBG_CHECK_ME(); + return m_pImpl->bEnabled; + } + + + void UnoControlTableModel::setEnabled( bool _bEnabled ) + { + DBG_CHECK_ME(); + m_pImpl->bEnabled = _bEnabled; + } + + + void UnoControlTableModel::sortByColumn( ColPos const i_column, ColumnSortDirection const i_sortDirection ) + { + DBG_CHECK_ME(); + + try + { + Reference< XSortableGridData > const xSortAccess( getDataModel(), UNO_QUERY_THROW ); + xSortAccess->sortByColumn( i_column, i_sortDirection == ColumnSortAscending ); + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION("svtools.uno"); + } + } + + + ColumnSort UnoControlTableModel::getCurrentSortOrder() const + { + DBG_CHECK_ME(); + + ColumnSort currentSort; + try + { + Reference< XSortableGridData > const xSortAccess( getDataModel(), UNO_QUERY_THROW ); + Pair< ::sal_Int32, sal_Bool > const aCurrentSortOrder( xSortAccess->getCurrentSortOrder() ); + currentSort.nColumnPos = aCurrentSortOrder.First; + currentSort.eSortDirection = aCurrentSortOrder.Second ? ColumnSortAscending : ColumnSortDescending; + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION("svtools.uno"); + } + return currentSort; + } + + + void UnoControlTableModel::notifyColumnChange( ColPos const i_columnPos, ColumnAttributeGroup const i_attributeGroup ) const + { + DBG_CHECK_ME(); + ENSURE_OR_RETURN_VOID( ( i_columnPos >= 0 ) && ( i_columnPos < getColumnCount() ), + "UnoControlTableModel::notifyColumnChange: invalid column index!" ); + + ModellListeners aListeners( m_pImpl->m_aListeners ); + for (auto const& listener : aListeners) + { + listener->columnChanged( i_columnPos, i_attributeGroup ); + } + } + + + void UnoControlTableModel::notifyRowsInserted( GridDataEvent const & i_event ) const + { + // check sanity of the event + ENSURE_OR_RETURN_VOID( i_event.FirstRow >= 0, "UnoControlTableModel::notifyRowsInserted: invalid first row!" ); + ENSURE_OR_RETURN_VOID( i_event.LastRow >= i_event.FirstRow, "UnoControlTableModel::notifyRowsInserted: invalid row indexes!" ); + + // check own sanity + Reference< XGridColumnModel > const xColumnModel( m_pImpl->m_aColumnModel ); + ENSURE_OR_RETURN_VOID( xColumnModel.is(), "UnoControlTableModel::notifyRowsInserted: no column model anymore!" ); + + Reference< XGridDataModel > const xDataModel( m_pImpl->m_aDataModel ); + ENSURE_OR_RETURN_VOID( xDataModel.is(), "UnoControlTableModel::notifyRowsInserted: no data model anymore!" ); + + // implicitly add columns to the column model + // TODO: is this really a good idea? + sal_Int32 const dataColumnCount = xDataModel->getColumnCount(); + OSL_ENSURE( dataColumnCount > 0, "UnoControlTableModel::notifyRowsInserted: no columns at all?" ); + + sal_Int32 const modelColumnCount = xColumnModel->getColumnCount(); + if ( ( modelColumnCount == 0 ) && ( dataColumnCount > 0 ) ) + { + // TODO: shouldn't we clear the mutexes guard for this call? + xColumnModel->setDefaultColumns( dataColumnCount ); + } + + // multiplex the event to our own listeners + ModellListeners aListeners( m_pImpl->m_aListeners ); + for (auto const& listener : aListeners) + { + listener->rowsInserted( i_event.FirstRow, i_event.LastRow ); + } + } + + + void UnoControlTableModel::notifyRowsRemoved( GridDataEvent const & i_event ) const + { + ModellListeners aListeners( m_pImpl->m_aListeners ); + for (auto const& listener : aListeners) + { + listener->rowsRemoved( i_event.FirstRow, i_event.LastRow ); + } + } + + + void UnoControlTableModel::notifyDataChanged( css::awt::grid::GridDataEvent const & i_event ) const + { + RowPos const firstRow = i_event.FirstRow == -1 ? 0 : i_event.FirstRow; + RowPos const lastRow = i_event.FirstRow == -1 ? getRowCount() - 1 : i_event.LastRow; + + ModellListeners aListeners( m_pImpl->m_aListeners ); + for (auto const& listener : aListeners) + { + listener->cellsUpdated( firstRow, lastRow ); + } + } + + + void UnoControlTableModel::notifyAllDataChanged() const + { + ModellListeners aListeners( m_pImpl->m_aListeners ); + for (auto const& listener : aListeners) + { + listener->cellsUpdated( 0, getRowCount() - 1 ); + } + } + + +} // svt::table + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/uno/unocontroltablemodel.hxx b/svtools/source/uno/unocontroltablemodel.hxx new file mode 100644 index 000000000..53aa83265 --- /dev/null +++ b/svtools/source/uno/unocontroltablemodel.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 . + */ + +#pragma once + +#include <table/tablemodel.hxx> +#include <table/tablesort.hxx> + +#include <com/sun/star/awt/grid/GridDataEvent.hpp> +#include <com/sun/star/awt/grid/XGridColumnModel.hpp> +#include <com/sun/star/awt/grid/XGridDataModel.hpp> +#include <com/sun/star/awt/grid/XGridColumn.hpp> +#include <com/sun/star/style/VerticalAlignment.hpp> + +#include <memory> + + +namespace svt::table +{ + + + //= UnoControlTableModel + + class UnoGridColumnFacade; + struct UnoControlTableModel_Impl; + class UnoControlTableModel : public ITableModel, public ITableDataSort + { + private: + std::unique_ptr<UnoControlTableModel_Impl> m_pImpl; + + public: + UnoControlTableModel(); + virtual ~UnoControlTableModel() override; + + public: + // ITableModel overridables + virtual TableSize getColumnCount() const override; + virtual TableSize getRowCount() const override; + virtual bool hasColumnHeaders() const override; + virtual bool hasRowHeaders() const override; + virtual PColumnModel getColumnModel( ColPos column ) override; + virtual PTableRenderer getRenderer() const override; + virtual PTableInputHandler getInputHandler() const override; + virtual TableMetrics getRowHeight() const override; + virtual TableMetrics getColumnHeaderHeight() const override; + virtual TableMetrics getRowHeaderWidth() const override; + virtual ScrollbarVisibility getVerticalScrollbarVisibility() const override; + virtual ScrollbarVisibility getHorizontalScrollbarVisibility() const override; + virtual void addTableModelListener( const PTableModelListener& i_listener ) override; + virtual void removeTableModelListener( const PTableModelListener& i_listener ) override; + virtual void getCellContent( ColPos const i_col, RowPos const i_row, css::uno::Any& o_cellContent ) override; + virtual void getCellToolTip( ColPos const i_col, RowPos const i_row, css::uno::Any & o_cellToolTip ) override; + virtual css::uno::Any getRowHeading( RowPos const i_rowPos ) const override; + virtual ::std::optional< ::Color > getLineColor() const override; + virtual ::std::optional< ::Color > getHeaderBackgroundColor() const override; + virtual ::std::optional< ::Color > getHeaderTextColor() const override; + virtual ::std::optional< ::Color > getActiveSelectionBackColor() const override; + virtual ::std::optional< ::Color > getInactiveSelectionBackColor() const override; + virtual ::std::optional< ::Color > getActiveSelectionTextColor() const override; + virtual ::std::optional< ::Color > getInactiveSelectionTextColor() const override; + virtual ::std::optional< ::Color > getTextColor() const override; + virtual ::std::optional< ::Color > getTextLineColor() const override; + virtual ::std::optional< ::std::vector< ::Color > > + getRowBackgroundColors() const override; + virtual css::style::VerticalAlignment + getVerticalAlign() const override; + virtual ITableDataSort* getSortAdapter() override; + virtual bool isEnabled() const override; + + // ITableDataSort overridables + virtual void sortByColumn( ColPos const i_column, ColumnSortDirection const i_sortDirection ) override; + virtual ColumnSort getCurrentSortOrder() const override; + + // column write access + void appendColumn( css::uno::Reference< css::awt::grid::XGridColumn > const & i_column ); + void insertColumn( ColPos const i_position, css::uno::Reference< css::awt::grid::XGridColumn > const & i_column ); + void removeColumn( ColPos const i_position ); + void removeAllColumns(); + + // other operations + void setVerticalScrollbarVisibility( ScrollbarVisibility const i_visibility ) const; + void setHorizontalScrollbarVisibility( ScrollbarVisibility const i_visibility ) const; + + void setDataModel( css::uno::Reference< css::awt::grid::XGridDataModel > const & i_gridDataModel ); + bool hasDataModel() const; + css::uno::Reference< css::awt::grid::XGridDataModel > + getDataModel() const; + void setColumnModel( css::uno::Reference< css::awt::grid::XGridColumnModel > const & i_gridColumnModel ); + bool hasColumnModel() const; + css::uno::Reference< css::awt::grid::XGridColumnModel > + getColumnModel() const; + + void setRowHeaders(bool _bRowHeaders); + void setColumnHeaders(bool _bColumnHeaders); + + void setRowHeight( TableMetrics _nHeight ); + void setRowHeaderWidth( TableMetrics _nWidth ); + void setColumnHeaderHeight( TableMetrics _nHeight ); + + void setLineColor( css::uno::Any const & i_color ); + void setHeaderBackgroundColor( css::uno::Any const & i_color ); + void setHeaderTextColor( css::uno::Any const & i_color ); + void setActiveSelectionBackColor( css::uno::Any const & i_color ); + void setInactiveSelectionBackColor( css::uno::Any const & i_color ); + void setActiveSelectionTextColor( css::uno::Any const & i_color ); + void setInactiveSelectionTextColor( css::uno::Any const & i_color ); + void setTextColor( css::uno::Any const & i_color ); + void setTextLineColor( css::uno::Any const & i_color ); + void setRowBackgroundColors( css::uno::Any const & i_APIValue ); + + void setVerticalAlign(css::style::VerticalAlignment _rAlign); + void setEnabled( bool _bEnabled ); + + // multiplexing of XGridDataListener events + void notifyRowsInserted( css::awt::grid::GridDataEvent const & i_event ) const; + void notifyRowsRemoved( css::awt::grid::GridDataEvent const & i_event ) const; + void notifyDataChanged( css::awt::grid::GridDataEvent const & i_event ) const; + + /// retrieves the index of a column within the model + ColPos getColumnPos( UnoGridColumnFacade const & i_column ) const; + + /// notifies a change in a column belonging to the model + void notifyColumnChange( ColPos const i_columnPos, ColumnAttributeGroup const i_attributeGroup ) const; + + /** notifies a change in all data represented by the model. To be used if you cannot specified the changed data + in more detail. + */ + void notifyAllDataChanged() const; + + private: + void impl_notifyTableMetricsChanged() const; + }; + + +} // svt::table + + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/uno/unoevent.cxx b/svtools/source/uno/unoevent.cxx new file mode 100644 index 000000000..244ee6549 --- /dev/null +++ b/svtools/source/uno/unoevent.cxx @@ -0,0 +1,484 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <com/sun/star/beans/PropertyValue.hpp> +#include <cppuhelper/supportsservice.hxx> +#include <osl/diagnose.h> +#include <sfx2/event.hxx> +#include <svtools/unoevent.hxx> +#include <svl/macitem.hxx> + +using namespace ::com::sun::star; +using namespace css::uno; + +using css::container::NoSuchElementException; +using css::container::XNameReplace; +using css::lang::IllegalArgumentException; +using css::beans::PropertyValue; + + +static const char sAPI_ServiceName[] = "com.sun.star.container.XNameReplace"; +static const char sEventType[] = "EventType"; +static const char sMacroName[] = "MacroName"; +static const char sLibrary[] = "Library"; +static const char sStarBasic[] = "StarBasic"; +static const char sScript[] = "Script"; +static const char sNone[] = "None"; + +namespace { + +void getAnyFromMacro(Any& rAny, const SvxMacro& rMacro) +{ + bool bRetValueOK = false; // do we have a ret value? + + if (rMacro.HasMacro()) + { + switch (rMacro.GetScriptType()) + { + case STARBASIC: + { + // create sequence + Sequence<PropertyValue> aSequence(3); + Any aTmp; + + // create type + PropertyValue aTypeValue; + aTypeValue.Name = sEventType; + aTmp <<= OUString(sStarBasic); + aTypeValue.Value = aTmp; + aSequence[0] = aTypeValue; + + // macro name + PropertyValue aNameValue; + aNameValue.Name = sMacroName; + const OUString& sNameTmp(rMacro.GetMacName()); + aTmp <<= sNameTmp; + aNameValue.Value = aTmp; + aSequence[1] = aNameValue; + + // library name + PropertyValue aLibValue; + aLibValue.Name = sLibrary; + const OUString& sLibTmp(rMacro.GetLibName()); + aTmp <<= sLibTmp; + aLibValue.Value = aTmp; + aSequence[2] = aLibValue; + + rAny <<= aSequence; + bRetValueOK = true; + break; + } + case EXTENDED_STYPE: + { + // create sequence + Sequence<PropertyValue> aSequence(2); + Any aTmp; + + // create type + PropertyValue aTypeValue; + aTypeValue.Name = sEventType; + aTmp <<= OUString(sScript); + aTypeValue.Value = aTmp; + aSequence[0] = aTypeValue; + + // macro name + PropertyValue aNameValue; + aNameValue.Name = sScript; + const OUString& sNameTmp(rMacro.GetMacName()); + aTmp <<= sNameTmp; + aNameValue.Value = aTmp; + aSequence[1] = aNameValue; + + rAny <<= aSequence; + bRetValueOK = true; + break; + } + case JAVASCRIPT: + default: + OSL_FAIL("not implemented"); + } + } + // else: bRetValueOK not set + + // if we don't have a return value, make an empty one + if ( bRetValueOK) + return; + + // create "None" macro + Sequence<PropertyValue> aSequence(1); + + PropertyValue aKindValue; + aKindValue.Name = sEventType; + Any aTmp; + aTmp <<= OUString(sNone); + aKindValue.Value = aTmp; + aSequence[0] = aKindValue; + + rAny <<= aSequence; +} + +/// @throws IllegalArgumentException +void getMacroFromAny( + SvxMacro& rMacro, + const Any& rAny) +{ + // get sequence + Sequence<PropertyValue> aSequence; + rAny >>= aSequence; + + // process ... + bool bTypeOK = false; + bool bNone = false; // true if EventType=="None" + enum ScriptType eType = EXTENDED_STYPE; + OUString sScriptVal; + OUString sMacroVal; + OUString sLibVal; + for (const PropertyValue& aValue : std::as_const(aSequence)) + { + if (aValue.Name == sEventType) + { + OUString sTmp; + aValue.Value >>= sTmp; + if (sTmp == sStarBasic) + { + eType = STARBASIC; + bTypeOK = true; + } + else if (sTmp == "JavaScript") + { + eType = JAVASCRIPT; + bTypeOK = true; + } + else if (sTmp == sScript) + { + eType = EXTENDED_STYPE; + bTypeOK = true; + } + else if (sTmp == sNone) + { + bNone = true; + bTypeOK = true; + } + // else: unknown script type + } + else if (aValue.Name == sMacroName) + { + aValue.Value >>= sMacroVal; + } + else if (aValue.Name == sLibrary) + { + aValue.Value >>= sLibVal; + } + else if (aValue.Name == sScript) + { + aValue.Value >>= sScriptVal; + } + // else: unknown PropertyValue -> ignore + } + + if (!bTypeOK) + { + // no valid type: abort + throw IllegalArgumentException(); + } + + if (bNone) + { + // return empty macro + rMacro = SvxMacro( "", "" ); + } + else + { + if (eType == STARBASIC) + { + // create macro and return + SvxMacro aMacro(sMacroVal, sLibVal, eType); + rMacro = aMacro; + } + else if (eType == EXTENDED_STYPE) + { + SvxMacro aMacro(sScriptVal, sScript); + rMacro = aMacro; + } + else + { + // we can't process type: abort + // TODO: JavaScript macros + throw IllegalArgumentException(); + } + } +} + +} + +SvBaseEventDescriptor::SvBaseEventDescriptor( const SvEventDescription* pSupportedMacroItems ) : + mpSupportedMacroItems(pSupportedMacroItems), + mnMacroItems(0) +{ + assert(pSupportedMacroItems != nullptr && "Need a list of supported events!"); + + for( ; mpSupportedMacroItems[mnMacroItems].mnEvent != SvMacroItemId::NONE; mnMacroItems++) ; +} + + +SvBaseEventDescriptor::~SvBaseEventDescriptor() +{ +} + +void SvBaseEventDescriptor::replaceByName( + const OUString& rName, + const Any& rElement ) +{ + SvMacroItemId nMacroID = getMacroID(rName); + + // error checking + if (SvMacroItemId::NONE == nMacroID) + throw NoSuchElementException(); + if (rElement.getValueType() != getElementType()) + throw IllegalArgumentException(); + + // get sequence + Sequence<PropertyValue> aSequence; + rElement >>= aSequence; + + // perform replace (in subclass) + SvxMacro aMacro("",""); + getMacroFromAny(aMacro, rElement); + replaceByName(nMacroID, aMacro); +} + +Any SvBaseEventDescriptor::getByName( + const OUString& rName ) +{ + SvMacroItemId nMacroID = getMacroID(rName); + + // error checking + if (SvMacroItemId::NONE == nMacroID) + throw NoSuchElementException(); + + // perform get (in subclass) + Any aAny; + SvxMacro aMacro( "", "" ); + getByName(aMacro, nMacroID); + getAnyFromMacro(aAny, aMacro); + return aAny; +} + +Sequence<OUString> SvBaseEventDescriptor::getElementNames() +{ + // create and fill sequence + Sequence<OUString> aSequence(mnMacroItems); + for( sal_Int16 i = 0; i < mnMacroItems; i++) + { + aSequence[i] = OUString::createFromAscii( mpSupportedMacroItems[i].mpEventName ); + } + + return aSequence; +} + +sal_Bool SvBaseEventDescriptor::hasByName( + const OUString& rName ) +{ + SvMacroItemId nMacroID = getMacroID(rName); + return (nMacroID != SvMacroItemId::NONE); +} + +Type SvBaseEventDescriptor::getElementType() +{ + return cppu::UnoType<Sequence<PropertyValue>>::get(); +} + +sal_Bool SvBaseEventDescriptor::hasElements() +{ + return mnMacroItems != 0; +} + +sal_Bool SvBaseEventDescriptor::supportsService(const OUString& rServiceName) +{ + return cppu::supportsService(this, rServiceName); +} + +Sequence<OUString> SvBaseEventDescriptor::getSupportedServiceNames() +{ + return { sAPI_ServiceName }; +} + +SvMacroItemId SvBaseEventDescriptor::mapNameToEventID(const OUString& rName) const +{ + // iterate over known event names + for(sal_Int16 i = 0; i < mnMacroItems; i++) + { + if( rName.equalsAscii(mpSupportedMacroItems[i].mpEventName)) + { + return mpSupportedMacroItems[i].mnEvent; + } + } + + // not found -> return zero + return SvMacroItemId::NONE; +} + +SvMacroItemId SvBaseEventDescriptor::getMacroID(const OUString& rName) const +{ + return mapNameToEventID(rName); +} + +SvEventDescriptor::SvEventDescriptor( + XInterface& rParent, + const SvEventDescription* pSupportedMacroItems) : + SvBaseEventDescriptor(pSupportedMacroItems), + xParentRef(&rParent) +{ +} + + +SvEventDescriptor::~SvEventDescriptor() +{ + // automatically release xParentRef ! +} + +void SvEventDescriptor::replaceByName( + const SvMacroItemId nEvent, + const SvxMacro& rMacro) +{ + SvxMacroItem aItem(getMacroItemWhich()); + aItem.SetMacroTable(getMacroItem().GetMacroTable()); + aItem.SetMacro(nEvent, rMacro); + setMacroItem(aItem); +} + +void SvEventDescriptor::getByName( + SvxMacro& rMacro, + const SvMacroItemId nEvent ) +{ + const SvxMacroItem& rItem = getMacroItem(); + if( rItem.HasMacro( nEvent ) ) + rMacro = rItem.GetMacro(nEvent); + else + { + SvxMacro aEmptyMacro("", ""); + rMacro = aEmptyMacro; + } +} + +SvDetachedEventDescriptor::SvDetachedEventDescriptor( + const SvEventDescription* pSupportedMacroItems) : + SvBaseEventDescriptor(pSupportedMacroItems) +{ + aMacros.resize(mnMacroItems); +} + +SvDetachedEventDescriptor::~SvDetachedEventDescriptor() +{ +} + +sal_Int16 SvDetachedEventDescriptor::getIndex(const SvMacroItemId nID) const +{ + // iterate over supported events + sal_Int16 nIndex = 0; + while ( (mpSupportedMacroItems[nIndex].mnEvent != nID) && + (mpSupportedMacroItems[nIndex].mnEvent != SvMacroItemId::NONE) ) + { + nIndex++; + } + return (mpSupportedMacroItems[nIndex].mnEvent == nID) ? nIndex : -1; +} + +OUString SvDetachedEventDescriptor::getImplementationName() +{ + return "SvDetachedEventDescriptor"; +} + + +void SvDetachedEventDescriptor::replaceByName( + const SvMacroItemId nEvent, + const SvxMacro& rMacro) +{ + sal_Int16 nIndex = getIndex(nEvent); + if (-1 == nIndex) + throw IllegalArgumentException(); + + aMacros[nIndex].reset( new SvxMacro(rMacro.GetMacName(), rMacro.GetLibName(), + rMacro.GetScriptType() ) ); +} + + +void SvDetachedEventDescriptor::getByName( + SvxMacro& rMacro, + const SvMacroItemId nEvent ) +{ + sal_Int16 nIndex = getIndex(nEvent); + if (-1 == nIndex ) + throw NoSuchElementException(); + + if( aMacros[nIndex] ) + rMacro = *aMacros[nIndex]; +} + +bool SvDetachedEventDescriptor::hasById( + const SvMacroItemId nEvent ) const /// item ID of event +{ + sal_Int16 nIndex = getIndex(nEvent); + if (-1 == nIndex) + throw IllegalArgumentException(); + + return (nullptr != aMacros[nIndex]) && aMacros[nIndex]->HasMacro(); +} + + +SvMacroTableEventDescriptor::SvMacroTableEventDescriptor(const SvEventDescription* pSupportedMacroItems) : + SvDetachedEventDescriptor(pSupportedMacroItems) +{ +} + +SvMacroTableEventDescriptor::SvMacroTableEventDescriptor( + const SvxMacroTableDtor& rMacroTable, + const SvEventDescription* pSupportedMacroItems) : + SvDetachedEventDescriptor(pSupportedMacroItems) +{ + assert(mpSupportedMacroItems); + for(sal_Int16 i = 0; mpSupportedMacroItems[i].mnEvent != SvMacroItemId::NONE; i++) + { + const SvMacroItemId nEvent = mpSupportedMacroItems[i].mnEvent; + const SvxMacro* pMacro = rMacroTable.Get(nEvent); + if (nullptr != pMacro) + replaceByName(nEvent, *pMacro); + } +} + +SvMacroTableEventDescriptor::~SvMacroTableEventDescriptor() +{ +} + +void SvMacroTableEventDescriptor::copyMacrosIntoTable( + SvxMacroTableDtor& rMacroTable) +{ + for(sal_Int16 i = 0; mpSupportedMacroItems[i].mnEvent != SvMacroItemId::NONE; i++) + { + const SvMacroItemId nEvent = mpSupportedMacroItems[i].mnEvent; + if (hasById(nEvent)) + { + SvxMacro& rMacro = rMacroTable.Insert(nEvent, SvxMacro("", "")); + getByName(rMacro, nEvent); + } + } +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/uno/unogridcolumnfacade.cxx b/svtools/source/uno/unogridcolumnfacade.cxx new file mode 100644 index 000000000..dfb291751 --- /dev/null +++ b/svtools/source/uno/unogridcolumnfacade.cxx @@ -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 . + */ + +#include "unogridcolumnfacade.hxx" +#include "unocontroltablemodel.hxx" + +#include <com/sun/star/awt/grid/XGridColumn.hpp> +#include <com/sun/star/awt/grid/XGridColumnListener.hpp> + +#include <tools/debug.hxx> +#include <tools/diagnose_ex.h> +#include <vcl/svapp.hxx> +#include <cppuhelper/implbase.hxx> + + +namespace svt::table +{ + + + using css::uno::Reference; + using css::awt::grid::XGridColumn; + using css::uno::Exception; + using css::awt::grid::XGridColumnListener; + using css::lang::EventObject; + using css::awt::grid::GridColumnEvent; + using css::style::HorizontalAlignment_LEFT; + using css::style::HorizontalAlignment; + + + namespace + { + template< class T1, class T2 > + void lcl_set( Reference< XGridColumn > const & i_column, void ( SAL_CALL XGridColumn::*i_setter )( T1 ), + T2 i_value ) + { + try + { + (i_column.get()->*i_setter) ( i_value ); + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION("svtools.uno"); + } + } + + template< class ATTRIBUTE_TYPE > + ATTRIBUTE_TYPE lcl_get( Reference< XGridColumn > const & i_column, ATTRIBUTE_TYPE ( SAL_CALL XGridColumn::*i_getter )() ) + { + ATTRIBUTE_TYPE value = ATTRIBUTE_TYPE(); + try + { + value = (i_column.get()->*i_getter)(); + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION("svtools.uno"); + } + return value; + } + } + + + //= ColumnChangeMultiplexer + + typedef ::cppu::WeakImplHelper < XGridColumnListener + > ColumnChangeMultiplexer_Base; + class ColumnChangeMultiplexer :public ColumnChangeMultiplexer_Base + { + public: + explicit ColumnChangeMultiplexer( UnoGridColumnFacade& i_colImpl ); + ColumnChangeMultiplexer(const ColumnChangeMultiplexer&) = delete; + ColumnChangeMultiplexer& operator=(const ColumnChangeMultiplexer&) = delete; + + void dispose(); + + protected: + virtual ~ColumnChangeMultiplexer() override; + + // XGridColumnListener + virtual void SAL_CALL columnChanged( const GridColumnEvent& i_event ) override; + + // XEventListener + virtual void SAL_CALL disposing( const EventObject& i_event ) override; + + private: + UnoGridColumnFacade* m_pColumnImplementation; + }; + + + ColumnChangeMultiplexer::ColumnChangeMultiplexer( UnoGridColumnFacade& i_colImpl ) + :m_pColumnImplementation( &i_colImpl ) + { + } + + + ColumnChangeMultiplexer::~ColumnChangeMultiplexer() + { + } + + + void ColumnChangeMultiplexer::dispose() + { + DBG_TESTSOLARMUTEX(); + m_pColumnImplementation = nullptr; + } + + + void SAL_CALL ColumnChangeMultiplexer::columnChanged( const GridColumnEvent& i_event ) + { + if ( i_event.AttributeName == "DataColumnIndex" ) + { + SolarMutexGuard aGuard; + if ( m_pColumnImplementation != nullptr ) + m_pColumnImplementation->dataColumnIndexChanged(); + return; + } + + ColumnAttributeGroup nChangedAttributes( ColumnAttributeGroup::NONE ); + + if ( i_event.AttributeName == "HorizontalAlign" ) + nChangedAttributes |= ColumnAttributeGroup::APPEARANCE; + + if ( i_event.AttributeName == "ColumnWidth" + || i_event.AttributeName == "MaxWidth" + || i_event.AttributeName == "MinWidth" + || i_event.AttributeName == "PreferredWidth" + || i_event.AttributeName == "Resizeable" + || i_event.AttributeName == "Flexibility" + ) + nChangedAttributes |= ColumnAttributeGroup::WIDTH; + + OSL_ENSURE( nChangedAttributes != ColumnAttributeGroup::NONE, + "ColumnChangeMultiplexer::columnChanged: unknown column attributed changed!" ); + + SolarMutexGuard aGuard; + if ( m_pColumnImplementation != nullptr ) + m_pColumnImplementation->columnChanged( nChangedAttributes ); + } + + + void SAL_CALL ColumnChangeMultiplexer::disposing( const EventObject& ) + { + } + + + //= UnoGridColumnFacade + + + UnoGridColumnFacade::UnoGridColumnFacade( UnoControlTableModel const & i_owner, Reference< XGridColumn > const & i_gridColumn ) + :m_pOwner( &i_owner ) + ,m_nDataColumnIndex( -1 ) + ,m_xGridColumn( i_gridColumn, css::uno::UNO_SET_THROW ) + ,m_pChangeMultiplexer( new ColumnChangeMultiplexer( *this ) ) + { + m_xGridColumn->addGridColumnListener( m_pChangeMultiplexer.get() ); + impl_updateDataColumnIndex_nothrow(); + } + + + UnoGridColumnFacade::~UnoGridColumnFacade() + { + } + + + void UnoGridColumnFacade::dispose() + { + DBG_TESTSOLARMUTEX(); + ENSURE_OR_RETURN_VOID( m_pOwner != nullptr, "UnoGridColumnFacade::dispose: already disposed!" ); + + m_xGridColumn->removeGridColumnListener( m_pChangeMultiplexer.get() ); + m_pChangeMultiplexer->dispose(); + m_pChangeMultiplexer.clear(); + m_xGridColumn.clear(); + m_pOwner = nullptr; + } + + + void UnoGridColumnFacade::impl_updateDataColumnIndex_nothrow() + { + m_nDataColumnIndex = -1; + ENSURE_OR_RETURN_VOID( m_xGridColumn.is(), "UnoGridColumnFacade: already disposed!" ); + try + { + m_nDataColumnIndex = m_xGridColumn->getDataColumnIndex(); + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION("svtools.uno"); + } + } + + + void UnoGridColumnFacade::dataColumnIndexChanged() + { + DBG_TESTSOLARMUTEX(); + impl_updateDataColumnIndex_nothrow(); + if ( m_pOwner != nullptr ) + m_pOwner->notifyAllDataChanged(); + } + + + void UnoGridColumnFacade::columnChanged( ColumnAttributeGroup const i_attributeGroup ) + { + DBG_TESTSOLARMUTEX(); + if ( m_pOwner != nullptr ) + m_pOwner->notifyColumnChange( m_pOwner->getColumnPos( *this ), i_attributeGroup ); + } + + + OUString UnoGridColumnFacade::getName() const + { + OUString sName; + ENSURE_OR_RETURN( m_xGridColumn.is(), "UnoGridColumnFacade: already disposed!", sName ); + try + { + sName = m_xGridColumn->getTitle(); + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION("svtools.uno"); + } + return sName; + } + + + OUString UnoGridColumnFacade::getHelpText() const + { + OUString sHelpText; + ENSURE_OR_RETURN( m_xGridColumn.is(), "UnoGridColumnFacade: already disposed!", sHelpText ); + try + { + sHelpText = m_xGridColumn->getHelpText(); + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION("svtools.uno"); + } + return sHelpText; + } + + + bool UnoGridColumnFacade::isResizable() const + { + ENSURE_OR_RETURN( m_xGridColumn.is(), "UnoGridColumnFacade: already disposed!", false ); + return lcl_get( m_xGridColumn, &XGridColumn::getResizeable ); + } + + + sal_Int32 UnoGridColumnFacade::getFlexibility() const + { + ENSURE_OR_RETURN( m_xGridColumn.is(), "UnoGridColumnFacade: already disposed!", 1 ); + return lcl_get( m_xGridColumn, &XGridColumn::getFlexibility ); + } + + + TableMetrics UnoGridColumnFacade::getWidth() const + { + ENSURE_OR_RETURN( m_xGridColumn.is(), "UnoGridColumnFacade: already disposed!", 0 ); + return lcl_get( m_xGridColumn, &XGridColumn::getColumnWidth ); + } + + + void UnoGridColumnFacade::setWidth( TableMetrics _nWidth ) + { + ENSURE_OR_RETURN_VOID( m_xGridColumn.is(), "UnoGridColumnFacade: already disposed!" ); + lcl_set( m_xGridColumn, &XGridColumn::setColumnWidth, _nWidth ); + } + + + TableMetrics UnoGridColumnFacade::getMinWidth() const + { + ENSURE_OR_RETURN( m_xGridColumn.is(), "UnoGridColumnFacade: already disposed!", 0 ); + return lcl_get( m_xGridColumn, &XGridColumn::getMinWidth ); + } + + + TableMetrics UnoGridColumnFacade::getMaxWidth() const + { + ENSURE_OR_RETURN( m_xGridColumn.is(), "UnoGridColumnFacade: already disposed!", 0 ); + return lcl_get( m_xGridColumn, &XGridColumn::getMaxWidth ); + } + + + css::style::HorizontalAlignment UnoGridColumnFacade::getHorizontalAlign() + { + ENSURE_OR_RETURN( m_xGridColumn.is(), "UnoGridColumnFacade: already disposed!", HorizontalAlignment_LEFT ); + return lcl_get( m_xGridColumn, &XGridColumn::getHorizontalAlign ); + } + + +} // svt::table + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/uno/unogridcolumnfacade.hxx b/svtools/source/uno/unogridcolumnfacade.hxx new file mode 100644 index 000000000..672397276 --- /dev/null +++ b/svtools/source/uno/unogridcolumnfacade.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 . + */ + +#pragma once + +#include <table/tablemodel.hxx> + +#include <com/sun/star/awt/grid/XGridColumn.hpp> +#include <com/sun/star/style/HorizontalAlignment.hpp> + +#include <rtl/ref.hxx> + + +namespace svt::table +{ + + + //= UnoGridColumnFacade + + class ColumnChangeMultiplexer; + class UnoControlTableModel; + class UnoGridColumnFacade :public IColumnModel + { + public: + UnoGridColumnFacade( + UnoControlTableModel const & i_owner, + css::uno::Reference< css::awt::grid::XGridColumn > const & i_gridColumn + ); + virtual ~UnoGridColumnFacade() override; + UnoGridColumnFacade(const UnoGridColumnFacade&) = delete; + UnoGridColumnFacade& operator=(const UnoGridColumnFacade&) = delete; + + // IColumnModel overridables + virtual OUString getName() const override; + virtual OUString getHelpText() const override; + virtual bool isResizable() const override; + virtual sal_Int32 getFlexibility() const override; + virtual TableMetrics getWidth() const override; + virtual void setWidth( TableMetrics _nWidth ) override; + virtual TableMetrics getMinWidth() const override; + virtual TableMetrics getMaxWidth() const override; + virtual css::style::HorizontalAlignment getHorizontalAlign() override; + + /** disposes the column wrapper + + Note that the XGridColumn which is wrapped by the instance is <strong>not</strong> disposed, as we + do not own it. + */ + void dispose(); + + sal_Int32 + getDataColumnIndex() const { return m_nDataColumnIndex; } + + // callbacks for the XGridColumnListener + void columnChanged( ColumnAttributeGroup const i_attributeGroup ); + void dataColumnIndexChanged(); + + private: + void impl_updateDataColumnIndex_nothrow(); + + private: + UnoControlTableModel const * m_pOwner; + sal_Int32 m_nDataColumnIndex; + css::uno::Reference< css::awt::grid::XGridColumn > m_xGridColumn; + ::rtl::Reference< ColumnChangeMultiplexer > m_pChangeMultiplexer; + }; + + +} // svt::table + + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/uno/unoiface.cxx b/svtools/source/uno/unoiface.cxx new file mode 100644 index 000000000..7f10167cf --- /dev/null +++ b/svtools/source/uno/unoiface.cxx @@ -0,0 +1,512 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <tools/debug.hxx> +#include <vcl/svapp.hxx> +#include <svl/zforlist.hxx> +#include <svmedit.hxx> +#include <unoiface.hxx> +#include <com/sun/star/awt/LineEndFormat.hpp> +#include <cppuhelper/queryinterface.hxx> +#include <cppuhelper/typeprovider.hxx> +#include <toolkit/helper/convert.hxx> +#include <toolkit/helper/property.hxx> +#include <svl/numuno.hxx> +#include <svtools/calendar.hxx> +#include "svtxgridcontrol.hxx" +#include <table/tablecontrol.hxx> + +namespace +{ + void lcl_setWinBits( vcl::Window* _pWindow, WinBits _nBits, bool _bSet ) + { + WinBits nStyle = _pWindow->GetStyle(); + if ( _bSet ) + nStyle |= _nBits; + else + nStyle &= ~_nBits; + _pWindow->SetStyle( nStyle ); + } +} + + +// help function for the toolkit... + + +extern "C" { + +SAL_DLLPUBLIC_EXPORT vcl::Window* CreateWindow( VCLXWindow** ppNewComp, const css::awt::WindowDescriptor* pDescriptor, vcl::Window* pParent, WinBits nWinBits ) +{ + vcl::Window* pWindow = nullptr; + OUString aServiceName( pDescriptor->WindowServiceName ); + if ( aServiceName.equalsIgnoreAsciiCase( "MultiLineEdit" ) ) + { + if ( pParent ) + { + pWindow = VclPtr<MultiLineEdit>::Create( pParent, nWinBits|WB_IGNORETAB); + static_cast< MultiLineEdit* >( pWindow )->DisableSelectionOnFocus(); + *ppNewComp = new VCLXMultiLineEdit; + } + else + { + *ppNewComp = nullptr; + return nullptr; + } + } + else if (aServiceName.equalsIgnoreAsciiCase("datefield") ) + { + pWindow = VclPtr<CalendarField>::Create( pParent, nWinBits); + static_cast<CalendarField*>(pWindow)->EnableToday(); + static_cast<CalendarField*>(pWindow)->EnableNone(); + static_cast<CalendarField*>(pWindow)->EnableEmptyFieldValue( true ); + SVTXDateField * newComp = new SVTXDateField; + *ppNewComp = newComp; + newComp->SetFormatter( static_cast<FormatterBase*>(static_cast<DateField*>(pWindow)) ); + } + else if ( aServiceName.equalsIgnoreAsciiCase( "Grid" ) ) + { + if ( pParent ) + { + pWindow = VclPtr< ::svt::table::TableControl>::Create(pParent, nWinBits); + *ppNewComp = new SVTXGridControl; + } + else + { + *ppNewComp = nullptr; + return nullptr; + } + } + return pWindow; +} + +} // extern "C" + + + +VCLXMultiLineEdit::VCLXMultiLineEdit() + :maTextListeners( *this ) + ,meLineEndType( LINEEND_LF ) // default behavior before introducing this property: LF (unix-like) +{ +} + +VCLXMultiLineEdit::~VCLXMultiLineEdit() +{ +} + +css::uno::Any VCLXMultiLineEdit::queryInterface( const css::uno::Type & rType ) +{ + css::uno::Any aRet = ::cppu::queryInterface( rType, + static_cast< css::awt::XTextComponent* >(this), + static_cast< css::awt::XTextArea* >(this), + static_cast< css::awt::XTextLayoutConstrains* >(this), + static_cast< css::lang::XTypeProvider* >(this) ); + return (aRet.hasValue() ? aRet : VCLXWindow::queryInterface( rType )); +} + +IMPL_IMPLEMENTATION_ID( VCLXMultiLineEdit ) + +// css::lang::XTypeProvider +css::uno::Sequence< css::uno::Type > VCLXMultiLineEdit::getTypes() +{ + static const ::cppu::OTypeCollection aTypeList( + cppu::UnoType<css::lang::XTypeProvider>::get(), + cppu::UnoType<css::awt::XTextComponent>::get(), + cppu::UnoType<css::awt::XTextArea>::get(), + cppu::UnoType<css::awt::XTextLayoutConstrains>::get(), + VCLXWindow::getTypes() + ); + return aTypeList.getTypes(); +} + +void VCLXMultiLineEdit::addTextListener( const css::uno::Reference< css::awt::XTextListener > & l ) +{ + maTextListeners.addInterface( l ); +} + +void VCLXMultiLineEdit::removeTextListener( const css::uno::Reference< css::awt::XTextListener > & l ) +{ + maTextListeners.removeInterface( l ); +} + +void VCLXMultiLineEdit::setText( const OUString& aText ) +{ + SolarMutexGuard aGuard; + + VclPtr< MultiLineEdit > pEdit = GetAs< MultiLineEdit >(); + if ( pEdit ) + { + pEdit->SetText( aText ); + + // #107218# Call same listeners like VCL would do after user interaction + SetSynthesizingVCLEvent( true ); + pEdit->SetModifyFlag(); + pEdit->Modify(); + SetSynthesizingVCLEvent( false ); + } +} + +void VCLXMultiLineEdit::insertText( const css::awt::Selection& rSel, const OUString& aText ) +{ + SolarMutexGuard aGuard; + + VclPtr< MultiLineEdit > pEdit = GetAs< MultiLineEdit >(); + if ( pEdit ) + { + setSelection( rSel ); + pEdit->ReplaceSelected( aText ); + } +} + +OUString VCLXMultiLineEdit::getText() +{ + SolarMutexGuard aGuard; + + OUString aText; + VclPtr< MultiLineEdit > pEdit = GetAs< MultiLineEdit >(); + if ( pEdit ) + aText = pEdit->GetText( meLineEndType ); + return aText; +} + +OUString VCLXMultiLineEdit::getSelectedText() +{ + SolarMutexGuard aGuard; + + OUString aText; + VclPtr< MultiLineEdit > pMultiLineEdit = GetAs< MultiLineEdit >(); + if ( pMultiLineEdit) + aText = pMultiLineEdit->GetSelected( meLineEndType ); + return aText; + +} + +void VCLXMultiLineEdit::setSelection( const css::awt::Selection& aSelection ) +{ + SolarMutexGuard aGuard; + + VclPtr< MultiLineEdit > pMultiLineEdit = GetAs< MultiLineEdit >(); + if ( pMultiLineEdit ) + { + pMultiLineEdit->SetSelection( Selection( aSelection.Min, aSelection.Max ) ); + } +} + +css::awt::Selection VCLXMultiLineEdit::getSelection() +{ + SolarMutexGuard aGuard; + + css::awt::Selection aSel; + VclPtr< MultiLineEdit > pMultiLineEdit = GetAs< MultiLineEdit >(); + if ( pMultiLineEdit ) + { + aSel.Min = pMultiLineEdit->GetSelection().Min(); + aSel.Max = pMultiLineEdit->GetSelection().Max(); + } + return aSel; +} + +sal_Bool VCLXMultiLineEdit::isEditable() +{ + SolarMutexGuard aGuard; + + VclPtr< MultiLineEdit > pMultiLineEdit = GetAs< MultiLineEdit >(); + return pMultiLineEdit && !pMultiLineEdit->IsReadOnly() && pMultiLineEdit->IsEnabled(); +} + +void VCLXMultiLineEdit::setEditable( sal_Bool bEditable ) +{ + SolarMutexGuard aGuard; + + VclPtr< MultiLineEdit > pMultiLineEdit = GetAs< MultiLineEdit >(); + if ( pMultiLineEdit ) + pMultiLineEdit->SetReadOnly( !bEditable ); +} + +void VCLXMultiLineEdit::setMaxTextLen( sal_Int16 nLen ) +{ + SolarMutexGuard aGuard; + + VclPtr< MultiLineEdit > pMultiLineEdit = GetAs< MultiLineEdit >(); + if ( pMultiLineEdit ) + pMultiLineEdit->SetMaxTextLen( nLen ); +} + +sal_Int16 VCLXMultiLineEdit::getMaxTextLen() +{ + SolarMutexGuard aGuard; + + VclPtr< MultiLineEdit > pMultiLineEdit = GetAs< MultiLineEdit >(); + return pMultiLineEdit ? static_cast<sal_Int16>(pMultiLineEdit->GetMaxTextLen()) : sal_Int16(0); +} + +OUString VCLXMultiLineEdit::getTextLines() +{ + SolarMutexGuard aGuard; + + OUString aText; + VclPtr< MultiLineEdit > pEdit = GetAs< MultiLineEdit >(); + if ( pEdit ) + aText = pEdit->GetTextLines( meLineEndType ); + return aText; +} + +css::awt::Size VCLXMultiLineEdit::getMinimumSize() +{ + SolarMutexGuard aGuard; + + css::awt::Size aSz; + VclPtr< MultiLineEdit > pEdit = GetAs< MultiLineEdit >(); + if ( pEdit ) + aSz = AWTSize(pEdit->CalcMinimumSize()); + return aSz; +} + +css::awt::Size VCLXMultiLineEdit::getPreferredSize() +{ + return getMinimumSize(); +} + +css::awt::Size VCLXMultiLineEdit::calcAdjustedSize( const css::awt::Size& rNewSize ) +{ + SolarMutexGuard aGuard; + + css::awt::Size aSz = rNewSize; + VclPtr< MultiLineEdit > pEdit = GetAs< MultiLineEdit >(); + if ( pEdit ) + aSz = AWTSize(pEdit->CalcAdjustedSize( VCLSize(rNewSize ))); + return aSz; +} + +css::awt::Size VCLXMultiLineEdit::getMinimumSize( sal_Int16 nCols, sal_Int16 nLines ) +{ + SolarMutexGuard aGuard; + + css::awt::Size aSz; + VclPtr< MultiLineEdit > pEdit = GetAs< MultiLineEdit >(); + if ( pEdit ) + aSz = AWTSize(pEdit->CalcBlockSize( nCols, nLines )); + return aSz; +} + +void VCLXMultiLineEdit::getColumnsAndLines( sal_Int16& nCols, sal_Int16& nLines ) +{ + SolarMutexGuard aGuard; + + nCols = nLines = 0; + VclPtr< MultiLineEdit > pEdit = GetAs< MultiLineEdit >(); + if ( pEdit ) + { + sal_uInt16 nC, nL; + pEdit->GetMaxVisColumnsAndLines( nC, nL ); + nCols = nC; + nLines = nL; + } +} + +void VCLXMultiLineEdit::ProcessWindowEvent( const VclWindowEvent& rVclWindowEvent ) +{ + switch ( rVclWindowEvent.GetId() ) + { + case VclEventId::EditModify: + { + if ( maTextListeners.getLength() ) + { + css::awt::TextEvent aEvent; + aEvent.Source = static_cast<cppu::OWeakObject*>(this); + maTextListeners.textChanged( aEvent ); + } + } + break; + default: + { + VCLXWindow::ProcessWindowEvent( rVclWindowEvent ); + } + break; + } +} + +void VCLXMultiLineEdit::setProperty( const OUString& PropertyName, const css::uno::Any& Value) +{ + SolarMutexGuard aGuard; + + VclPtr< MultiLineEdit > pMultiLineEdit = GetAs< MultiLineEdit >(); + if ( !pMultiLineEdit ) + return; + + sal_uInt16 nPropType = GetPropertyId( PropertyName ); + switch ( nPropType ) + { + case BASEPROPERTY_LINE_END_FORMAT: + { + sal_Int16 nLineEndType = css::awt::LineEndFormat::LINE_FEED; + OSL_VERIFY( Value >>= nLineEndType ); + switch ( nLineEndType ) + { + case css::awt::LineEndFormat::CARRIAGE_RETURN: meLineEndType = LINEEND_CR; break; + case css::awt::LineEndFormat::LINE_FEED: meLineEndType = LINEEND_LF; break; + case css::awt::LineEndFormat::CARRIAGE_RETURN_LINE_FEED: meLineEndType = LINEEND_CRLF; break; + default: OSL_FAIL( "VCLXMultiLineEdit::setProperty: invalid line end value!" ); break; + } + } + break; + + case BASEPROPERTY_READONLY: + { + bool b; + if ( Value >>= b ) + pMultiLineEdit->SetReadOnly( b ); + } + break; + case BASEPROPERTY_MAXTEXTLEN: + { + sal_Int16 n = sal_Int16(); + if ( Value >>= n ) + pMultiLineEdit->SetMaxTextLen( n ); + } + break; + case BASEPROPERTY_HIDEINACTIVESELECTION: + { + bool b; + if ( Value >>= b ) + { + pMultiLineEdit->EnableFocusSelectionHide( b ); + lcl_setWinBits( pMultiLineEdit, WB_NOHIDESELECTION, !b ); + } + } + break; + default: + { + VCLXWindow::setProperty( PropertyName, Value ); + } + } +} + +css::uno::Any VCLXMultiLineEdit::getProperty( const OUString& PropertyName ) +{ + SolarMutexGuard aGuard; + + css::uno::Any aProp; + VclPtr< MultiLineEdit > pMultiLineEdit = GetAs< MultiLineEdit >(); + if ( pMultiLineEdit ) + { + sal_uInt16 nPropType = GetPropertyId( PropertyName ); + switch ( nPropType ) + { + case BASEPROPERTY_LINE_END_FORMAT: + { + sal_Int16 nLineEndType = css::awt::LineEndFormat::LINE_FEED; + switch ( meLineEndType ) + { + case LINEEND_CR: nLineEndType = css::awt::LineEndFormat::CARRIAGE_RETURN; break; + case LINEEND_LF: nLineEndType = css::awt::LineEndFormat::LINE_FEED; break; + case LINEEND_CRLF: nLineEndType = css::awt::LineEndFormat::CARRIAGE_RETURN_LINE_FEED; break; + default: OSL_FAIL( "VCLXMultiLineEdit::getProperty: invalid line end value!" ); break; + } + aProp <<= nLineEndType; + } + break; + + case BASEPROPERTY_READONLY: + { + aProp <<= pMultiLineEdit->IsReadOnly(); + } + break; + case BASEPROPERTY_MAXTEXTLEN: + { + aProp <<= static_cast<sal_Int16>(pMultiLineEdit->GetMaxTextLen()); + } + break; + default: + { + aProp = VCLXWindow::getProperty( PropertyName ); + } + } + } + return aProp; +} + +void SAL_CALL VCLXMultiLineEdit::setFocus( ) +{ + SolarMutexGuard aGuard; + + // don't grab the focus if we already have it. Reason is that the only thing which the edit + // does is forwarding the focus to its text window. This text window then does a "select all". + // So if the text window already has the focus, and we give the focus to the multi line + // edit, then all which happens is that everything is selected. + // #i27072# + if ( GetWindow() && !GetWindow()->HasChildPathFocus() ) + GetWindow()->GrabFocus(); +} + +void VCLXMultiLineEdit::ImplGetPropertyIds( std::vector< sal_uInt16 > &rIds ) +{ + PushPropertyIds( rIds, + // FIXME: elide duplication ? + BASEPROPERTY_LINE_END_FORMAT, + BASEPROPERTY_READONLY, + BASEPROPERTY_MAXTEXTLEN, + BASEPROPERTY_HIDEINACTIVESELECTION, + 0); + VCLXWindow::ImplGetPropertyIds( rIds, true ); +} + +SVTXDateField::SVTXDateField() + :VCLXDateField() +{ +} + +SVTXDateField::~SVTXDateField() +{ +} + +void SAL_CALL SVTXDateField::setProperty( const OUString& PropertyName, const css::uno::Any& Value ) +{ + VCLXDateField::setProperty( PropertyName, Value ); + + // some properties need to be forwarded to the sub edit, too + SolarMutexGuard g; + VclPtr< Edit > pSubEdit = GetWindow() ? static_cast< Edit* >( GetWindow().get() )->GetSubEdit() : nullptr; + if ( !pSubEdit ) + return; + + switch ( GetPropertyId( PropertyName ) ) + { + case BASEPROPERTY_TEXTLINECOLOR: + if ( !Value.hasValue() ) + pSubEdit->SetTextLineColor(); + else + { + sal_Int32 nColor = 0; + if ( Value >>= nColor ) + pSubEdit->SetTextLineColor( Color( nColor ) ); + } + break; + } +} + +void SVTXDateField::ImplGetPropertyIds( std::vector< sal_uInt16 > &rIds ) +{ + PushPropertyIds( rIds, + BASEPROPERTY_TEXTLINECOLOR, + 0); + VCLXDateField::ImplGetPropertyIds( rIds ); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/uno/unoimap.cxx b/svtools/source/uno/unoimap.cxx new file mode 100644 index 000000000..df3537683 --- /dev/null +++ b/svtools/source/uno/unoimap.cxx @@ -0,0 +1,723 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 <com/sun/star/container/XIndexContainer.hpp> +#include <com/sun/star/lang/IndexOutOfBoundsException.hpp> +#include <com/sun/star/lang/XServiceInfo.hpp> +#include <com/sun/star/document/XEventsSupplier.hpp> +#include <com/sun/star/lang/XUnoTunnel.hpp> +#include <com/sun/star/beans/XPropertySet.hpp> +#include <com/sun/star/awt/Rectangle.hpp> +#include <com/sun/star/awt/Point.hpp> +#include <com/sun/star/drawing/PointSequence.hpp> +#include <comphelper/servicehelper.hxx> +#include <comphelper/propertysethelper.hxx> +#include <comphelper/propertysetinfo.hxx> +#include <cppuhelper/weakagg.hxx> +#include <cppuhelper/implbase.hxx> +#include <cppuhelper/supportsservice.hxx> +#include <algorithm> +#include <osl/diagnose.h> +#include <rtl/ref.hxx> +#include <svtools/unoevent.hxx> +#include <svtools/unoimap.hxx> +#include <vcl/imap.hxx> +#include <vcl/imapcirc.hxx> +#include <vcl/imaprect.hxx> +#include <vcl/imappoly.hxx> + +using namespace comphelper; +using namespace cppu; +using namespace com::sun::star; +using namespace css::uno; +using namespace css::lang; +using namespace css::container; +using namespace css::beans; +using namespace css::document; +using namespace css::drawing; + +const sal_Int32 HANDLE_URL = 1; +const sal_Int32 HANDLE_DESCRIPTION = 2; +const sal_Int32 HANDLE_TARGET = 3; +const sal_Int32 HANDLE_NAME = 4; +const sal_Int32 HANDLE_ISACTIVE = 5; +const sal_Int32 HANDLE_POLYGON = 6; +const sal_Int32 HANDLE_CENTER = 7; +const sal_Int32 HANDLE_RADIUS = 8; +const sal_Int32 HANDLE_BOUNDARY = 9; +const sal_Int32 HANDLE_TITLE = 10; + +namespace { + +class SvUnoImageMapObject : public OWeakAggObject, + public XEventsSupplier, + public XServiceInfo, + public PropertySetHelper, + public XTypeProvider, + public XUnoTunnel +{ +public: + SvUnoImageMapObject( sal_uInt16 nType, const SvEventDescription* pSupportedMacroItems ); + SvUnoImageMapObject( const IMapObject& rMapObject, const SvEventDescription* pSupportedMacroItems ); + + UNO3_GETIMPLEMENTATION_DECL( SvUnoImageMapObject ) + + std::unique_ptr<IMapObject> createIMapObject() const; + + rtl::Reference<SvMacroTableEventDescriptor> mxEvents; + + // overridden helpers from PropertySetHelper + virtual void _setPropertyValues( const PropertyMapEntry** ppEntries, const Any* pValues ) override; + virtual void _getPropertyValues( const PropertyMapEntry** ppEntries, Any* pValue ) override; + + // XInterface + virtual Any SAL_CALL queryAggregation( const Type & rType ) override; + virtual Any SAL_CALL queryInterface( const Type & rType ) override; + virtual void SAL_CALL acquire() throw() override; + virtual void SAL_CALL release() throw() override; + + // XTypeProvider + virtual Sequence< Type > SAL_CALL getTypes( ) override; + virtual Sequence< sal_Int8 > SAL_CALL getImplementationId( ) override; + + // XEventsSupplier + virtual Reference< css::container::XNameReplace > SAL_CALL getEvents( ) override; + + // XServiceInfo + virtual OUString SAL_CALL getImplementationName( ) override; + virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) override; + virtual Sequence< OUString > SAL_CALL getSupportedServiceNames( ) override; + +private: + static rtl::Reference<PropertySetInfo> createPropertySetInfo( sal_uInt16 nType ); + + + sal_uInt16 mnType; + + OUString maURL; + OUString maAltText; + OUString maDesc; + OUString maTarget; + OUString maName; + bool mbIsActive; + awt::Rectangle maBoundary; + awt::Point maCenter; + sal_Int32 mnRadius; + PointSequence maPolygon; +}; + +} + +UNO3_GETIMPLEMENTATION_IMPL( SvUnoImageMapObject ); + +rtl::Reference<PropertySetInfo> SvUnoImageMapObject::createPropertySetInfo( sal_uInt16 nType ) +{ + switch( nType ) + { + case IMAP_OBJ_POLYGON: + { + static PropertyMapEntry const aPolygonObj_Impl[] = + { + { OUString("URL"), HANDLE_URL, cppu::UnoType<OUString>::get(), 0, 0 }, + { OUString("Title"), HANDLE_TITLE, cppu::UnoType<OUString>::get(), 0, 0 }, + { OUString("Description"), HANDLE_DESCRIPTION, cppu::UnoType<OUString>::get(), 0, 0 }, + { OUString("Target"), HANDLE_TARGET, cppu::UnoType<OUString>::get(), 0, 0 }, + { OUString("Name"), HANDLE_NAME, cppu::UnoType<OUString>::get(), 0, 0 }, + { OUString("IsActive"), HANDLE_ISACTIVE, cppu::UnoType<bool>::get(), 0, 0 }, + { OUString("Polygon"), HANDLE_POLYGON, cppu::UnoType<PointSequence>::get(), 0, 0 }, + { OUString(), 0, css::uno::Type(), 0, 0 } + }; + + return rtl::Reference<PropertySetInfo>(new PropertySetInfo( aPolygonObj_Impl )); + } + case IMAP_OBJ_CIRCLE: + { + static PropertyMapEntry const aCircleObj_Impl[] = + { + { OUString("URL"), HANDLE_URL, cppu::UnoType<OUString>::get(), 0, 0 }, + { OUString("Title"), HANDLE_TITLE, cppu::UnoType<OUString>::get(), 0, 0 }, + { OUString("Description"), HANDLE_DESCRIPTION, cppu::UnoType<OUString>::get(), 0, 0 }, + { OUString("Target"), HANDLE_TARGET, cppu::UnoType<OUString>::get(), 0, 0 }, + { OUString("Name"), HANDLE_NAME, cppu::UnoType<OUString>::get(), 0, 0 }, + { OUString("IsActive"), HANDLE_ISACTIVE, cppu::UnoType<bool>::get(), 0, 0 }, + { OUString("Center"), HANDLE_CENTER, cppu::UnoType<awt::Point>::get(), 0, 0 }, + { OUString("Radius"), HANDLE_RADIUS, cppu::UnoType<sal_Int32>::get(), 0, 0 }, + { OUString(), 0, css::uno::Type(), 0, 0 } + }; + + return rtl::Reference<PropertySetInfo>(new PropertySetInfo( aCircleObj_Impl )); + } + case IMAP_OBJ_RECTANGLE: + default: + { + static PropertyMapEntry const aRectangleObj_Impl[] = + { + { OUString("URL"), HANDLE_URL, cppu::UnoType<OUString>::get(), 0, 0 }, + { OUString("Title"), HANDLE_TITLE, cppu::UnoType<OUString>::get(), 0, 0 }, + { OUString("Description"), HANDLE_DESCRIPTION, cppu::UnoType<OUString>::get(), 0, 0 }, + { OUString("Target"), HANDLE_TARGET, cppu::UnoType<OUString>::get(), 0, 0 }, + { OUString("Name"), HANDLE_NAME, cppu::UnoType<OUString>::get(), 0, 0 }, + { OUString("IsActive"), HANDLE_ISACTIVE, cppu::UnoType<bool>::get(), 0, 0 }, + { OUString("Boundary"), HANDLE_BOUNDARY, cppu::UnoType<awt::Rectangle>::get(), 0, 0 }, + { OUString(), 0, css::uno::Type(), 0, 0 } + }; + + return rtl::Reference<PropertySetInfo>(new PropertySetInfo( aRectangleObj_Impl )); + } + } +} + +SvUnoImageMapObject::SvUnoImageMapObject( sal_uInt16 nType, const SvEventDescription* pSupportedMacroItems ) +: PropertySetHelper( createPropertySetInfo( nType ) ), + mnType( nType ) +, mbIsActive( true ) +, mnRadius( 0 ) +{ + mxEvents = new SvMacroTableEventDescriptor( pSupportedMacroItems ); +} + +SvUnoImageMapObject::SvUnoImageMapObject( const IMapObject& rMapObject, const SvEventDescription* pSupportedMacroItems ) +: PropertySetHelper( createPropertySetInfo( rMapObject.GetType() ) ), + mnType( rMapObject.GetType() ) +, mbIsActive( true ) +, mnRadius( 0 ) +{ + maURL = rMapObject.GetURL(); + maAltText = rMapObject.GetAltText(); + maDesc = rMapObject.GetDesc(); + maTarget = rMapObject.GetTarget(); + maName = rMapObject.GetName(); + mbIsActive = rMapObject.IsActive(); + + switch( mnType ) + { + case IMAP_OBJ_RECTANGLE: + { + const tools::Rectangle aRect( static_cast<const IMapRectangleObject*>(&rMapObject)->GetRectangle(false) ); + maBoundary.X = aRect.Left(); + maBoundary.Y = aRect.Top(); + maBoundary.Width = aRect.GetWidth(); + maBoundary.Height = aRect.GetHeight(); + } + break; + case IMAP_OBJ_CIRCLE: + { + mnRadius = static_cast<sal_Int32>(static_cast<const IMapCircleObject*>(&rMapObject)->GetRadius(false)); + const Point aPoint( static_cast<const IMapCircleObject*>(&rMapObject)->GetCenter(false) ); + + maCenter.X = aPoint.X(); + maCenter.Y = aPoint.Y(); + } + break; + case IMAP_OBJ_POLYGON: + default: + { + const tools::Polygon aPoly( static_cast<const IMapPolygonObject*>(&rMapObject)->GetPolygon(false) ); + + const sal_uInt16 nCount = aPoly.GetSize(); + maPolygon.realloc( nCount ); + awt::Point* pPoints = maPolygon.getArray(); + + for( sal_uInt16 nPoint = 0; nPoint < nCount; nPoint++ ) + { + const Point& rPoint = aPoly.GetPoint( nPoint ); + pPoints->X = rPoint.X(); + pPoints->Y = rPoint.Y(); + + pPoints++; + } + } + } + + mxEvents = new SvMacroTableEventDescriptor( rMapObject.GetMacroTable(), pSupportedMacroItems ); +} + +std::unique_ptr<IMapObject> SvUnoImageMapObject::createIMapObject() const +{ + const OUString aURL( maURL ); + const OUString aAltText( maAltText ); + const OUString aDesc( maDesc ); + const OUString aTarget( maTarget ); + const OUString aName( maName ); + + std::unique_ptr<IMapObject> pNewIMapObject; + + switch( mnType ) + { + case IMAP_OBJ_RECTANGLE: + { + const tools::Rectangle aRect( maBoundary.X, maBoundary.Y, maBoundary.X + maBoundary.Width - 1, maBoundary.Y + maBoundary.Height - 1 ); + pNewIMapObject.reset(new IMapRectangleObject( aRect, aURL, aAltText, aDesc, aTarget, aName, mbIsActive, false )); + } + break; + + case IMAP_OBJ_CIRCLE: + { + const Point aCenter( maCenter.X, maCenter.Y ); + pNewIMapObject.reset(new IMapCircleObject( aCenter, mnRadius, aURL, aAltText, aDesc, aTarget, aName, mbIsActive, false )); + } + break; + + case IMAP_OBJ_POLYGON: + default: + { + const sal_uInt16 nCount = static_cast<sal_uInt16>(maPolygon.getLength()); + + tools::Polygon aPoly( nCount ); + for( sal_uInt16 nPoint = 0; nPoint < nCount; nPoint++ ) + { + Point aPoint( maPolygon[nPoint].X, maPolygon[nPoint].Y ); + aPoly.SetPoint( aPoint, nPoint ); + } + + aPoly.Optimize( PolyOptimizeFlags::CLOSE ); + pNewIMapObject.reset(new IMapPolygonObject( aPoly, aURL, aAltText, aDesc, aTarget, aName, mbIsActive, false )); + } + break; + } + + SvxMacroTableDtor aMacroTable; + mxEvents->copyMacrosIntoTable(aMacroTable); + pNewIMapObject->SetMacroTable( aMacroTable ); + + return pNewIMapObject; +} + +// XInterface + +Any SAL_CALL SvUnoImageMapObject::queryInterface( const Type & rType ) +{ + return OWeakAggObject::queryInterface( rType ); +} + +Any SAL_CALL SvUnoImageMapObject::queryAggregation( const Type & rType ) +{ + Any aAny; + + if( rType == cppu::UnoType<XServiceInfo>::get()) + aAny <<= Reference< XServiceInfo >(this); + else if( rType == cppu::UnoType<XTypeProvider>::get()) + aAny <<= Reference< XTypeProvider >(this); + else if( rType == cppu::UnoType<XPropertySet>::get()) + aAny <<= Reference< XPropertySet >(this); + else if( rType == cppu::UnoType<XEventsSupplier>::get()) + aAny <<= Reference< XEventsSupplier >(this); + else if( rType == cppu::UnoType<XMultiPropertySet>::get()) + aAny <<= Reference< XMultiPropertySet >(this); + else if( rType == cppu::UnoType<XUnoTunnel>::get()) + aAny <<= Reference< XUnoTunnel >(this); + else + aAny = OWeakAggObject::queryAggregation( rType ); + + return aAny; +} + +void SAL_CALL SvUnoImageMapObject::acquire() throw() +{ + OWeakAggObject::acquire(); +} + +void SAL_CALL SvUnoImageMapObject::release() throw() +{ + OWeakAggObject::release(); +} + +uno::Sequence< uno::Type > SAL_CALL SvUnoImageMapObject::getTypes() +{ + static const uno::Sequence< uno::Type > aTypes { + cppu::UnoType<XAggregation>::get(), + cppu::UnoType<XEventsSupplier>::get(), + cppu::UnoType<XServiceInfo>::get(), + cppu::UnoType<XPropertySet>::get(), + cppu::UnoType<XMultiPropertySet>::get(), + cppu::UnoType<XTypeProvider>::get(), + cppu::UnoType<XUnoTunnel>::get() }; + return aTypes; +} + +uno::Sequence< sal_Int8 > SAL_CALL SvUnoImageMapObject::getImplementationId() +{ + return css::uno::Sequence<sal_Int8>(); +} + +// XServiceInfo +sal_Bool SAL_CALL SvUnoImageMapObject::supportsService( const OUString& ServiceName ) +{ + return cppu::supportsService(this, ServiceName); +} + +Sequence< OUString > SAL_CALL SvUnoImageMapObject::getSupportedServiceNames() +{ + Sequence< OUString > aSNS( 2 ); + aSNS.getArray()[0] = "com.sun.star.image.ImageMapObject"; + switch( mnType ) + { + case IMAP_OBJ_POLYGON: + default: + aSNS.getArray()[1] = "com.sun.star.image.ImageMapPolygonObject"; + break; + case IMAP_OBJ_RECTANGLE: + aSNS.getArray()[1] = "com.sun.star.image.ImageMapRectangleObject"; + break; + case IMAP_OBJ_CIRCLE: + aSNS.getArray()[1] = "com.sun.star.image.ImageMapCircleObject"; + break; + } + return aSNS; +} + +OUString SAL_CALL SvUnoImageMapObject::getImplementationName() +{ + switch( mnType ) + { + case IMAP_OBJ_POLYGON: + default: + return "org.openoffice.comp.svt.ImageMapPolygonObject"; + case IMAP_OBJ_CIRCLE: + return "org.openoffice.comp.svt.ImageMapCircleObject"; + case IMAP_OBJ_RECTANGLE: + return "org.openoffice.comp.svt.ImageMapRectangleObject"; + } +} + +// overridden helpers from PropertySetHelper +void SvUnoImageMapObject::_setPropertyValues( const PropertyMapEntry** ppEntries, const Any* pValues ) +{ + bool bOk = false; + + while( *ppEntries ) + { + switch( (*ppEntries)->mnHandle ) + { + case HANDLE_URL: + bOk = *pValues >>= maURL; + break; + case HANDLE_TITLE: + bOk = *pValues >>= maAltText; + break; + case HANDLE_DESCRIPTION: + bOk = *pValues >>= maDesc; + break; + case HANDLE_TARGET: + bOk = *pValues >>= maTarget; + break; + case HANDLE_NAME: + bOk = *pValues >>= maName; + break; + case HANDLE_ISACTIVE: + bOk = *pValues >>= mbIsActive; + break; + case HANDLE_BOUNDARY: + bOk = *pValues >>= maBoundary; + break; + case HANDLE_CENTER: + bOk = *pValues >>= maCenter; + break; + case HANDLE_RADIUS: + bOk = *pValues >>= mnRadius; + break; + case HANDLE_POLYGON: + bOk = *pValues >>= maPolygon; + break; + default: + OSL_FAIL( "SvUnoImageMapObject::_setPropertyValues: unexpected property handle" ); + break; + } + + if( !bOk ) + throw IllegalArgumentException(); + + ppEntries++; + pValues++; + } +} + +void SvUnoImageMapObject::_getPropertyValues( const PropertyMapEntry** ppEntries, Any* pValues ) +{ + while( *ppEntries ) + { + switch( (*ppEntries)->mnHandle ) + { + case HANDLE_URL: + *pValues <<= maURL; + break; + case HANDLE_TITLE: + *pValues <<= maAltText; + break; + case HANDLE_DESCRIPTION: + *pValues <<= maDesc; + break; + case HANDLE_TARGET: + *pValues <<= maTarget; + break; + case HANDLE_NAME: + *pValues <<= maName; + break; + case HANDLE_ISACTIVE: + *pValues <<= mbIsActive; + break; + case HANDLE_BOUNDARY: + *pValues <<= maBoundary; + break; + case HANDLE_CENTER: + *pValues <<= maCenter; + break; + case HANDLE_RADIUS: + *pValues <<= mnRadius; + break; + case HANDLE_POLYGON: + *pValues <<= maPolygon; + break; + default: + OSL_FAIL( "SvUnoImageMapObject::_getPropertyValues: unexpected property handle" ); + break; + } + + ppEntries++; + pValues++; + } +} + + +Reference< XNameReplace > SAL_CALL SvUnoImageMapObject::getEvents() +{ + return mxEvents.get(); +} + +namespace { + +class SvUnoImageMap : public WeakImplHelper< XIndexContainer, XServiceInfo, XUnoTunnel > +{ +public: + explicit SvUnoImageMap(); + SvUnoImageMap( const ImageMap& rMap, const SvEventDescription* pSupportedMacroItems ); + + void fillImageMap( ImageMap& rMap ) const; + /// @throws IllegalArgumentException + static SvUnoImageMapObject* getObject( const Any& aElement ); + + UNO3_GETIMPLEMENTATION_DECL( SvUnoImageMap ) + + // XIndexContainer + virtual void SAL_CALL insertByIndex( sal_Int32 Index, const Any& Element ) override; + virtual void SAL_CALL removeByIndex( sal_Int32 Index ) override; + + // XIndexReplace + virtual void SAL_CALL replaceByIndex( sal_Int32 Index, const Any& Element ) override; + + // XIndexAccess + virtual sal_Int32 SAL_CALL getCount( ) override; + virtual Any SAL_CALL getByIndex( sal_Int32 Index ) override; + + // XElementAccess + virtual Type SAL_CALL getElementType( ) override; + virtual sal_Bool SAL_CALL hasElements( ) override; + + // XSerivceInfo + virtual OUString SAL_CALL getImplementationName( ) override; + virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) override; + virtual Sequence< OUString > SAL_CALL getSupportedServiceNames( ) override; + +private: + OUString maName; + + std::vector< rtl::Reference<SvUnoImageMapObject> > maObjectList; +}; + +} + +UNO3_GETIMPLEMENTATION_IMPL( SvUnoImageMap ); + +SvUnoImageMap::SvUnoImageMap() +{ +} + +SvUnoImageMap::SvUnoImageMap( const ImageMap& rMap, const SvEventDescription* pSupportedMacroItems ) +{ + maName = rMap.GetName(); + + const std::size_t nCount = rMap.GetIMapObjectCount(); + for( std::size_t nPos = 0; nPos < nCount; nPos++ ) + { + IMapObject* pMapObject = rMap.GetIMapObject( nPos ); + rtl::Reference<SvUnoImageMapObject> xUnoObj = new SvUnoImageMapObject( *pMapObject, pSupportedMacroItems ); + maObjectList.push_back( xUnoObj ); + } +} + +SvUnoImageMapObject* SvUnoImageMap::getObject( const Any& aElement ) +{ + Reference< XInterface > xObject; + aElement >>= xObject; + + SvUnoImageMapObject* pObject = comphelper::getUnoTunnelImplementation<SvUnoImageMapObject>( xObject ); + if( nullptr == pObject ) + throw IllegalArgumentException(); + + return pObject; +} + +// XIndexContainer +void SAL_CALL SvUnoImageMap::insertByIndex( sal_Int32 nIndex, const Any& Element ) +{ + SvUnoImageMapObject* pObject = getObject( Element ); + const sal_Int32 nCount = maObjectList.size(); + if( nullptr == pObject || nIndex > nCount ) + throw IndexOutOfBoundsException(); + + if( nIndex == nCount ) + maObjectList.emplace_back(pObject ); + else + { + auto aIter = maObjectList.begin(); + std::advance(aIter, nIndex); + maObjectList.insert( aIter, pObject ); + } +} + +void SAL_CALL SvUnoImageMap::removeByIndex( sal_Int32 nIndex ) +{ + const sal_Int32 nCount = maObjectList.size(); + if( nIndex >= nCount ) + throw IndexOutOfBoundsException(); + + if( nCount - 1 == nIndex ) + { + maObjectList.pop_back(); + } + else + { + auto aIter = maObjectList.begin(); + std::advance(aIter, nIndex); + maObjectList.erase( aIter ); + } +} + +// XIndexReplace +void SAL_CALL SvUnoImageMap::replaceByIndex( sal_Int32 nIndex, const Any& Element ) +{ + SvUnoImageMapObject* pObject = getObject( Element ); + const sal_Int32 nCount = maObjectList.size(); + if( nullptr == pObject || nIndex >= nCount ) + throw IndexOutOfBoundsException(); + + auto aIter = maObjectList.begin(); + std::advance(aIter, nIndex); + *aIter = pObject; +} + +// XIndexAccess +sal_Int32 SAL_CALL SvUnoImageMap::getCount( ) +{ + return maObjectList.size(); +} + +Any SAL_CALL SvUnoImageMap::getByIndex( sal_Int32 nIndex ) +{ + const sal_Int32 nCount = maObjectList.size(); + if( nIndex >= nCount ) + throw IndexOutOfBoundsException(); + + auto aIter = maObjectList.begin(); + std::advance(aIter, nIndex); + + Reference< XPropertySet > xObj( aIter->get() ); + return makeAny( xObj ); +} + +// XElementAccess +Type SAL_CALL SvUnoImageMap::getElementType( ) +{ + return cppu::UnoType<XPropertySet>::get(); +} + +sal_Bool SAL_CALL SvUnoImageMap::hasElements( ) +{ + return (!maObjectList.empty()); +} + +// XSerivceInfo +OUString SAL_CALL SvUnoImageMap::getImplementationName( ) +{ + return "org.openoffice.comp.svt.SvUnoImageMap"; +} + +sal_Bool SAL_CALL SvUnoImageMap::supportsService( const OUString& ServiceName ) +{ + return cppu::supportsService(this, ServiceName); +} + +Sequence< OUString > SAL_CALL SvUnoImageMap::getSupportedServiceNames( ) +{ + return { "com.sun.star.image.ImageMap" }; +} + +void SvUnoImageMap::fillImageMap( ImageMap& rMap ) const +{ + rMap.ClearImageMap(); + + rMap.SetName( maName ); + + for (auto const& elem : maObjectList) + { + std::unique_ptr<IMapObject> pNewMapObject = elem->createIMapObject(); + rMap.InsertIMapObject( std::move(pNewMapObject) ); + } +} + + +// factory helper methods + + +Reference< XInterface > SvUnoImageMapRectangleObject_createInstance( const SvEventDescription* pSupportedMacroItems ) +{ + return static_cast<XWeak*>(new SvUnoImageMapObject( IMAP_OBJ_RECTANGLE, pSupportedMacroItems )); +} + +Reference< XInterface > SvUnoImageMapCircleObject_createInstance( const SvEventDescription* pSupportedMacroItems ) +{ + return static_cast<XWeak*>(new SvUnoImageMapObject( IMAP_OBJ_CIRCLE, pSupportedMacroItems )); +} + +Reference< XInterface > SvUnoImageMapPolygonObject_createInstance( const SvEventDescription* pSupportedMacroItems ) +{ + return static_cast<XWeak*>(new SvUnoImageMapObject( IMAP_OBJ_POLYGON, pSupportedMacroItems )); +} + +Reference< XInterface > SvUnoImageMap_createInstance() +{ + return static_cast<XWeak*>(new SvUnoImageMap); +} + +Reference< XInterface > SvUnoImageMap_createInstance( const ImageMap& rMap, const SvEventDescription* pSupportedMacroItems ) +{ + return static_cast<XWeak*>(new SvUnoImageMap( rMap, pSupportedMacroItems )); +} + +bool SvUnoImageMap_fillImageMap( const Reference< XInterface >& xImageMap, ImageMap& rMap ) +{ + SvUnoImageMap* pUnoImageMap = comphelper::getUnoTunnelImplementation<SvUnoImageMap>( xImageMap ); + if( nullptr == pUnoImageMap ) + return false; + + pUnoImageMap->fillImageMap( rMap ); + return true; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/uno/wizard/unowizard.cxx b/svtools/source/uno/wizard/unowizard.cxx new file mode 100644 index 000000000..ddc87539c --- /dev/null +++ b/svtools/source/uno/wizard/unowizard.cxx @@ -0,0 +1,451 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 "wizardshell.hxx" + +#include <com/sun/star/container/NoSuchElementException.hpp> +#include <com/sun/star/lang/XInitialization.hpp> +#include <com/sun/star/beans/XPropertySetInfo.hpp> +#include <com/sun/star/uno/XComponentContext.hpp> +#include <com/sun/star/ucb/AlreadyInitializedException.hpp> +#include <com/sun/star/ui/dialogs/XWizard.hpp> +#include <com/sun/star/ui/dialogs/XWizardController.hpp> +#include <com/sun/star/ui/dialogs/WizardButton.hpp> +#include <com/sun/star/util/InvalidStateException.hpp> + +#include <comphelper/proparrhlp.hxx> +#include <cppuhelper/implbase.hxx> +#include <svtools/genericunodialog.hxx> +#include <toolkit/helper/vclunohelper.hxx> +#include <tools/diagnose_ex.h> +#include <osl/mutex.hxx> +#include <vcl/svapp.hxx> +#include <tools/urlobj.hxx> + +using namespace ::com::sun::star; +using namespace ::svt::uno; + +namespace { + + using css::uno::Reference; + using css::uno::XInterface; + using css::uno::UNO_QUERY; + using css::uno::Any; + using css::uno::Sequence; + using css::ui::dialogs::XWizard; + using css::beans::XPropertySetInfo; + using css::uno::XComponentContext; + using css::beans::Property; + using css::lang::IllegalArgumentException; + using css::ucb::AlreadyInitializedException; + using css::ui::dialogs::XWizardController; + using css::ui::dialogs::XWizardPage; + using css::container::NoSuchElementException; + using css::util::InvalidStateException; + using css::awt::XWindow; + + namespace WizardButton = css::ui::dialogs::WizardButton; + + WizardButtonFlags lcl_convertWizardButtonToWZB( const sal_Int16 i_nWizardButton ) + { + switch ( i_nWizardButton ) + { + case WizardButton::NONE: return WizardButtonFlags::NONE; + case WizardButton::NEXT: return WizardButtonFlags::NEXT; + case WizardButton::PREVIOUS: return WizardButtonFlags::PREVIOUS; + case WizardButton::FINISH: return WizardButtonFlags::FINISH; + case WizardButton::CANCEL: return WizardButtonFlags::CANCEL; + case WizardButton::HELP: return WizardButtonFlags::HELP; + } + OSL_FAIL( "lcl_convertWizardButtonToWZB: invalid WizardButton constant!" ); + return WizardButtonFlags::NONE; + } + + typedef ::cppu::ImplInheritanceHelper < ::svt::OGenericUnoDialog + , ui::dialogs::XWizard + > Wizard_Base; + class Wizard; + typedef ::comphelper::OPropertyArrayUsageHelper< Wizard > Wizard_PBase; + class Wizard : public Wizard_Base + , public Wizard_PBase + { + public: + explicit Wizard( const css::uno::Reference< css::uno::XComponentContext >& i_rContext ); + + // lang::XServiceInfo + virtual OUString SAL_CALL getImplementationName() override; + virtual css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() override; + + // beans::XPropertySet + virtual css::uno::Reference< beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() override; + virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper() override; + + // OPropertyArrayUsageHelper + virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const override; + + // ui::dialogs::XWizard + virtual OUString SAL_CALL getHelpURL() override; + virtual void SAL_CALL setHelpURL( const OUString& _helpurl ) override; + virtual css::uno::Reference< awt::XWindow > SAL_CALL getDialogWindow() override; + virtual css::uno::Reference< ui::dialogs::XWizardPage > SAL_CALL getCurrentPage( ) override; + virtual void SAL_CALL enableButton( ::sal_Int16 WizardButton, sal_Bool Enable ) override; + virtual void SAL_CALL setDefaultButton( ::sal_Int16 WizardButton ) override; + virtual sal_Bool SAL_CALL travelNext( ) override; + virtual sal_Bool SAL_CALL travelPrevious( ) override; + virtual void SAL_CALL enablePage( ::sal_Int16 PageID, sal_Bool Enable ) override; + virtual void SAL_CALL updateTravelUI( ) override; + virtual sal_Bool SAL_CALL advanceTo( ::sal_Int16 PageId ) override; + virtual sal_Bool SAL_CALL goBackTo( ::sal_Int16 PageId ) override; + virtual void SAL_CALL activatePath( ::sal_Int16 PathIndex, sal_Bool Final ) override; + + // ui::dialogs::XExecutableDialog + virtual void SAL_CALL setTitle( const OUString& aTitle ) override; + virtual ::sal_Int16 SAL_CALL execute( ) override; + + // lang::XInitialization + virtual void SAL_CALL initialize( const css::uno::Sequence< css::uno::Any >& aArguments ) override; + + protected: + virtual ~Wizard() override; + + protected: + virtual std::unique_ptr<weld::DialogController> createDialog(const css::uno::Reference<css::awt::XWindow>& rParent) override; + + private: + css::uno::Sequence< css::uno::Sequence< sal_Int16 > > m_aWizardSteps; + css::uno::Reference< ui::dialogs::XWizardController > m_xController; + OUString m_sHelpURL; + }; + + Wizard::Wizard( const Reference< XComponentContext >& _rxContext ) + :Wizard_Base( _rxContext ) + { + } + + OUString lcl_getHelpURL( const OString& sHelpId ) + { + OUStringBuffer aBuffer; + OUString aTmp( + OStringToOUString( sHelpId, RTL_TEXTENCODING_UTF8 ) ); + INetURLObject aHID( aTmp ); + if ( aHID.GetProtocol() == INetProtocol::NotValid ) + aBuffer.append( INET_HID_SCHEME ); + aBuffer.append( aTmp ); + return aBuffer.makeStringAndClear(); + } + + Wizard::~Wizard() + { + if (m_xDialog) + { + ::osl::MutexGuard aGuard( m_aMutex ); + if (m_xDialog) + { + m_sHelpURL = lcl_getHelpURL(m_xDialog->get_help_id()); + destroyDialog(); + } + } + } + + void lcl_checkPaths( const Sequence< Sequence< sal_Int16 > >& i_rPaths, const Reference< XInterface >& i_rContext ) + { + // need at least one path + if ( !i_rPaths.hasElements() ) + throw IllegalArgumentException( OUString(), i_rContext, 2 ); + + // each path must be of length 1, at least + sal_Int32 i = 0; + for ( const Sequence< sal_Int16 >& rPath : i_rPaths ) + { + if ( !rPath.hasElements() ) + throw IllegalArgumentException( OUString(), i_rContext, 2 ); + + // page IDs must be in ascending order + auto pPageId = std::adjacent_find(rPath.begin(), rPath.end(), std::greater_equal<sal_Int16>()); + if (pPageId != rPath.end()) + { + throw IllegalArgumentException( + "Path " + OUString::number(i) + + ": invalid page ID sequence - each page ID must be greater than the previous one.", + i_rContext, 2 ); + } + ++i; + } + + // if we have one path, that's okay + if ( i_rPaths.getLength() == 1 ) + return; + + // if we have multiple paths, they must start with the same page id + const sal_Int16 nFirstPageId = i_rPaths[0][0]; + if (std::any_of(i_rPaths.begin(), i_rPaths.end(), + [nFirstPageId](const Sequence< sal_Int16 >& rPath) { return rPath[0] != nFirstPageId; })) + throw IllegalArgumentException( + "All paths must start with the same page id.", + i_rContext, 2 ); + } + + void SAL_CALL Wizard::initialize( const Sequence< Any >& i_Arguments ) + { + ::osl::MutexGuard aGuard( m_aMutex ); + if ( m_bInitialized ) + throw AlreadyInitializedException( OUString(), *this ); + + if ( i_Arguments.getLength() != 2 ) + throw IllegalArgumentException( OUString(), *this, -1 ); + + // the second argument must be a XWizardController, for each constructor + m_xController.set( i_Arguments[1], UNO_QUERY ); + if ( !m_xController.is() ) + throw IllegalArgumentException( OUString(), *this, 2 ); + + // the first arg is either a single path (short[]), or multiple paths (short[][]) + Sequence< sal_Int16 > aSinglePath; + i_Arguments[0] >>= aSinglePath; + Sequence< Sequence< sal_Int16 > > aMultiplePaths; + i_Arguments[0] >>= aMultiplePaths; + + if ( !aMultiplePaths.hasElements() ) + { + aMultiplePaths.realloc(1); + aMultiplePaths[0] = aSinglePath; + } + lcl_checkPaths( aMultiplePaths, *this ); + // if we survived this, the paths are valid, and we're done here ... + m_aWizardSteps = aMultiplePaths; + + m_bInitialized = true; + } + + OString lcl_getHelpId( const OUString& _rHelpURL ) + { + INetURLObject aHID( _rHelpURL ); + if ( aHID.GetProtocol() == INetProtocol::Hid ) + return OUStringToOString( aHID.GetURLPath(), RTL_TEXTENCODING_UTF8 ); + else + return OUStringToOString( _rHelpURL, RTL_TEXTENCODING_UTF8 ); + } + + std::unique_ptr<weld::DialogController> Wizard::createDialog(const css::uno::Reference<css::awt::XWindow>& rParent) + { + auto xDialog = std::make_unique<WizardShell>(Application::GetFrameWeld(rParent), m_xController, m_aWizardSteps); + xDialog->set_help_id(lcl_getHelpId(m_sHelpURL)); + xDialog->setTitleBase( m_sTitle ); + return xDialog; + } + + OUString SAL_CALL Wizard::getImplementationName() + { + return "com.sun.star.comp.svtools.uno.Wizard"; + } + + Sequence< OUString > SAL_CALL Wizard::getSupportedServiceNames() + { + return { "com.sun.star.ui.dialogs.Wizard" }; + } + + Reference< XPropertySetInfo > SAL_CALL Wizard::getPropertySetInfo() + { + return createPropertySetInfo( getInfoHelper() ); + } + + ::cppu::IPropertyArrayHelper& SAL_CALL Wizard::getInfoHelper() + { + return *getArrayHelper(); + } + + ::cppu::IPropertyArrayHelper* Wizard::createArrayHelper( ) const + { + Sequence< Property > aProps; + describeProperties( aProps ); + return new ::cppu::OPropertyArrayHelper( aProps ); + } + + OUString SAL_CALL Wizard::getHelpURL() + { + SolarMutexGuard aSolarGuard; + ::osl::MutexGuard aGuard( m_aMutex ); + + if (!m_xDialog) + return m_sHelpURL; + + return lcl_getHelpURL(m_xDialog->get_help_id()); + } + + void SAL_CALL Wizard::setHelpURL( const OUString& i_HelpURL ) + { + SolarMutexGuard aSolarGuard; + ::osl::MutexGuard aGuard( m_aMutex ); + + if (!m_xDialog) + m_sHelpURL = i_HelpURL; + else + m_xDialog->set_help_id(lcl_getHelpId(i_HelpURL)); + } + + Reference< XWindow > SAL_CALL Wizard::getDialogWindow() + { + SolarMutexGuard aSolarGuard; + ::osl::MutexGuard aGuard( m_aMutex ); + + ENSURE_OR_RETURN( m_xDialog, "Wizard::getDialogWindow: illegal call (execution did not start, yet)!", nullptr ); + return m_xDialog->getDialog()->GetXWindow(); + } + + void SAL_CALL Wizard::enableButton( ::sal_Int16 i_WizardButton, sal_Bool i_Enable ) + { + SolarMutexGuard aSolarGuard; + ::osl::MutexGuard aGuard( m_aMutex ); + + WizardShell* pWizardImpl = dynamic_cast<WizardShell*>(m_xDialog.get()); + ENSURE_OR_RETURN_VOID( pWizardImpl, "Wizard::enableButtons: invalid dialog implementation!" ); + + pWizardImpl->enableButtons( lcl_convertWizardButtonToWZB( i_WizardButton ), i_Enable ); + } + + void SAL_CALL Wizard::setDefaultButton( ::sal_Int16 i_WizardButton ) + { + SolarMutexGuard aSolarGuard; + ::osl::MutexGuard aGuard( m_aMutex ); + + WizardShell* pWizardImpl = dynamic_cast<WizardShell*>(m_xDialog.get()); + ENSURE_OR_RETURN_VOID( pWizardImpl, "Wizard::setDefaultButton: invalid dialog implementation!" ); + + pWizardImpl->defaultButton( lcl_convertWizardButtonToWZB( i_WizardButton ) ); + } + + sal_Bool SAL_CALL Wizard::travelNext( ) + { + SolarMutexGuard aSolarGuard; + ::osl::MutexGuard aGuard( m_aMutex ); + + WizardShell* pWizardImpl = dynamic_cast<WizardShell*>(m_xDialog.get()); + ENSURE_OR_RETURN_FALSE( pWizardImpl, "Wizard::travelNext: invalid dialog implementation!" ); + + return pWizardImpl->travelNext(); + } + + sal_Bool SAL_CALL Wizard::travelPrevious( ) + { + SolarMutexGuard aSolarGuard; + ::osl::MutexGuard aGuard( m_aMutex ); + + WizardShell* pWizardImpl = dynamic_cast<WizardShell*>(m_xDialog.get()); + ENSURE_OR_RETURN_FALSE( pWizardImpl, "Wizard::travelPrevious: invalid dialog implementation!" ); + + return pWizardImpl->travelPrevious(); + } + + void SAL_CALL Wizard::enablePage( ::sal_Int16 i_PageID, sal_Bool i_Enable ) + { + SolarMutexGuard aSolarGuard; + ::osl::MutexGuard aGuard( m_aMutex ); + + WizardShell* pWizardImpl = dynamic_cast<WizardShell*>(m_xDialog.get()); + ENSURE_OR_RETURN_VOID( pWizardImpl, "Wizard::enablePage: invalid dialog implementation!" ); + + if ( !pWizardImpl->knowsPage( i_PageID ) ) + throw NoSuchElementException( OUString(), *this ); + + if ( i_PageID == pWizardImpl->getCurrentPage() ) + throw InvalidStateException( OUString(), *this ); + + pWizardImpl->enablePage( i_PageID, i_Enable ); + } + + void SAL_CALL Wizard::updateTravelUI( ) + { + SolarMutexGuard aSolarGuard; + ::osl::MutexGuard aGuard( m_aMutex ); + + WizardShell* pWizardImpl = dynamic_cast<WizardShell*>(m_xDialog.get()); + ENSURE_OR_RETURN_VOID( pWizardImpl, "Wizard::updateTravelUI: invalid dialog implementation!" ); + + pWizardImpl->updateTravelUI(); + } + + sal_Bool SAL_CALL Wizard::advanceTo( ::sal_Int16 i_PageId ) + { + SolarMutexGuard aSolarGuard; + ::osl::MutexGuard aGuard( m_aMutex ); + + WizardShell* pWizardImpl = dynamic_cast<WizardShell*>(m_xDialog.get()); + ENSURE_OR_RETURN_FALSE( pWizardImpl, "Wizard::advanceTo: invalid dialog implementation!" ); + + return pWizardImpl->advanceTo( i_PageId ); + } + + sal_Bool SAL_CALL Wizard::goBackTo( ::sal_Int16 i_PageId ) + { + SolarMutexGuard aSolarGuard; + ::osl::MutexGuard aGuard( m_aMutex ); + + WizardShell* pWizardImpl = dynamic_cast<WizardShell*>(m_xDialog.get()); + ENSURE_OR_RETURN_FALSE( pWizardImpl, "Wizard::goBackTo: invalid dialog implementation!" ); + + return pWizardImpl->goBackTo( i_PageId ); + } + + Reference< XWizardPage > SAL_CALL Wizard::getCurrentPage( ) + { + SolarMutexGuard aSolarGuard; + ::osl::MutexGuard aGuard( m_aMutex ); + + WizardShell* pWizardImpl = dynamic_cast<WizardShell*>(m_xDialog.get()); + ENSURE_OR_RETURN( pWizardImpl, "Wizard::getCurrentPage: invalid dialog implementation!", Reference< XWizardPage >() ); + + return pWizardImpl->getCurrentWizardPage(); + } + + void SAL_CALL Wizard::activatePath( ::sal_Int16 i_PathIndex, sal_Bool i_Final ) + { + SolarMutexGuard aSolarGuard; + ::osl::MutexGuard aGuard( m_aMutex ); + + if ( ( i_PathIndex < 0 ) || ( i_PathIndex >= m_aWizardSteps.getLength() ) ) + throw NoSuchElementException( OUString(), *this ); + + WizardShell* pWizardImpl = dynamic_cast<WizardShell*>(m_xDialog.get()); + ENSURE_OR_RETURN_VOID( pWizardImpl, "Wizard::activatePath: invalid dialog implementation!" ); + + pWizardImpl->activatePath( i_PathIndex, i_Final ); + } + + void SAL_CALL Wizard::setTitle( const OUString& i_Title ) + { + // simply disambiguate + Wizard_Base::OGenericUnoDialog::setTitle( i_Title ); + } + + ::sal_Int16 SAL_CALL Wizard::execute( ) + { + return Wizard_Base::OGenericUnoDialog::execute(); + } +} + +extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface * +com_sun_star_comp_svtools_uno_Wizard_get_implementation( + css::uno::XComponentContext *context, + css::uno::Sequence<css::uno::Any> const &) +{ + return cppu::acquire(new Wizard(context)); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/uno/wizard/wizardpagecontroller.cxx b/svtools/source/uno/wizard/wizardpagecontroller.cxx new file mode 100644 index 000000000..2790a0e57 --- /dev/null +++ b/svtools/source/uno/wizard/wizardpagecontroller.cxx @@ -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 . + */ + + +#include "wizardpagecontroller.hxx" +#include "wizardshell.hxx" + +#include <com/sun/star/awt/XControl.hpp> + +#include <toolkit/helper/vclunohelper.hxx> +#include <tools/diagnose_ex.h> + + +namespace svt::uno +{ + + + using css::uno::Reference; + using css::uno::UNO_SET_THROW; + using css::uno::Exception; + using css::ui::dialogs::XWizardController; + using css::awt::XWindow; + + using namespace ::com::sun::star; + + + //= WizardPageController + + + WizardPageController::WizardPageController(weld::Container* pParent, const Reference< XWizardController >& i_rController, + const sal_Int16 i_nPageId ) + :m_xController( i_rController ) + ,m_xWizardPage() + { + ENSURE_OR_THROW( m_xController.is(), "no controller" ); + try + { + // Plug a toplevel SalFrame into the native page which can host our awt widgetry + m_xWizardPage.set(m_xController->createPage(pParent->CreateChildFrame(), i_nPageId), UNO_SET_THROW); + + Reference< XWindow > xPageWindow(m_xWizardPage->getWindow(), UNO_SET_THROW); + xPageWindow->setVisible( true ); + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION("svtools.uno"); + } + } + + WizardPageController::~WizardPageController() + { + try + { + if ( m_xWizardPage.is() ) + m_xWizardPage->dispose(); + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION("svtools.uno"); + } + } + + void WizardPageController::initializePage() + { + if ( !m_xWizardPage.is() ) + return; + + try + { + m_xWizardPage->activatePage(); + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION("svtools.uno"); + } + } + + bool WizardPageController::commitPage( vcl::WizardTypes::CommitPageReason i_eReason ) + { + if ( !m_xWizardPage.is() ) + return true; + + try + { + return m_xWizardPage->commitPage( WizardShell::convertCommitReasonToTravelType( i_eReason ) ); + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION("svtools.uno"); + } + + return true; + } + + bool WizardPageController::canAdvance() const + { + if ( !m_xWizardPage.is() ) + return true; + + try + { + return m_xWizardPage->canAdvance(); + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION("svtools.uno"); + } + + return true; + } + + +} // namespace svt::uno + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/uno/wizard/wizardpagecontroller.hxx b/svtools/source/uno/wizard/wizardpagecontroller.hxx new file mode 100644 index 000000000..68d724591 --- /dev/null +++ b/svtools/source/uno/wizard/wizardpagecontroller.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 <vcl/wizardmachine.hxx> +#include <com/sun/star/ui/dialogs/XWizardController.hpp> + +namespace svt::uno +{ + + + class WizardShell; + + + //= WizardPageController + + class WizardPageController : public vcl::IWizardPageController + { + public: + WizardPageController( + weld::Container* pParent, + const css::uno::Reference< css::ui::dialogs::XWizardController >& i_rController, + const sal_Int16 i_nPageId + ); + virtual ~WizardPageController(); + + // IWizardPageController overridables + virtual void initializePage() override; + virtual bool commitPage( vcl::WizardTypes::CommitPageReason _eReason ) override; + virtual bool canAdvance() const override; + + const css::uno::Reference< css::ui::dialogs::XWizardPage >& + getWizardPage() const { return m_xWizardPage; } + + private: + const css::uno::Reference< css::ui::dialogs::XWizardController > m_xController; + css::uno::Reference< css::ui::dialogs::XWizardPage > m_xWizardPage; + }; + + +} // namespace svt::uno + + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/uno/wizard/wizardshell.cxx b/svtools/source/uno/wizard/wizardshell.cxx new file mode 100644 index 000000000..7876e62ac --- /dev/null +++ b/svtools/source/uno/wizard/wizardshell.cxx @@ -0,0 +1,257 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this 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 "wizardshell.hxx" +#include "wizardpagecontroller.hxx" + +#include <tools/diagnose_ex.h> + +#include <com/sun/star/ui/dialogs/WizardTravelType.hpp> + +using vcl::RoadmapWizardTypes::WizardPath; + +namespace svt::uno +{ + + + using css::uno::Reference; + using css::uno::Exception; + using css::uno::Sequence; + using css::ui::dialogs::XWizardController; + using css::ui::dialogs::XWizardPage; + + namespace WizardTravelType = css::ui::dialogs::WizardTravelType; + + + namespace + { + + sal_Int16 lcl_determineFirstPageID( const Sequence< Sequence< sal_Int16 > >& i_rPaths ) + { + ENSURE_OR_THROW( i_rPaths.hasElements() && i_rPaths[0].hasElements(), "illegal paths" ); + return i_rPaths[0][0]; + } + } + + //= WizardShell + WizardShell::WizardShell(weld::Window* i_pParent, const Reference< XWizardController >& i_rController, + const Sequence< Sequence< sal_Int16 > >& i_rPaths) + :WizardShell_Base( i_pParent ) + ,m_xController( i_rController ) + ,m_nFirstPageID( lcl_determineFirstPageID( i_rPaths ) ) + { + ENSURE_OR_THROW( m_xController.is(), "invalid controller" ); + + // declare the paths + for ( sal_Int32 i=0; i<i_rPaths.getLength(); ++i ) + { + const Sequence< sal_Int16 >& rPath( i_rPaths[i] ); + WizardPath aPath( rPath.getLength() ); + std::transform(rPath.begin(), rPath.end(), aPath.begin(), + [this](const sal_Int16 nPageId) -> WizardPath::value_type { return impl_pageIdToState(nPageId); }); + declarePath( i, aPath ); + } + + // create the first page, to know the page size + GetOrCreatePage( impl_pageIdToState( i_rPaths[0][0] ) ); + m_xAssistant->set_current_page(0); + + // some defaults + enableAutomaticNextButtonState(); + } + + short WizardShell::run() + { + ActivatePage(); + return WizardShell_Base::run(); + } + + sal_Int16 WizardShell::convertCommitReasonToTravelType( const CommitPageReason i_eReason ) + { + switch ( i_eReason ) + { + case vcl::WizardTypes::eTravelForward: + return WizardTravelType::FORWARD; + + case vcl::WizardTypes::eTravelBackward: + return WizardTravelType::BACKWARD; + + case vcl::WizardTypes::eFinish: + return WizardTravelType::FINISH; + + default: + break; + } + OSL_FAIL( "WizardShell::convertCommitReasonToTravelType: unsupported CommitPageReason!" ); + return WizardTravelType::FINISH; + } + + + void WizardShell::enterState( WizardState i_nState ) + { + WizardShell_Base::enterState( i_nState ); + + if ( !m_xController.is() ) + return; + + try + { + m_xController->onActivatePage( impl_stateToPageId( i_nState ) ); + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION("svtools.uno"); + } + } + + + bool WizardShell::leaveState( WizardState i_nState ) + { + if ( !WizardShell_Base::leaveState( i_nState ) ) + return false; + + if ( !m_xController.is() ) + return true; + + try + { + m_xController->onDeactivatePage( impl_stateToPageId( i_nState ) ); + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION("svtools.uno"); + } + + return true; + } + + + PWizardPageController WizardShell::impl_getController(BuilderPage* i_pPage) const + { + Page2ControllerMap::const_iterator pos = m_aPageControllers.find( i_pPage ); + ENSURE_OR_RETURN( pos != m_aPageControllers.end(), "WizardShell::impl_getController: no controller for this page!", PWizardPageController() ); + return pos->second; + } + + + Reference< XWizardPage > WizardShell::getCurrentWizardPage() const + { + const WizardState eState = getCurrentState(); + + PWizardPageController pController( impl_getController( GetPage( eState ) ) ); + ENSURE_OR_RETURN( pController, "WizardShell::getCurrentWizardPage: invalid page/controller!", nullptr ); + + return pController->getWizardPage(); + } + + void WizardShell::enablePage( const sal_Int16 i_nPageID, const bool i_bEnable ) + { + enableState( impl_pageIdToState( i_nPageID ), i_bEnable ); + } + + namespace + { + class EmptyPage : public BuilderPage + { + public: + EmptyPage(weld::Widget* pParent, weld::DialogController* pController) + : BuilderPage(pParent, pController, "svt/ui/emptypage.ui", "EmptyPage") + { + m_xContainer->set_size_request(m_xContainer->get_approximate_digit_width() * 70, + m_xContainer->get_text_height() * 45); + } + weld::Container* GetContainer() const { return m_xContainer.get(); } + }; + } + + std::unique_ptr<BuilderPage> WizardShell::createPage( WizardState i_nState ) + { + ENSURE_OR_RETURN( m_xController.is(), "WizardShell::createPage: no WizardController!", nullptr ); + + sal_Int16 nPageId = impl_stateToPageId(i_nState); + + OString sIdent(OString::number(nPageId)); + weld::Container* pPageContainer = m_xAssistant->append_page(sIdent); + + auto xPage = std::make_unique<EmptyPage>(pPageContainer, this); + auto pController = std::make_shared<WizardPageController>(xPage->GetContainer(), m_xController, nPageId); + + m_aPageControllers[xPage.get()] = pController; + + return xPage; + } + + vcl::IWizardPageController* WizardShell::getPageController(BuilderPage* i_pCurrentPage) const + { + return impl_getController( i_pCurrentPage ).get(); + } + + OUString WizardShell::getStateDisplayName( WizardState i_nState ) const + { + try + { + if ( m_xController.is() ) + return m_xController->getPageTitle( impl_stateToPageId( i_nState ) ); + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION("svtools.uno"); + } + // fallback for ill-behaved clients: the numeric state + return OUString::number(i_nState); + } + + + bool WizardShell::canAdvance() const + { + try + { + if ( m_xController.is() && !m_xController->canAdvance() ) + return false; + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION("svtools.uno"); + } + + return WizardShell_Base::canAdvance(); + } + + + bool WizardShell::onFinish() + { + try + { + if ( m_xController.is() && !m_xController->confirmFinish() ) + return false; + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION("svtools.uno"); + } + + return WizardShell_Base::onFinish(); + } + + +} // namespace svt::uno + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/source/uno/wizard/wizardshell.hxx b/svtools/source/uno/wizard/wizardshell.hxx new file mode 100644 index 000000000..21e3130e4 --- /dev/null +++ b/svtools/source/uno/wizard/wizardshell.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 + +#include <com/sun/star/ui/dialogs/XWizardController.hpp> +#include <com/sun/star/ui/dialogs/XWizard.hpp> +#include <vcl/roadmapwizard.hxx> +#include <map> +#include <memory> + +using vcl::WizardTypes::WizardState; +using vcl::WizardTypes::CommitPageReason; + +namespace svt::uno +{ + + + class WizardPageController; + typedef std::shared_ptr< WizardPageController > PWizardPageController; + + + //= WizardShell + + typedef ::vcl::RoadmapWizardMachine WizardShell_Base; + class WizardShell : public WizardShell_Base + { + public: + WizardShell( + weld::Window* pParent, + const css::uno::Reference< css::ui::dialogs::XWizardController >& i_rController, + const css::uno::Sequence< css::uno::Sequence< sal_Int16 > >& i_rPaths + ); + + // Dialog overridables + virtual short run() override; + + // OWizardMachine overridables + virtual std::unique_ptr<BuilderPage> createPage( WizardState i_nState ) override; + virtual void enterState( WizardState i_nState ) override; + virtual bool leaveState( WizardState i_nState ) override; + virtual OUString getStateDisplayName( WizardState i_nState ) const override; + virtual bool canAdvance() const override; + virtual bool onFinish() override; + virtual vcl::IWizardPageController* getPageController(BuilderPage* pCurrentPage) const override; + + static sal_Int16 convertCommitReasonToTravelType( const CommitPageReason i_eReason ); + + // operations + bool advanceTo( const sal_Int16 i_nPageId ) + { + return skipUntil( impl_pageIdToState( i_nPageId ) ); + } + bool goBackTo( const sal_Int16 i_nPageId ) + { + return skipBackwardUntil( impl_pageIdToState( i_nPageId ) ); + } + using WizardShell_Base::travelNext; + using WizardShell_Base::travelPrevious; + + void activatePath( const sal_Int16 i_nPathID, const bool i_bFinal ) + { + WizardShell_Base::activatePath( vcl::RoadmapWizardTypes::PathId( i_nPathID ), i_bFinal ); + } + + css::uno::Reference< css::ui::dialogs::XWizardPage > + getCurrentWizardPage() const; + + sal_Int16 getCurrentPage() const + { + return impl_stateToPageId( getCurrentState() ); + } + + void enablePage( const sal_Int16 i_PageID, const bool i_Enable ); + + bool knowsPage( const sal_Int16 i_nPageID ) const + { + return knowsState( impl_pageIdToState( i_nPageID ) ); + } + + private: + sal_Int16 impl_stateToPageId( const WizardState i_nState ) const + { + return static_cast< sal_Int16 >( i_nState + m_nFirstPageID ); + } + + WizardState impl_pageIdToState( const sal_Int16 i_nPageId ) const + { + return static_cast<WizardState>(i_nPageId - m_nFirstPageID); + } + + PWizardPageController impl_getController(BuilderPage* i_pPage) const; + + // prevent outside access to some base class members + using WizardShell_Base::skip; + using WizardShell_Base::skipUntil; + using WizardShell_Base::skipBackwardUntil; + using WizardShell_Base::getCurrentState; + using WizardShell_Base::activatePath; + + private: + typedef std::map<BuilderPage*, PWizardPageController> Page2ControllerMap; + + const css::uno::Reference< css::ui::dialogs::XWizardController > m_xController; + const sal_Int16 m_nFirstPageID; + Page2ControllerMap m_aPageControllers; + }; + + +} // namespace svt::uno + + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svtools/uiconfig/ui/addresstemplatedialog.ui b/svtools/uiconfig/ui/addresstemplatedialog.ui new file mode 100644 index 000000000..5646b9e75 --- /dev/null +++ b/svtools/uiconfig/ui/addresstemplatedialog.ui @@ -0,0 +1,567 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Generated with glade 3.22.1 --> +<interface domain="svt"> + <requires lib="gtk+" version="3.18"/> + <object class="GtkDialog" id="AddressTemplateDialog"> + <property name="can_focus">False</property> + <property name="border_width">6</property> + <property name="title" translatable="yes" context="addresstemplatedialog|AddressTemplateDialog">Templates: Address Book Assignment</property> + <property name="resizable">False</property> + <property name="modal">True</property> + <property name="default_width">0</property> + <property name="default_height">0</property> + <property name="type_hint">dialog</property> + <child> + <placeholder/> + </child> + <child internal-child="vbox"> + <object class="GtkBox" id="dialog-vbox1"> + <property name="can_focus">False</property> + <property name="orientation">vertical</property> + <property name="spacing">12</property> + <child internal-child="action_area"> + <object class="GtkButtonBox" id="dialog-action_area1"> + <property name="can_focus">False</property> + <property name="layout_style">end</property> + <child> + <object class="GtkButton" id="ok"> + <property name="label">gtk-ok</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="can_default">True</property> + <property name="has_default">True</property> + <property name="receives_default">True</property> + <property name="use_stock">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">0</property> + </packing> + </child> + <child> + <object class="GtkButton" id="cancel"> + <property name="label">gtk-cancel</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <property name="use_stock">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">1</property> + </packing> + </child> + <child> + <object class="GtkButton" id="help"> + <property name="label">gtk-help</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <property name="use_stock">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">2</property> + <property name="secondary">True</property> + </packing> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="pack_type">end</property> + <property name="position">0</property> + </packing> + </child> + <child> + <object class="GtkGrid" id="grid1"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="hexpand">True</property> + <property name="vexpand">True</property> + <property name="row_spacing">12</property> + <child> + <object class="GtkFrame" id="frame1"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="hexpand">True</property> + <property name="label_xalign">0</property> + <property name="shadow_type">none</property> + <child> + <object class="GtkAlignment" id="alignment1"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="top_padding">6</property> + <property name="left_padding">12</property> + <child> + <object class="GtkGrid" id="grid2"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="row_spacing">6</property> + <property name="column_spacing">12</property> + <child> + <object class="GtkLabel" id="label33"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="addresstemplatedialog|label33">Data source:</property> + <property name="use_underline">True</property> + <property name="mnemonic_widget">datasource</property> + <property name="xalign">1</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">0</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="label43"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="addresstemplatedialog|label43">Table:</property> + <property name="use_underline">True</property> + <property name="mnemonic_widget">datatable</property> + <property name="xalign">1</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">1</property> + </packing> + </child> + <child> + <object class="GtkComboBoxText" id="datasource"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="hexpand">True</property> + <property name="has_entry">True</property> + <child internal-child="entry"> + <object class="GtkEntry" id="comboboxtext-entry"> + <property name="can_focus">True</property> + <property name="activates_default">True</property> + </object> + </child> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">0</property> + </packing> + </child> + <child> + <object class="GtkComboBoxText" id="datatable"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="hexpand">True</property> + <property name="has_entry">True</property> + <child internal-child="entry"> + <object class="GtkEntry" id="comboboxtext-entry1"> + <property name="can_focus">True</property> + <property name="activates_default">True</property> + </object> + </child> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">1</property> + </packing> + </child> + <child> + <object class="GtkButton" id="admin"> + <property name="label" translatable="yes" context="addresstemplatedialog|admin">_Assign</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <property name="use_underline">True</property> + </object> + <packing> + <property name="left_attach">2</property> + <property name="top_attach">0</property> + </packing> + </child> + <child> + <placeholder/> + </child> + </object> + </child> + </object> + </child> + <child type="label"> + <object class="GtkLabel" id="label100"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="addresstemplatedialog|label100">Address Book Source</property> + <attributes> + <attribute name="weight" value="bold"/> + </attributes> + </object> + </child> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">0</property> + </packing> + </child> + <child> + <object class="GtkFrame" id="assign"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="hexpand">True</property> + <property name="vexpand">True</property> + <property name="label_xalign">0</property> + <property name="shadow_type">none</property> + <child> + <object class="GtkAlignment" id="alignment2"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="top_padding">6</property> + <property name="left_padding">12</property> + <child> + <object class="GtkScrolledWindow" id="scrollwindow"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="hexpand">True</property> + <property name="vexpand">True</property> + <property name="hscrollbar_policy">never</property> + <property name="vscrollbar_policy">always</property> + <property name="shadow_type">in</property> + <child> + <object class="GtkViewport" id="viewport1"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <child> + <object class="GtkGrid" id="grid"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <child> + <object class="GtkGrid"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="hexpand">True</property> + <property name="border_width">6</property> + <property name="column_spacing">18</property> + <property name="column_homogeneous">True</property> + <child> + <object class="GtkGrid" id="grid5"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="hexpand">True</property> + <property name="vexpand">True</property> + <property name="row_spacing">6</property> + <property name="column_spacing">12</property> + <child> + <object class="GtkLabel" id="label0"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="no">label</property> + <property name="use_underline">True</property> + <property name="mnemonic_widget">box0</property> + <property name="xalign">1</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">0</property> + </packing> + </child> + <child> + <object class="GtkComboBoxText" id="box0"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="hexpand">True</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">0</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="label2"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="no">label</property> + <property name="use_underline">True</property> + <property name="mnemonic_widget">box2</property> + <property name="xalign">1</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">1</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="label4"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="no">label</property> + <property name="use_underline">True</property> + <property name="mnemonic_widget">box4</property> + <property name="xalign">1</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">2</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="label6"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="no">label</property> + <property name="use_underline">True</property> + <property name="mnemonic_widget">box6</property> + <property name="xalign">1</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">3</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="label8"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="no">label</property> + <property name="use_underline">True</property> + <property name="mnemonic_widget">box8</property> + <property name="xalign">1</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">4</property> + </packing> + </child> + <child> + <object class="GtkComboBoxText" id="box2"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="hexpand">True</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">1</property> + </packing> + </child> + <child> + <object class="GtkComboBoxText" id="box4"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="hexpand">True</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">2</property> + </packing> + </child> + <child> + <object class="GtkComboBoxText" id="box6"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="hexpand">True</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">3</property> + </packing> + </child> + <child> + <object class="GtkComboBoxText" id="box8"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="hexpand">True</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">4</property> + </packing> + </child> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">0</property> + </packing> + </child> + <child> + <object class="GtkGrid" id="grid6"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="hexpand">True</property> + <property name="vexpand">True</property> + <property name="row_spacing">6</property> + <property name="column_spacing">12</property> + <child> + <object class="GtkLabel" id="label1"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="no">label</property> + <property name="use_underline">True</property> + <property name="mnemonic_widget">box1</property> + <property name="xalign">1</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">0</property> + </packing> + </child> + <child> + <object class="GtkComboBoxText" id="box1"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="hexpand">True</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">0</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="label3"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="no">label</property> + <property name="use_underline">True</property> + <property name="mnemonic_widget">box3</property> + <property name="xalign">1</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">1</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="label5"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="no">label</property> + <property name="use_underline">True</property> + <property name="mnemonic_widget">box5</property> + <property name="xalign">1</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">2</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="label7"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="no">label</property> + <property name="use_underline">True</property> + <property name="mnemonic_widget">box7</property> + <property name="xalign">1</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">3</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="label9"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="no">label</property> + <property name="use_underline">True</property> + <property name="mnemonic_widget">box9</property> + <property name="xalign">1</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">4</property> + </packing> + </child> + <child> + <object class="GtkComboBoxText" id="box3"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="hexpand">True</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">1</property> + </packing> + </child> + <child> + <object class="GtkComboBoxText" id="box5"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="hexpand">True</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">2</property> + </packing> + </child> + <child> + <object class="GtkComboBoxText" id="box7"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="hexpand">True</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">3</property> + </packing> + </child> + <child> + <object class="GtkComboBoxText" id="box9"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="hexpand">True</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">4</property> + </packing> + </child> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">0</property> + </packing> + </child> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">0</property> + </packing> + </child> + </object> + </child> + </object> + </child> + </object> + </child> + </object> + </child> + <child type="label"> + <object class="GtkLabel" id="label23"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="addresstemplatedialog|label23">Field Assignment</property> + <attributes> + <attribute name="weight" value="bold"/> + </attributes> + </object> + </child> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">1</property> + </packing> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">1</property> + </packing> + </child> + </object> + </child> + <action-widgets> + <action-widget response="-5">ok</action-widget> + <action-widget response="-6">cancel</action-widget> + <action-widget response="-11">help</action-widget> + </action-widgets> + </object> +</interface> diff --git a/svtools/uiconfig/ui/combocontrol.ui b/svtools/uiconfig/ui/combocontrol.ui new file mode 100644 index 000000000..b3a8ee9e9 --- /dev/null +++ b/svtools/uiconfig/ui/combocontrol.ui @@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Generated with glade 3.22.1 --> +<interface domain="svt"> + <requires lib="gtk+" version="3.18"/> + <object class="GtkBox" id="ComboControl"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="orientation">vertical</property> + <child> + <object class="GtkComboBoxText" id="combobox"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="hexpand">True</property> + <property name="has_entry">True</property> + <child internal-child="entry"> + <object class="GtkEntry"> + <property name="can_focus">True</property> + </object> + </child> + </object> + <packing> + <property name="expand">True</property> + <property name="fill">True</property> + <property name="position">0</property> + </packing> + </child> + </object> +</interface> diff --git a/svtools/uiconfig/ui/datewindow.ui b/svtools/uiconfig/ui/datewindow.ui new file mode 100644 index 000000000..bce2ff038 --- /dev/null +++ b/svtools/uiconfig/ui/datewindow.ui @@ -0,0 +1,32 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Generated with glade 3.22.1 --> +<interface domain="svt"> + <requires lib="gtk+" version="3.18"/> + <object class="GtkPopover" id="date_popup_window"> + <property name="can_focus">False</property> + <property name="no_show_all">True</property> + <property name="border_width">4</property> + <child> + <object class="GtkBox" id="box1"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="orientation">vertical</property> + <property name="spacing">6</property> + <child> + <object class="GtkCalendar" id="date"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="year">2019</property> + <property name="month">1</property> + <property name="day">14</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">0</property> + </packing> + </child> + </object> + </child> + </object> +</interface> diff --git a/svtools/uiconfig/ui/editcontrol.ui b/svtools/uiconfig/ui/editcontrol.ui new file mode 100644 index 000000000..3be2e2487 --- /dev/null +++ b/svtools/uiconfig/ui/editcontrol.ui @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Generated with glade 3.22.1 --> +<interface domain="svt"> + <requires lib="gtk+" version="3.18"/> + <object class="GtkBox" id="EditControl"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="hexpand">True</property> + <property name="spacing">6</property> + <child> + <object class="GtkEntry" id="entry"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="hexpand">True</property> + <property name="vexpand">True</property> + <property name="activates_default">True</property> + <property name="width_chars">1</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">0</property> + </packing> + </child> + </object> +</interface> diff --git a/svtools/uiconfig/ui/emptypage.ui b/svtools/uiconfig/ui/emptypage.ui new file mode 100644 index 000000000..c793016c2 --- /dev/null +++ b/svtools/uiconfig/ui/emptypage.ui @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Generated with glade 3.22.1 --> +<interface domain="svt"> + <requires lib="gtk+" version="3.18"/> + <object class="GtkBox" id="EmptyPage"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="hexpand">True</property> + <property name="vexpand">True</property> + <property name="border_width">6</property> + <property name="spacing">6</property> + <child> + <placeholder/> + </child> + </object> +</interface> diff --git a/svtools/uiconfig/ui/fileviewmenu.ui b/svtools/uiconfig/ui/fileviewmenu.ui new file mode 100644 index 000000000..b47e91174 --- /dev/null +++ b/svtools/uiconfig/ui/fileviewmenu.ui @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Generated with glade 3.20.0 --> +<interface domain="svt"> + <requires lib="gtk+" version="3.18"/> + <object class="GtkMenu" id="menu"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <child> + <object class="GtkMenuItem" id="delete"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="fileviewmenu|delete">_Delete</property> + <property name="use_underline">True</property> + </object> + </child> + <child> + <object class="GtkMenuItem" id="rename"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="fileviewmenu|rename">_Rename</property> + <property name="use_underline">True</property> + </object> + </child> + </object> +</interface> diff --git a/svtools/uiconfig/ui/graphicexport.ui b/svtools/uiconfig/ui/graphicexport.ui new file mode 100644 index 000000000..ddf5ee157 --- /dev/null +++ b/svtools/uiconfig/ui/graphicexport.ui @@ -0,0 +1,964 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Generated with glade 3.22.1 --> +<interface domain="svt"> + <requires lib="gtk+" version="3.18"/> + <object class="GtkAdjustment" id="adjustment1"> + <property name="lower">1</property> + <property name="upper">100</property> + <property name="value">75</property> + <property name="step_increment">1</property> + <property name="page_increment">10</property> + </object> + <object class="GtkAdjustment" id="adjustment2"> + <property name="lower">1</property> + <property name="upper">9</property> + <property name="value">9</property> + <property name="step_increment">1</property> + <property name="page_increment">10</property> + </object> + <object class="GtkAdjustment" id="adjustment3"> + <property name="upper">99999.990000000005</property> + <property name="step_increment">1</property> + <property name="page_increment">10</property> + </object> + <object class="GtkAdjustment" id="adjustment4"> + <property name="upper">99999.990000000005</property> + <property name="step_increment">1</property> + <property name="page_increment">10</property> + </object> + <object class="GtkAdjustment" id="adjustment5"> + <property name="upper">99999</property> + <property name="step_increment">1</property> + <property name="page_increment">10</property> + </object> + <object class="GtkDialog" id="GraphicExportDialog"> + <property name="can_focus">False</property> + <property name="border_width">6</property> + <property name="title" translatable="yes" context="graphicexport|GraphicExportDialog">%1 Options</property> + <property name="resizable">False</property> + <property name="modal">True</property> + <property name="default_width">0</property> + <property name="default_height">0</property> + <property name="type_hint">dialog</property> + <child> + <placeholder/> + </child> + <child internal-child="vbox"> + <object class="GtkBox" id="dialog-vbox1"> + <property name="can_focus">False</property> + <property name="orientation">vertical</property> + <property name="spacing">12</property> + <child internal-child="action_area"> + <object class="GtkButtonBox" id="dialog-action_area1"> + <property name="can_focus">False</property> + <property name="layout_style">end</property> + <child> + <object class="GtkButton" id="help"> + <property name="label">gtk-help</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <property name="use_stock">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">0</property> + </packing> + </child> + <child> + <object class="GtkButton" id="ok"> + <property name="label">gtk-ok</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="can_default">True</property> + <property name="has_default">True</property> + <property name="receives_default">True</property> + <property name="use_stock">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">1</property> + </packing> + </child> + <child> + <object class="GtkButton" id="cancel"> + <property name="label">gtk-cancel</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <property name="use_stock">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">2</property> + </packing> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="pack_type">end</property> + <property name="position">0</property> + </packing> + </child> + <child> + <object class="GtkBox" id="box1"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="orientation">vertical</property> + <property name="spacing">12</property> + <child> + <object class="GtkFrame" id="frame1"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label_xalign">0</property> + <property name="shadow_type">none</property> + <child> + <object class="GtkAlignment" id="alignment1"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="top_padding">6</property> + <property name="left_padding">12</property> + <child> + <object class="GtkGrid" id="grid1"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="row_spacing">6</property> + <property name="column_spacing">6</property> + <child> + <object class="GtkLabel" id="label5"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="graphicexport|label5">Width:</property> + <property name="use_underline">True</property> + <property name="mnemonic_widget">widthmf</property> + <property name="xalign">1</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">0</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="label6"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="graphicexport|label6">Height:</property> + <property name="use_underline">True</property> + <property name="mnemonic_widget">heightmf</property> + <property name="xalign">1</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">1</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="resolutionft"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="graphicexport|resolutionft">Resolution:</property> + <property name="use_underline">True</property> + <property name="mnemonic_widget">resolutionmf</property> + <property name="xalign">1</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">2</property> + </packing> + </child> + <child> + <object class="GtkSpinButton" id="widthmf"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="activates_default">True</property> + <property name="xalign">1</property> + <property name="adjustment">adjustment3</property> + <property name="digits">2</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">0</property> + </packing> + </child> + <child> + <object class="GtkSpinButton" id="heightmf"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="activates_default">True</property> + <property name="xalign">1</property> + <property name="adjustment">adjustment4</property> + <property name="digits">2</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">1</property> + </packing> + </child> + <child> + <object class="GtkSpinButton" id="resolutionmf"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="activates_default">True</property> + <property name="xalign">1</property> + <property name="adjustment">adjustment5</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">2</property> + </packing> + </child> + <child> + <object class="GtkComboBoxText" id="widthlb"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <items> + <item translatable="yes" context="graphicexport|liststore2">inches</item> + <item translatable="yes" context="graphicexport|liststore2">cm</item> + <item translatable="yes" context="graphicexport|liststore2">mm</item> + <item translatable="yes" context="graphicexport|liststore2">points</item> + <item translatable="yes" context="graphicexport|liststore2">pixels</item> + </items> + </object> + <packing> + <property name="left_attach">2</property> + <property name="top_attach">0</property> + </packing> + </child> + <child> + <object class="GtkComboBoxText" id="resolutionlb"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <items> + <item translatable="yes" context="graphicexport|liststore1">pixels/cm</item> + <item translatable="yes" context="graphicexport|liststore1">pixels/inch</item> + <item translatable="yes" context="graphicexport|liststore1">pixels/meter</item> + </items> + </object> + <packing> + <property name="left_attach">2</property> + <property name="top_attach">2</property> + </packing> + </child> + <child> + <placeholder/> + </child> + </object> + </child> + </object> + </child> + <child type="label"> + <object class="GtkLabel" id="label1"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="graphicexport|label1">Size</property> + <attributes> + <attribute name="weight" value="bold"/> + </attributes> + </object> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">0</property> + </packing> + </child> + <child> + <object class="GtkFrame" id="colordepth"> + <property name="can_focus">False</property> + <property name="label_xalign">0</property> + <property name="shadow_type">none</property> + <child> + <object class="GtkAlignment" id="alignment2"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="top_padding">6</property> + <property name="left_padding">12</property> + <child> + <object class="GtkComboBoxText" id="colordepthlb"> + <property name="visible">True</property> + <property name="can_focus">False</property> + </object> + </child> + </object> + </child> + <child type="label"> + <object class="GtkLabel" id="label2"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="graphicexport|label2">Color Depth</property> + <attributes> + <attribute name="weight" value="bold"/> + </attributes> + </object> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">1</property> + </packing> + </child> + <child> + <object class="GtkFrame" id="jpgquality"> + <property name="can_focus">False</property> + <property name="label_xalign">0</property> + <property name="shadow_type">none</property> + <child> + <object class="GtkAlignment" id="alignment5"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="top_padding">6</property> + <property name="left_padding">12</property> + <child> + <object class="GtkGrid" id="grid2"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="column_spacing">6</property> + <child> + <object class="GtkSpinButton" id="compressionjpgnf"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="activates_default">True</property> + <property name="xalign">1</property> + <property name="adjustment">adjustment1</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">0</property> + </packing> + </child> + <child> + <object class="GtkScale" id="compressionjpgsb"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="valign">center</property> + <property name="hexpand">True</property> + <property name="adjustment">adjustment1</property> + <property name="digits">0</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">0</property> + </packing> + </child> + </object> + </child> + </object> + </child> + <child type="label"> + <object class="GtkLabel" id="label9"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="graphicexport|label9">Quality</property> + <attributes> + <attribute name="weight" value="bold"/> + </attributes> + </object> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">2</property> + </packing> + </child> + <child> + <object class="GtkFrame" id="pngcompression"> + <property name="can_focus">False</property> + <property name="label_xalign">0</property> + <property name="shadow_type">none</property> + <child> + <object class="GtkAlignment" id="alignment13"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="top_padding">6</property> + <property name="left_padding">12</property> + <child> + <object class="GtkGrid" id="grid9"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="column_spacing">6</property> + <child> + <object class="GtkSpinButton" id="compressionpngnf"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="activates_default">True</property> + <property name="xalign">1</property> + <property name="adjustment">adjustment2</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">0</property> + </packing> + </child> + <child> + <object class="GtkScale" id="compressionpngsb"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="valign">center</property> + <property name="hexpand">True</property> + <property name="adjustment">adjustment2</property> + <property name="digits">0</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">0</property> + </packing> + </child> + </object> + </child> + </object> + </child> + <child type="label"> + <object class="GtkLabel" id="label"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="graphicexport|label">Compression</property> + <attributes> + <attribute name="weight" value="bold"/> + </attributes> + </object> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">3</property> + </packing> + </child> + <child> + <object class="GtkFrame" id="bmpcompression"> + <property name="can_focus">False</property> + <property name="label_xalign">0</property> + <property name="shadow_type">none</property> + <child> + <object class="GtkAlignment" id="alignment3"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="top_padding">6</property> + <property name="left_padding">12</property> + <child> + <object class="GtkCheckButton" id="rlecb"> + <property name="label" translatable="yes" context="graphicexport|rlecb">RLE encoding</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">False</property> + <property name="use_underline">True</property> + <property name="xalign">0</property> + <property name="active">True</property> + <property name="draw_indicator">True</property> + </object> + </child> + </object> + </child> + <child type="label"> + <object class="GtkLabel" id="label3"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="graphicexport|label3">Compression</property> + <attributes> + <attribute name="weight" value="bold"/> + </attributes> + </object> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">4</property> + </packing> + </child> + <child> + <object class="GtkFrame" id="mode"> + <property name="can_focus">False</property> + <property name="label_xalign">0</property> + <property name="shadow_type">none</property> + <child> + <object class="GtkAlignment" id="alignment6"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="top_padding">6</property> + <property name="left_padding">12</property> + <child> + <object class="GtkCheckButton" id="interlacedcb"> + <property name="label" translatable="yes" context="graphicexport|interlacedcb">Interlaced</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">False</property> + <property name="use_underline">True</property> + <property name="xalign">0</property> + <property name="active">True</property> + <property name="draw_indicator">True</property> + </object> + </child> + </object> + </child> + <child type="label"> + <object class="GtkLabel" id="label12"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="graphicexport|label12">Mode</property> + <attributes> + <attribute name="weight" value="bold"/> + </attributes> + </object> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">5</property> + </packing> + </child> + <child> + <object class="GtkFrame" id="drawingobjects"> + <property name="can_focus">False</property> + <property name="label_xalign">0</property> + <property name="shadow_type">none</property> + <child> + <object class="GtkAlignment" id="alignment7"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="top_padding">6</property> + <property name="left_padding">12</property> + <child> + <object class="GtkCheckButton" id="savetransparencycb"> + <property name="label" translatable="yes" context="graphicexport|savetransparencycb">Save transparency</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">False</property> + <property name="use_underline">True</property> + <property name="xalign">0</property> + <property name="active">True</property> + <property name="draw_indicator">True</property> + </object> + </child> + </object> + </child> + <child type="label"> + <object class="GtkLabel" id="labe"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="graphicexport|labe">Drawing Objects</property> + <attributes> + <attribute name="weight" value="bold"/> + </attributes> + </object> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">6</property> + </packing> + </child> + <child> + <object class="GtkFrame" id="encoding"> + <property name="can_focus">False</property> + <property name="label_xalign">0</property> + <property name="shadow_type">none</property> + <child> + <object class="GtkAlignment" id="alignment8"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="top_padding">6</property> + <property name="left_padding">12</property> + <child> + <object class="GtkGrid" id="grid3"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <child> + <object class="GtkRadioButton" id="binarycb"> + <property name="label" translatable="yes" context="graphicexport|binarycb">Binary</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">False</property> + <property name="use_underline">True</property> + <property name="xalign">0</property> + <property name="draw_indicator">True</property> + <property name="group">textcb</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">0</property> + </packing> + </child> + <child> + <object class="GtkRadioButton" id="textcb"> + <property name="label" translatable="yes" context="graphicexport|textcb">Text</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">False</property> + <property name="use_underline">True</property> + <property name="xalign">0</property> + <property name="active">True</property> + <property name="draw_indicator">True</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">1</property> + </packing> + </child> + </object> + </child> + </object> + </child> + <child type="label"> + <object class="GtkLabel" id="label16"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="graphicexport|label16">Encoding</property> + <attributes> + <attribute name="weight" value="bold"/> + </attributes> + </object> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">7</property> + </packing> + </child> + <child> + <object class="GtkGrid" id="epsgrid"> + <property name="can_focus">False</property> + <child> + <object class="GtkFrame" id="frame9"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label_xalign">0</property> + <property name="shadow_type">none</property> + <child> + <object class="GtkAlignment" id="alignment9"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="top_padding">6</property> + <property name="left_padding">12</property> + <child> + <object class="GtkGrid" id="grid5"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <child> + <object class="GtkCheckButton" id="tiffpreviewcb"> + <property name="label" translatable="yes" context="graphicexport|tiffpreviewcb">Image preview (TIFF)</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">False</property> + <property name="use_underline">True</property> + <property name="xalign">0</property> + <property name="active">True</property> + <property name="draw_indicator">True</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">0</property> + </packing> + </child> + <child> + <object class="GtkCheckButton" id="epsipreviewcb"> + <property name="label" translatable="yes" context="graphicexport|epsipreviewcb">Interchange (EPSI)</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">False</property> + <property name="use_underline">True</property> + <property name="xalign">0</property> + <property name="draw_indicator">True</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">1</property> + </packing> + </child> + </object> + </child> + </object> + </child> + <child type="label"> + <object class="GtkLabel" id="label17"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="graphicexport|label17">Preview</property> + <attributes> + <attribute name="weight" value="bold"/> + </attributes> + </object> + </child> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">0</property> + </packing> + </child> + <child> + <object class="GtkFrame" id="frame10"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label_xalign">0</property> + <property name="shadow_type">none</property> + <child> + <object class="GtkAlignment" id="alignment10"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="top_padding">6</property> + <property name="left_padding">12</property> + <child> + <object class="GtkGrid" id="grid6"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <child> + <object class="GtkRadioButton" id="color1rb"> + <property name="label" translatable="yes" context="graphicexport|color1rb">Color</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">False</property> + <property name="use_underline">True</property> + <property name="xalign">0</property> + <property name="draw_indicator">True</property> + <property name="group">color2rb</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">0</property> + </packing> + </child> + <child> + <object class="GtkRadioButton" id="color2rb"> + <property name="label" translatable="yes" context="graphicexport|color2rb">Grayscale</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">False</property> + <property name="use_underline">True</property> + <property name="xalign">0</property> + <property name="active">True</property> + <property name="draw_indicator">True</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">1</property> + </packing> + </child> + </object> + </child> + </object> + </child> + <child type="label"> + <object class="GtkLabel" id="label18"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="graphicexport|label18">Color Format</property> + <attributes> + <attribute name="weight" value="bold"/> + </attributes> + </object> + </child> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">0</property> + </packing> + </child> + <child> + <object class="GtkFrame" id="frame11"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label_xalign">0</property> + <property name="shadow_type">none</property> + <child> + <object class="GtkAlignment" id="alignment11"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="top_padding">6</property> + <property name="left_padding">12</property> + <child> + <object class="GtkGrid" id="grid7"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <child> + <object class="GtkRadioButton" id="level1rb"> + <property name="label" translatable="yes" context="graphicexport|level1rb">Level 1</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">False</property> + <property name="use_underline">True</property> + <property name="xalign">0</property> + <property name="draw_indicator">True</property> + <property name="group">level2rb</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">0</property> + </packing> + </child> + <child> + <object class="GtkRadioButton" id="level2rb"> + <property name="label" translatable="yes" context="graphicexport|level2rb">Level 2</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">False</property> + <property name="use_underline">True</property> + <property name="xalign">0.059999998658895493</property> + <property name="active">True</property> + <property name="draw_indicator">True</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">1</property> + </packing> + </child> + </object> + </child> + </object> + </child> + <child type="label"> + <object class="GtkLabel" id="label19"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="graphicexport|label19">Version</property> + <attributes> + <attribute name="weight" value="bold"/> + </attributes> + </object> + </child> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">1</property> + </packing> + </child> + <child> + <object class="GtkFrame" id="EPSCompression"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label_xalign">0</property> + <property name="shadow_type">none</property> + <child> + <object class="GtkAlignment" id="alignment12"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="top_padding">6</property> + <property name="left_padding">12</property> + <child> + <object class="GtkGrid" id="grid8"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <child> + <object class="GtkRadioButton" id="compresslzw"> + <property name="label" translatable="yes" context="graphicexport|compresslzw">LZW encoding</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">False</property> + <property name="use_underline">True</property> + <property name="xalign">0</property> + <property name="draw_indicator">True</property> + <property name="group">compressnone</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">0</property> + </packing> + </child> + <child> + <object class="GtkRadioButton" id="compressnone"> + <property name="label" translatable="yes" context="graphicexport|compressnone">None</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">False</property> + <property name="use_underline">True</property> + <property name="xalign">0</property> + <property name="active">True</property> + <property name="draw_indicator">True</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">1</property> + </packing> + </child> + </object> + </child> + </object> + </child> + <child type="label"> + <object class="GtkLabel" id="label20"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="graphicexport|label20">Compression</property> + <attributes> + <attribute name="weight" value="bold"/> + </attributes> + </object> + </child> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">1</property> + </packing> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">8</property> + </packing> + </child> + <child> + <object class="GtkFrame" id="information"> + <property name="can_focus">False</property> + <property name="label_xalign">0</property> + <property name="shadow_type">none</property> + <child> + <object class="GtkAlignment" id="alignment4"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="top_padding">6</property> + <property name="left_padding">12</property> + <child> + <object class="GtkLabel" id="estsizeft"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="xpad">3</property> + <property name="wrap">True</property> + <property name="max_width_chars">30</property> + <property name="xalign">0</property> + </object> + </child> + </object> + </child> + <child type="label"> + <object class="GtkLabel" id="label4"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="graphicexport|label4">Information</property> + <attributes> + <attribute name="weight" value="bold"/> + </attributes> + </object> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">9</property> + </packing> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">1</property> + </packing> + </child> + </object> + </child> + <action-widgets> + <action-widget response="-11">help</action-widget> + <action-widget response="-5">ok</action-widget> + <action-widget response="-6">cancel</action-widget> + </action-widgets> + </object> +</interface> diff --git a/svtools/uiconfig/ui/inputbox.ui b/svtools/uiconfig/ui/inputbox.ui new file mode 100644 index 000000000..3a7d9a3d6 --- /dev/null +++ b/svtools/uiconfig/ui/inputbox.ui @@ -0,0 +1,109 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Generated with glade 3.22.1 --> +<interface domain="svt"> + <requires lib="gtk+" version="3.18"/> + <object class="GtkDialog" id="InputBox"> + <property name="can_focus">False</property> + <property name="border_width">6</property> + <property name="modal">True</property> + <property name="default_width">0</property> + <property name="default_height">0</property> + <property name="type_hint">dialog</property> + <child> + <placeholder/> + </child> + <child internal-child="vbox"> + <object class="GtkBox" id="dialog-vbox1"> + <property name="can_focus">False</property> + <property name="orientation">vertical</property> + <property name="spacing">12</property> + <child internal-child="action_area"> + <object class="GtkButtonBox" id="dialog-action_area1"> + <property name="can_focus">False</property> + <property name="layout_style">end</property> + <child> + <object class="GtkButton" id="ok"> + <property name="label">gtk-ok</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="can_default">True</property> + <property name="has_default">True</property> + <property name="receives_default">True</property> + <property name="use_stock">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">0</property> + </packing> + </child> + <child> + <object class="GtkButton" id="cancel"> + <property name="label">gtk-cancel</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <property name="use_stock">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">1</property> + </packing> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="pack_type">end</property> + <property name="position">2</property> + </packing> + </child> + <child> + <object class="GtkGrid" id="grid3"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="hexpand">True</property> + <property name="row_spacing">6</property> + <property name="column_spacing">12</property> + <child> + <object class="GtkLabel" id="prompt"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="use_underline">True</property> + <property name="mnemonic_widget">entry</property> + <property name="xalign">0</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">0</property> + </packing> + </child> + <child> + <object class="GtkEntry" id="entry"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="hexpand">True</property> + <property name="activates_default">True</property> + <property name="width_chars">65</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">1</property> + </packing> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">0</property> + </packing> + </child> + </object> + </child> + <action-widgets> + <action-widget response="-5">ok</action-widget> + <action-widget response="-6">cancel</action-widget> + </action-widgets> + </object> +</interface> diff --git a/svtools/uiconfig/ui/javadisableddialog.ui b/svtools/uiconfig/ui/javadisableddialog.ui new file mode 100644 index 000000000..4a00ed5e3 --- /dev/null +++ b/svtools/uiconfig/ui/javadisableddialog.ui @@ -0,0 +1,84 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Generated with glade 3.20.2 --> +<interface domain="svt"> + <requires lib="gtk+" version="3.18"/> + <object class="GtkMessageDialog" id="JavaDisabledDialog"> + <property name="can_focus">False</property> + <property name="title" translatable="yes" context="javadisableddialog|JavaDisabledDialog">Enable JRE?</property> + <property name="resizable">False</property> + <property name="modal">True</property> + <property name="type_hint">dialog</property> + <property name="skip_taskbar_hint">True</property> + <property name="message_type">question</property> + <property name="text" translatable="yes" context="javadisableddialog|JavaDisabledDialog">%PRODUCTNAME requires a Java runtime environment (JRE) to perform this task. However, use of a JRE has been disabled. Do you want to enable the use of a JRE now?</property> + <child internal-child="vbox"> + <object class="GtkBox" id="messagedialog-vbox"> + <property name="can_focus">False</property> + <property name="orientation">vertical</property> + <property name="spacing">12</property> + <child internal-child="action_area"> + <object class="GtkButtonBox" id="messagedialog-action_area"> + <property name="can_focus">False</property> + <child> + <object class="GtkButton" id="no"> + <property name="label">gtk-no</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <property name="use_underline">True</property> + <property name="use_stock">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">0</property> + </packing> + </child> + <child> + <object class="GtkButton" id="yes"> + <property name="label">gtk-yes</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="can_default">True</property> + <property name="has_default">True</property> + <property name="receives_default">True</property> + <property name="use_underline">True</property> + <property name="use_stock">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">1</property> + </packing> + </child> + <child> + <object class="GtkButton" id="cancel"> + <property name="label">gtk-cancel</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <property name="use_stock">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">2</property> + </packing> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="pack_type">end</property> + <property name="position">0</property> + </packing> + </child> + </object> + </child> + <action-widgets> + <action-widget response="-9">no</action-widget> + <action-widget response="-8">yes</action-widget> + <action-widget response="-6">cancel</action-widget> + </action-widgets> + </object> +</interface> diff --git a/svtools/uiconfig/ui/linewindow.ui b/svtools/uiconfig/ui/linewindow.ui new file mode 100644 index 000000000..e283da492 --- /dev/null +++ b/svtools/uiconfig/ui/linewindow.ui @@ -0,0 +1,55 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Generated with glade 3.22.1 --> +<interface domain="svt"> + <requires lib="gtk+" version="3.18"/> + <object class="GtkPopover" id="line_popup_window"> + <property name="can_focus">False</property> + <property name="no_show_all">True</property> + <property name="border_width">4</property> + <child> + <object class="GtkBox" id="box1"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="orientation">vertical</property> + <property name="spacing">6</property> + <child> + <object class="GtkButton" id="none_line_button"> + <property name="label" translatable="yes" context="linewindow|none_line_button">None</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="can_default">True</property> + <property name="receives_default">True</property> + <property name="no_show_all">True</property> + <property name="image">none_icon</property> + <property name="xalign">0</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">0</property> + </packing> + </child> + <child> + <object class="GtkDrawingArea" id="lineset"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <property name="events">GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK | GDK_STRUCTURE_MASK</property> + <property name="hexpand">True</property> + <property name="vexpand">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">1</property> + </packing> + </child> + </object> + </child> + </object> + <object class="GtkImage" id="none_icon"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="icon_name">cmd/sc_square_unfilled.png</property> + </object> +</interface> diff --git a/svtools/uiconfig/ui/listcontrol.ui b/svtools/uiconfig/ui/listcontrol.ui new file mode 100644 index 000000000..f814e31dd --- /dev/null +++ b/svtools/uiconfig/ui/listcontrol.ui @@ -0,0 +1,22 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Generated with glade 3.22.1 --> +<interface domain="svt"> + <requires lib="gtk+" version="3.18"/> + <object class="GtkBox" id="ListControl"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="orientation">vertical</property> + <child> + <object class="GtkComboBoxText" id="listbox"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="hexpand">True</property> + </object> + <packing> + <property name="expand">True</property> + <property name="fill">True</property> + <property name="position">0</property> + </packing> + </child> + </object> +</interface> diff --git a/svtools/uiconfig/ui/placeedit.ui b/svtools/uiconfig/ui/placeedit.ui new file mode 100644 index 000000000..c39144621 --- /dev/null +++ b/svtools/uiconfig/ui/placeedit.ui @@ -0,0 +1,453 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Generated with glade 3.20.4 --> +<interface domain="svt"> + <requires lib="gtk+" version="3.18"/> + <object class="GtkAdjustment" id="adjustment1"> + <property name="upper">65535</property> + <property name="step_increment">1</property> + <property name="page_increment">10</property> + </object> + <object class="GtkImage" id="image1"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="stock">gtk-refresh</property> + </object> + <object class="GtkDialog" id="PlaceEditDialog"> + <property name="can_focus">False</property> + <property name="border_width">6</property> + <property name="title" translatable="yes" context="placeedit|PlaceEditDialog">File Services</property> + <property name="modal">True</property> + <property name="default_width">0</property> + <property name="default_height">0</property> + <property name="type_hint">dialog</property> + <child internal-child="vbox"> + <object class="GtkBox" id="dialog-vbox1"> + <property name="can_focus">False</property> + <property name="orientation">vertical</property> + <property name="spacing">12</property> + <child internal-child="action_area"> + <object class="GtkButtonBox" id="dialog-action_area1"> + <property name="can_focus">False</property> + <property name="layout_style">end</property> + <child> + <object class="GtkButton" id="help"> + <property name="label">gtk-help</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <property name="use_stock">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">0</property> + <property name="secondary">True</property> + </packing> + </child> + <child> + <object class="GtkButton" id="delete"> + <property name="label">gtk-delete</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <property name="use_stock">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">1</property> + <property name="secondary">True</property> + </packing> + </child> + <child> + <object class="GtkButton" id="ok"> + <property name="label">gtk-ok</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="can_default">True</property> + <property name="has_default">True</property> + <property name="receives_default">True</property> + <property name="use_stock">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">2</property> + </packing> + </child> + <child> + <object class="GtkButton" id="cancel"> + <property name="label">gtk-cancel</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <property name="use_stock">True</property> + <property name="image_position">top</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">3</property> + </packing> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="pack_type">end</property> + <property name="position">0</property> + </packing> + </child> + <child> + <object class="GtkGrid" id="TypeGrid"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="row_spacing">6</property> + <property name="column_spacing">12</property> + <child> + <object class="GtkLabel" id="typeLabel"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="placeedit|typeLabel">Type:</property> + <property name="use_underline">True</property> + <property name="mnemonic_widget">type</property> + <property name="xalign">1</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">0</property> + </packing> + </child> + <child> + <object class="GtkComboBoxText" id="type"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="hexpand">True</property> + <items> + <item translatable="yes" context="placeedit|liststore1">WebDAV</item> + <item translatable="yes" context="placeedit|liststore1">FTP</item> + <item translatable="yes" context="placeedit|liststore1">SSH</item> + <item translatable="yes" context="placeedit|liststore1">Windows Share</item> + </items> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">0</property> + </packing> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">0</property> + </packing> + </child> + <child> + <object class="GtkGrid" id="Details"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="row_spacing">6</property> + <property name="column_spacing">12</property> + <child> + <object class="GtkLabel" id="hostLabel"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="placeedit|hostLabel">Host:</property> + <property name="use_underline">True</property> + <property name="mnemonic_widget">host</property> + <property name="xalign">0</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">0</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="pathLabel"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="placeedit|pathLabel">Root:</property> + <property name="use_underline">True</property> + <property name="mnemonic_widget">path</property> + <property name="xalign">0</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">8</property> + </packing> + </child> + <child> + <object class="GtkEntry" id="path"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="hexpand">True</property> + <property name="activates_default">True</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">8</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="shareLabel"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="placeedit|shareLabel">Share:</property> + <property name="use_underline">True</property> + <property name="mnemonic_widget">share</property> + <property name="xalign">0</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">2</property> + </packing> + </child> + <child> + <object class="GtkEntry" id="share"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="hexpand">True</property> + <property name="activates_default">True</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">2</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="repositoryLabel"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="placeedit|repositoryLabel">Repository:</property> + <property name="use_underline">True</property> + <property name="mnemonic_widget">repositories</property> + <property name="xalign">0</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">6</property> + </packing> + </child> + <child> + <object class="GtkCheckButton" id="webdavs"> + <property name="label" translatable="yes" context="placeedit|webdavs">Secure connection</property> + <property name="can_focus">True</property> + <property name="receives_default">False</property> + <property name="use_underline">True</property> + <property name="hexpand">True</property> + <property name="xalign">0</property> + <property name="draw_indicator">True</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">1</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="loginLabel"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="placeedit|loginLabel">User:</property> + <property name="use_underline">True</property> + <property name="mnemonic_widget">login</property> + <property name="xalign">0</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">3</property> + </packing> + </child> + <child> + <object class="GtkEntry" id="login"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="hexpand">True</property> + <property name="activates_default">True</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">3</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="nameLabel"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="placeedit|nameLabel">Label:</property> + <property name="use_underline">True</property> + <property name="mnemonic_widget">name</property> + <property name="xalign">0</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">7</property> + </packing> + </child> + <child> + <object class="GtkEntry" id="name"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="hexpand">True</property> + <property name="activates_default">True</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">7</property> + </packing> + </child> + <child> + <object class="GtkBox" id="HostDetails"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="spacing">6</property> + <child> + <object class="GtkEntry" id="host"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="hexpand">True</property> + <property name="activates_default">True</property> + </object> + <packing> + <property name="expand">True</property> + <property name="fill">True</property> + <property name="position">0</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="portLabel"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="placeedit|portLabel">Port:</property> + <property name="use_underline">True</property> + <property name="mnemonic_widget">port</property> + <property name="xalign">0</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">1</property> + </packing> + </child> + <child> + <object class="GtkSpinButton" id="port"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="activates_default">True</property> + <property name="text">0</property> + <property name="adjustment">adjustment1</property> + <property name="numeric">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">2</property> + </packing> + </child> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">0</property> + </packing> + </child> + <child> + <object class="GtkBox" id="RepositoryDetails"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="spacing">6</property> + <child> + <object class="GtkComboBoxText" id="repositories"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="hexpand">True</property> + </object> + <packing> + <property name="expand">True</property> + <property name="fill">True</property> + <property name="position">0</property> + </packing> + </child> + <child> + <object class="GtkButton" id="repositoriesRefresh"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <property name="image">image1</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">1</property> + </packing> + </child> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">6</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="passwordLabel"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="placeedit|passwordLabel">Password:</property> + <property name="mnemonic_widget">password</property> + <property name="xalign">0</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">4</property> + </packing> + </child> + <child> + <object class="GtkEntry" id="password"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="visibility">False</property> + <property name="activates_default">True</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">4</property> + </packing> + </child> + <child> + <object class="GtkCheckButton" id="rememberPassword"> + <property name="label" translatable="yes" context="placeedit|rememberPassword">Remember password</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">False</property> + <property name="use_underline">True</property> + <property name="xalign">0</property> + <property name="draw_indicator">True</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">5</property> + </packing> + </child> + <child> + <placeholder/> + </child> + <child> + <placeholder/> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">1</property> + </packing> + </child> + </object> + </child> + <action-widgets> + <action-widget response="-11">help</action-widget> + <action-widget response="101">delete</action-widget> + <action-widget response="-5">ok</action-widget> + <action-widget response="-6">cancel</action-widget> + </action-widgets> + <child> + <placeholder/> + </child> + </object> +</interface> diff --git a/svtools/uiconfig/ui/printersetupdialog.ui b/svtools/uiconfig/ui/printersetupdialog.ui new file mode 100644 index 000000000..354d7a7e4 --- /dev/null +++ b/svtools/uiconfig/ui/printersetupdialog.ui @@ -0,0 +1,273 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Generated with glade 3.20.4 --> +<interface domain="svt"> + <requires lib="gtk+" version="3.18"/> + <object class="GtkDialog" id="PrinterSetupDialog"> + <property name="can_focus">False</property> + <property name="border_width">6</property> + <property name="title" translatable="yes" context="printersetupdialog|PrinterSetupDialog">Printer Setup</property> + <property name="resizable">False</property> + <property name="modal">True</property> + <property name="default_width">0</property> + <property name="default_height">0</property> + <property name="type_hint">dialog</property> + <child internal-child="vbox"> + <object class="GtkBox" id="dialog-vbox1"> + <property name="can_focus">False</property> + <property name="orientation">vertical</property> + <property name="spacing">12</property> + <child internal-child="action_area"> + <object class="GtkButtonBox" id="dialog-action_area1"> + <property name="can_focus">False</property> + <property name="layout_style">end</property> + <child> + <object class="GtkButton" id="help"> + <property name="label">gtk-help</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <property name="use_stock">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">0</property> + <property name="secondary">True</property> + </packing> + </child> + <child> + <object class="GtkButton" id="options"> + <property name="label" translatable="yes" context="printersetupdialog|options">Options...</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">1</property> + </packing> + </child> + <child> + <object class="GtkButton" id="ok"> + <property name="label">gtk-ok</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="can_default">True</property> + <property name="has_default">True</property> + <property name="receives_default">True</property> + <property name="use_stock">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">2</property> + </packing> + </child> + <child> + <object class="GtkButton" id="cancel"> + <property name="label">gtk-cancel</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <property name="use_stock">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">3</property> + </packing> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="pack_type">end</property> + <property name="position">0</property> + </packing> + </child> + <child> + <object class="GtkFrame" id="frame1"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label_xalign">0</property> + <property name="shadow_type">none</property> + <child> + <object class="GtkAlignment" id="alignment1"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="top_padding">6</property> + <property name="left_padding">12</property> + <child> + <object class="GtkGrid" id="grid2"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="hexpand">True</property> + <property name="row_spacing">6</property> + <property name="column_spacing">12</property> + <child> + <object class="GtkLabel" id="label2"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="printersetupdialog|label2">Name:</property> + <property name="use_underline">True</property> + <property name="mnemonic_widget">name</property> + <property name="xalign">1</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">0</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="label3"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="printersetupdialog|label3">Status:</property> + <property name="xalign">1</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">1</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="label4"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="printersetupdialog|label4">Type:</property> + <property name="xalign">1</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">2</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="label5"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="printersetupdialog|label5">Location:</property> + <property name="xalign">1</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">3</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="label6"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="printersetupdialog|label6">Comment:</property> + <property name="xalign">1</property> + </object> + <packing> + <property name="left_attach">0</property> + <property name="top_attach">4</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="status"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="xalign">0</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">1</property> + <property name="width">2</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="type"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="xalign">0</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">2</property> + <property name="width">2</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="comment"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="xalign">0</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">4</property> + <property name="width">2</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="location"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="xalign">0</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">3</property> + <property name="width">2</property> + </packing> + </child> + <child> + <object class="GtkButton" id="properties"> + <property name="label" translatable="yes" context="printersetupdialog|properties">Properties...</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + </object> + <packing> + <property name="left_attach">2</property> + <property name="top_attach">0</property> + </packing> + </child> + <child> + <object class="GtkComboBoxText" id="name"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="hexpand">True</property> + </object> + <packing> + <property name="left_attach">1</property> + <property name="top_attach">0</property> + </packing> + </child> + </object> + </child> + </object> + </child> + <child type="label"> + <object class="GtkLabel" id="label1"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="printersetupdialog|label1">Printer</property> + <attributes> + <attribute name="weight" value="bold"/> + </attributes> + </object> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">1</property> + </packing> + </child> + </object> + </child> + <action-widgets> + <action-widget response="-11">help</action-widget> + <action-widget response="-5">ok</action-widget> + <action-widget response="-6">cancel</action-widget> + </action-widgets> + <child> + <placeholder/> + </child> + </object> +</interface> diff --git a/svtools/uiconfig/ui/querydeletedialog.ui b/svtools/uiconfig/ui/querydeletedialog.ui new file mode 100644 index 000000000..7614528d4 --- /dev/null +++ b/svtools/uiconfig/ui/querydeletedialog.ui @@ -0,0 +1,99 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Generated with glade 3.20.2 --> +<interface domain="svt"> + <requires lib="gtk+" version="3.18"/> + <object class="GtkMessageDialog" id="QueryDeleteDialog"> + <property name="can_focus">False</property> + <property name="title" translatable="yes" context="querydeletedialog|QueryDeleteDialog">Confirm Delete</property> + <property name="resizable">False</property> + <property name="modal">True</property> + <property name="type_hint">dialog</property> + <property name="skip_taskbar_hint">True</property> + <property name="message_type">question</property> + <property name="text" translatable="yes" context="querydeletedialog|QueryDeleteDialog">Are you sure you want to delete the selected data?</property> + <property name="secondary_text" translatable="yes" context="querydeletedialog|QueryDeleteDialog">Entry: %s</property> + <child internal-child="vbox"> + <object class="GtkBox" id="messagedialog-vbox"> + <property name="can_focus">False</property> + <property name="orientation">vertical</property> + <property name="spacing">12</property> + <child internal-child="action_area"> + <object class="GtkButtonBox" id="messagedialog-action_area"> + <property name="can_focus">False</property> + <child> + <object class="GtkButton" id="yes"> + <property name="label" translatable="yes" context="querydeletedialog|yes">_Delete</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="can_default">True</property> + <property name="has_default">True</property> + <property name="receives_default">True</property> + <property name="use_underline">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">0</property> + </packing> + </child> + <child> + <object class="GtkButton" id="all"> + <property name="label" translatable="yes" context="querydeletedialog|all">Delete _All</property> + <property name="visible">True</property> + <property name="sensitive">False</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <property name="use_underline">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">1</property> + </packing> + </child> + <child> + <object class="GtkButton" id="no"> + <property name="label" translatable="yes" context="querydeletedialog|no">Do _Not Delete</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <property name="use_underline">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">2</property> + </packing> + </child> + <child> + <object class="GtkButton" id="cancel"> + <property name="label">gtk-cancel</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <property name="use_stock">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">3</property> + </packing> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="pack_type">end</property> + <property name="position">0</property> + </packing> + </child> + </object> + </child> + <action-widgets> + <action-widget response="-8">yes</action-widget> + <action-widget response="101">all</action-widget> + <action-widget response="-9">no</action-widget> + <action-widget response="-6">cancel</action-widget> + </action-widgets> + </object> +</interface> diff --git a/svtools/uiconfig/ui/restartdialog.ui b/svtools/uiconfig/ui/restartdialog.ui new file mode 100644 index 000000000..6f66108db --- /dev/null +++ b/svtools/uiconfig/ui/restartdialog.ui @@ -0,0 +1,322 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Generated with glade 3.20.4 --> +<interface domain="svt"> + <requires lib="gtk+" version="3.18"/> + <object class="GtkDialog" id="RestartDialog"> + <property name="can_focus">False</property> + <property name="border_width">6</property> + <property name="title" translatable="yes" context="restartdialog|RestartDialog">Restart %PRODUCTNAME</property> + <property name="resizable">False</property> + <property name="modal">True</property> + <property name="default_width">0</property> + <property name="default_height">0</property> + <property name="type_hint">dialog</property> + <child internal-child="vbox"> + <object class="GtkBox" id="dialog-vbox1"> + <property name="can_focus">False</property> + <property name="orientation">vertical</property> + <property name="spacing">12</property> + <child internal-child="action_area"> + <object class="GtkButtonBox" id="dialog-action_area1"> + <property name="can_focus">False</property> + <property name="homogeneous">True</property> + <property name="layout_style">end</property> + <child> + <object class="GtkButton" id="yes"> + <property name="label" translatable="yes" context="restartdialog|yes">Restart Now</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="can_default">True</property> + <property name="has_default">True</property> + <property name="receives_default">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">0</property> + </packing> + </child> + <child> + <object class="GtkButton" id="no"> + <property name="label" translatable="yes" context="restartdialog|no">Restart Later</property> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">1</property> + </packing> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="pack_type">end</property> + <property name="position">0</property> + </packing> + </child> + <child> + <object class="GtkBox" id="box1"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="orientation">vertical</property> + <property name="spacing">12</property> + <child> + <object class="GtkLabel" id="reason_java"> + <property name="can_focus">False</property> + <property name="no_show_all">True</property> + <property name="label" translatable="yes" context="restartdialog|reason_java">For the selected Java runtime environment to work properly, %PRODUCTNAME must be restarted.</property> + <property name="wrap">True</property> + <property name="max_width_chars">30</property> + <property name="xalign">0</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">0</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="reason_mailmerge_install"> + <property name="can_focus">False</property> + <property name="no_show_all">True</property> + <property name="label" translatable="yes" context="restartdialog|reason_mailmerge_install">For mail merge to work properly, %PRODUCTNAME must be restarted.</property> + <property name="wrap">True</property> + <property name="max_width_chars">50</property> + <property name="xalign">0</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">1</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="reason_pdf"> + <property name="can_focus">False</property> + <property name="no_show_all">True</property> + <property name="label" translatable="yes" context="restartdialog|reason_pdf">For the modified default print job format to take effect, %PRODUCTNAME must be restarted.</property> + <property name="wrap">True</property> + <property name="max_width_chars">50</property> + <property name="xalign">0</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">2</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="reason_bibliography_install"> + <property name="can_focus">False</property> + <property name="no_show_all">True</property> + <property name="label" translatable="yes" context="restartdialog|reason_bibliography_install">For the bibliography to work properly, %PRODUCTNAME must be restarted.</property> + <property name="wrap">True</property> + <property name="max_width_chars">50</property> + <property name="xalign">0</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">3</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="reason_assigning_folders"> + <property name="can_focus">False</property> + <property name="no_show_all">True</property> + <property name="label" translatable="yes" context="restartdialog|reason_assigning_folders">For the assigned folders and archives to take effect, %PRODUCTNAME must be restarted.</property> + <property name="wrap">True</property> + <property name="max_width_chars">50</property> + <property name="xalign">0</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">4</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="reason_assigning_javaparameters"> + <property name="can_focus">False</property> + <property name="no_show_all">True</property> + <property name="label" translatable="yes" context="restartdialog|reason_assigning_javaparameters">For the assigned Java parameters to take effect, %PRODUCTNAME must be restarted.</property> + <property name="wrap">True</property> + <property name="max_width_chars">50</property> + <property name="xalign">0</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">5</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="reason_adding_path"> + <property name="can_focus">False</property> + <property name="no_show_all">True</property> + <property name="label" translatable="yes" context="restartdialog|reason_adding_path">For the added path to take effect, %PRODUCTNAME must be restarted.</property> + <property name="wrap">True</property> + <property name="max_width_chars">50</property> + <property name="xalign">0</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">6</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="reason_language_change"> + <property name="can_focus">False</property> + <property name="no_show_all">True</property> + <property name="label" translatable="yes" context="restartdialog|reason_language_change">For the updated language settings to take effect, %PRODUCTNAME must be restarted.</property> + <property name="wrap">True</property> + <property name="max_width_chars">50</property> + <property name="xalign">0</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">7</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="reason_exp_features"> + <property name="can_focus">False</property> + <property name="no_show_all">True</property> + <property name="label" translatable="yes" context="restartdialog|reason_exp_features">For the modified experimental features to take effect, %PRODUCTNAME must be restarted.</property> + <property name="wrap">True</property> + <property name="max_width_chars">50</property> + <property name="xalign">0</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">8</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="reason_extension_install"> + <property name="can_focus">False</property> + <property name="no_show_all">True</property> + <property name="label" translatable="yes" context="restartdialog|reason_extension_install">For the extension to work properly, %PRODUCTNAME must be restarted.</property> + <property name="wrap">True</property> + <property name="max_width_chars">50</property> + <property name="xalign">0</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">9</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="reason_opengl"> + <property name="can_focus">False</property> + <property name="no_show_all">True</property> + <property name="label" translatable="yes" context="restartdialog|reason_opengl">For the OpenGL changes to take effect, %PRODUCTNAME must be restarted.</property> + <property name="wrap">True</property> + <property name="max_width_chars">50</property> + <property name="xalign">0</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">10</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="reason_opencl"> + <property name="can_focus">False</property> + <property name="no_show_all">True</property> + <property name="label" translatable="yes" context="restartdialog|reason_opencl">For the OpenCL changes to take effect, %PRODUCTNAME must be restarted.</property> + <property name="wrap">True</property> + <property name="max_width_chars">50</property> + <property name="xalign">0</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">11</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="reason_threading"> + <property name="can_focus">False</property> + <property name="no_show_all">True</property> + <property name="label" translatable="yes" context="restartdialog|reason_threading">For the multi-threaded calculation changes to take effect, %PRODUCTNAME must be restarted.</property> + <property name="wrap">True</property> + <property name="max_width_chars">50</property> + <property name="xalign">0</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">12</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="reason_mscompatible_formsmenu"> + <property name="can_focus">False</property> + <property name="no_show_all">True</property> + <property name="label" translatable="yes" context="restartdialog|reason_mscompatible_formsmenu">For restructuring the Form menu, %PRODUCTNAME must be restarted.</property> + <property name="wrap">True</property> + <property name="max_width_chars">50</property> + <property name="xalign">0</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">13</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="label"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <property name="label" translatable="yes" context="restartdialog|label">Do you want to restart %PRODUCTNAME now?</property> + <property name="wrap">True</property> + <property name="xalign">0</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">14</property> + </packing> + </child> + <child> + <object class="GtkLabel" id="reason_skia"> + <property name="can_focus">False</property> + <property name="no_show_all">True</property> + <property name="label" translatable="yes" context="restartdialog|reason_skia">For the Skia changes to take effect, %PRODUCTNAME must be restarted.</property> + <property name="wrap">True</property> + <property name="max_width_chars">50</property> + <property name="xalign">0</property> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">15</property> + </packing> + </child> + </object> + <packing> + <property name="expand">False</property> + <property name="fill">True</property> + <property name="position">1</property> + </packing> + </child> + </object> + </child> + <action-widgets> + <action-widget response="-8">yes</action-widget> + <action-widget response="-9">no</action-widget> + </action-widgets> + <child> + <placeholder/> + </child> + </object> +</interface> diff --git a/svtools/util/svt.component b/svtools/util/svt.component new file mode 100644 index 000000000..f840548d9 --- /dev/null +++ b/svtools/util/svt.component @@ -0,0 +1,53 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + --> + +<component loader="com.sun.star.loader.SharedLibrary" environment="@CPPU_ENV@" + prefix="svt" xmlns="http://openoffice.org/2010/uno-components"> + <implementation name="com.sun.star.comp.graphic.GraphicRendererVCL" + constructor="com_sun_star_comp_graphic_GraphicRendererVCL_get_implementation"> + <service name="com.sun.star.graphic.GraphicRendererVCL"/> + </implementation> + <implementation name="com.sun.star.comp.svtools.OAddressBookSourceDialogUno" + constructor="com_sun_star_comp_svtools_OAddressBookSourceDialogUno_get_implementation"> + <service name="com.sun.star.ui.AddressBookSourceDialog"/> + </implementation> + <implementation name="com.sun.star.comp.svtools.uno.Wizard" + constructor="com_sun_star_comp_svtools_uno_Wizard_get_implementation"> + <service name="com.sun.star.ui.dialogs.Wizard"/> + </implementation> + <implementation name="com.sun.star.svtools.SvFilterOptionsDialog" + constructor="com_sun_star_svtools_SvFilterOptionsDialog_get_implementation"> + <service name="com.sun.star.ui.dialogs.FilterOptionsDialog"/> + </implementation> + <implementation name="com.sun.star.comp.svt.FilePicker"> + <service name="com.sun.star.ui.dialogs.FilePicker"/> + </implementation> + <implementation name="com.sun.star.comp.svt.FolderPicker"> + <service name="com.sun.star.ui.dialogs.FolderPicker"/> + </implementation> + <implementation name="com.sun.star.comp.embed.DocumentCloser" + constructor="com_sun_star_comp_embed_DocumentCloser_get_implementation"> + <service name="com.sun.star.embed.DocumentCloser"/> + </implementation> + <implementation name="com.sun.star.comp.embed.HatchWindowFactory" + constructor="com_sun_star_comp_embed_HatchWindowFactory_get_implementation"> + <service name="com.sun.star.comp.embed.HatchWindowFactory"/> + <service name="com.sun.star.embed.HatchWindowFactory"/> + </implementation> +</component> |