aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.gitignore2
-rw-r--r--COPYING678
-rw-r--r--README.md37
-rw-r--r--build/.classpath25
-rw-r--r--build/.project18
-rw-r--r--build/.settings/org.eclipse.jdt.core.prefs12
-rw-r--r--build/.settings/org.eclipse.ltk.core.refactoring.prefs3
-rw-r--r--build/.unoproject12
-rw-r--r--build/META-INF/MANIFEST.MF3
-rw-r--r--build/Zotero.jardesc18
-rwxr-xr-xbuild/buildoxt.sh18
-rw-r--r--build/oxt/Addons.xcu161
-rw-r--r--build/oxt/Addons_AOO4.xcu161
-rw-r--r--build/oxt/META-INF/manifest.xml16
-rw-r--r--build/oxt/Office/UI/BaseWindowState.xcu15
-rw-r--r--build/oxt/Office/UI/BasicIDEWindowState.xcu15
-rw-r--r--build/oxt/Office/UI/CalcWindowState.xcu15
-rw-r--r--build/oxt/Office/UI/DrawWindowState.xcu15
-rw-r--r--build/oxt/Office/UI/ImpressWindowState.xcu15
-rw-r--r--build/oxt/Office/UI/MathWindowState.xcu15
-rw-r--r--build/oxt/Office/UI/StartModuleWindowState.xcu15
-rw-r--r--build/oxt/Office/UI/WriterWindowState.xcu15
-rw-r--r--build/oxt/Zotero/Zotero.xba23
-rw-r--r--build/oxt/Zotero/dialog.xlb3
-rw-r--r--build/oxt/Zotero/script.xlb5
-rw-r--r--build/oxt/description.xml33
-rw-r--r--build/oxt/icons/addEditBibliography_16.pngbin0 -> 651 bytes
-rw-r--r--build/oxt/icons/addEditBibliography_26.pngbin0 -> 1516 bytes
-rw-r--r--build/oxt/icons/addEditCitation_16.pngbin0 -> 417 bytes
-rw-r--r--build/oxt/icons/addEditCitation_26.pngbin0 -> 590 bytes
-rw-r--r--build/oxt/icons/refresh_16.pngbin0 -> 548 bytes
-rw-r--r--build/oxt/icons/refresh_26.pngbin0 -> 832 bytes
-rw-r--r--build/oxt/icons/removeCodes_16.pngbin0 -> 513 bytes
-rw-r--r--build/oxt/icons/removeCodes_26.pngbin0 -> 850 bytes
-rw-r--r--build/oxt/icons/setDocPrefs_16.pngbin0 -> 751 bytes
-rw-r--r--build/oxt/icons/setDocPrefs_26.pngbin0 -> 1071 bytes
-rw-r--r--build/oxt/pkg-desc/pkg-description.txt1
-rw-r--r--build/package.properties0
-rw-r--r--build/source/org/zotero/integration/ooo/comp/Application.java98
-rw-r--r--build/source/org/zotero/integration/ooo/comp/Bookmark.java87
-rw-r--r--build/source/org/zotero/integration/ooo/comp/Comm.java73
-rw-r--r--build/source/org/zotero/integration/ooo/comp/CommCommand.java49
-rw-r--r--build/source/org/zotero/integration/ooo/comp/CommFrame.java30
-rw-r--r--build/source/org/zotero/integration/ooo/comp/CommMessage.java157
-rw-r--r--build/source/org/zotero/integration/ooo/comp/CommReader.java69
-rw-r--r--build/source/org/zotero/integration/ooo/comp/CommServer.java106
-rw-r--r--build/source/org/zotero/integration/ooo/comp/Document.java566
-rw-r--r--build/source/org/zotero/integration/ooo/comp/MarkManager.java117
-rw-r--r--build/source/org/zotero/integration/ooo/comp/Properties.java100
-rw-r--r--build/source/org/zotero/integration/ooo/comp/ReferenceMark.java520
-rw-r--r--build/source/org/zotero/integration/ooo/comp/RegistrationHandler.classes1
-rw-r--r--build/source/org/zotero/integration/ooo/comp/RegistrationHandler.java176
-rw-r--r--build/source/org/zotero/integration/ooo/comp/SaveEventListener.java104
-rw-r--r--build/source/org/zotero/integration/ooo/comp/StringInputStream.java106
-rw-r--r--build/source/org/zotero/integration/ooo/comp/TextTableManager.java74
-rw-r--r--build/source/org/zotero/integration/ooo/comp/ZoteroOpenOfficeIntegrationImpl.java139
-rw-r--r--chrome.manifest14
-rw-r--r--chrome/install.js518
-rw-r--r--chrome/install.xul147
-rw-r--r--chrome/overlay.xul16
-rw-r--r--chrome/preferences.xul27
-rw-r--r--chrome/progress.xul14
-rw-r--r--components/zoteroOpenOfficeIntegration.js511
-rw-r--r--defaults/preferences/zoteroOpenOfficeIntegration.js4
-rw-r--r--install.rdf33
-rw-r--r--resource/installer.jsm399
-rwxr-xr-xscripts/symlink_sdk45
-rw-r--r--update.rdf33
68 files changed, 5682 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..8976281
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+build/bin
+build/lib/libreoffice-sdk
diff --git a/COPYING b/COPYING
new file mode 100644
index 0000000..929288f
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,678 @@
+Zotero is Copyright © 2006, 2007, 2008, 2009, 2010, 2011
+Center for History and New Media, George Mason University,
+Fairfax, Virginia, USA http://zotero.org
+
+The Center for History and New Media distributes the Zotero source code
+under the GNU Affero General Public License, version 3 (AGPLv3). The full text
+of this license is given below.
+
+The Zotero name is a registered trademark of George Mason University.
+See http://zotero.org/trademark for more information.
+
+Third-party copyright in this distribution is noted where applicable.
+
+All rights not expressly granted are reserved.
+
+=========================================================================
+
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU Affero General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time. Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+<http://www.gnu.org/licenses/>.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..d1c33fa
--- /dev/null
+++ b/README.md
@@ -0,0 +1,37 @@
+# Zotero LibreOffice Integration
+
+Zotero LibreOffice Integration comprises extensions for LibreOffice/OpenOffice.org/NeoOffice and Zotero that communicate using local web servers.
+
+## Build Requirements
+
+- [Eclipse](https://www.eclipse.org/downloads/?)
+- [LibreOffice 5.3+](http://www.libreoffice.org/download/download/)
+- [Oracle JDK](http://www.oracle.com/technetwork/java/javase/downloads/index-jsp-138363.html) (currently 1.8.0u121)
+
+LibreOffice SDK is not required.
+
+To build:
+
+1. Run `scripts/symlink_sdk`
+1. Open Eclipse and import this project into your workspace.
+1. Right-click the project in the Eclipse Package Explorer and select "Java Build Path." Click the libraries tab and ensure that all referenced files exist, or else correct the paths.
+1. Double-click Zotero.jardesc. Click "Finish" to build Zotero.jar.
+1. Run `buildoxt.sh` from within the `build` directory to build `install/Zotero_OpenOffice_Integration.oxt`
+1. Install `Zotero_OpenOffice_Integration.oxt` into LibreOffice, either by choosing "Reinstall Extension" from within the Zotero preferences, by installing it manually from within LibreOffice, or by using `unopkg` from the command line.
+
+## Development Starter's Guide
+
+This extension is fairly straightforward. It consists of a LibreOffice UNO based java extension for LibreOffice.
+The [UNO runtime](https://wiki.openoffice.org/wiki/Documentation/DevGuide/OpenOffice.org_Developers_Guide) allows various
+programming languages to interface with a running LibreOffice process. The extension code is initialized by LibreOffice
+and starts execution in [ZoteroOpenOfficeIntegrationImpl.java](https://github.com/zotero/zotero-libreoffice-integration/blob/2183efa/build/source/org/zotero/integration/ooo/comp/ZoteroOpenOfficeIntegrationImpl.java#L40-L40).
+
+Communication between Zotero and LibreOffice is mediated in [zoteroOpenOfficeIntegration.js](https://github.com/zotero/zotero-libreoffice-integration/blob/2183efa/components/zoteroOpenOfficeIntegration.js#L38)
+where a TCP socket is initialized and used for both sending and receiving messages. The complimentary socket connection on the
+LibreOffice extension end is found in [CommServer.java](https://github.com/zotero/zotero-libreoffice-integration/blob/2183efa/build/source/org/zotero/integration/ooo/comp/CommServer.java#L14).
+
+The Java extension code can be debugged directly during runtime. Follow [these](https://help.libreoffice.org/Common/Start_Parameters#Java_Start_parameter)
+instructions to enable debugging in LibreOffice. Attempt performing a Zotero action in LibreOffice, which will freeze the
+process until a debugging client connects. Create a remote debugging configuration in Eclipse and run it. LibreOffice will
+unfreeze. If you add breakpoints in Eclipse they will be triggered freezing the LibreOffice process and allowing you to
+inspect the execution environment. This technique can be used to debug on remote or virtual machines too.
diff --git a/build/.classpath b/build/.classpath
new file mode 100644
index 0000000..4b58960
--- /dev/null
+++ b/build/.classpath
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="src" path="source"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
+ <classpathentry kind="lib" path="lib/jackson-core-2.0.2.jar"/>
+ <classpathentry kind="lib" path="lib/jackson-databind-2.0.2.jar"/>
+ <classpathentry kind="lib" path="lib/jna.jar"/>
+ <classpathentry kind="lib" path="lib/jackson-annotations-2.0.2.jar"/>
+ <classpathentry kind="lib" path="lib/libreoffice-sdk/commonwizards.jar"/>
+ <classpathentry kind="lib" path="lib/libreoffice-sdk/form.jar"/>
+ <classpathentry kind="lib" path="lib/libreoffice-sdk/query.jar"/>
+ <classpathentry kind="lib" path="lib/libreoffice-sdk/report.jar"/>
+ <classpathentry kind="lib" path="lib/libreoffice-sdk/ScriptFramework.jar"/>
+ <classpathentry kind="lib" path="lib/libreoffice-sdk/ScriptProviderForJava.jar"/>
+ <classpathentry kind="lib" path="lib/libreoffice-sdk/table.jar"/>
+ <classpathentry kind="lib" path="lib/libreoffice-sdk/unoil.jar"/>
+ <classpathentry kind="lib" path="lib/libreoffice-sdk/xmerge.jar"/>
+ <classpathentry kind="lib" path="lib/libreoffice-sdk/XMergeBridge.jar"/>
+ <classpathentry kind="lib" path="lib/libreoffice-sdk/java_uno.jar"/>
+ <classpathentry kind="lib" path="lib/libreoffice-sdk/juh.jar"/>
+ <classpathentry kind="lib" path="lib/libreoffice-sdk/jurt.jar"/>
+ <classpathentry kind="lib" path="lib/libreoffice-sdk/ridl.jar"/>
+ <classpathentry kind="lib" path="lib/libreoffice-sdk/unoloader.jar"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/build/.project b/build/.project
new file mode 100644
index 0000000..6396949
--- /dev/null
+++ b/build/.project
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>Zotero OpenOffice Integration</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.openoffice.ide.eclipse.core.unonature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
diff --git a/build/.settings/org.eclipse.jdt.core.prefs b/build/.settings/org.eclipse.jdt.core.prefs
new file mode 100644
index 0000000..b232e36
--- /dev/null
+++ b/build/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,12 @@
+#Sat Mar 05 02:28:35 PST 2011
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
+org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
+org.eclipse.jdt.core.compiler.compliance=1.5
+org.eclipse.jdt.core.compiler.debug.lineNumber=generate
+org.eclipse.jdt.core.compiler.debug.localVariable=generate
+org.eclipse.jdt.core.compiler.debug.sourceFile=generate
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.5
diff --git a/build/.settings/org.eclipse.ltk.core.refactoring.prefs b/build/.settings/org.eclipse.ltk.core.refactoring.prefs
new file mode 100644
index 0000000..e26cdcd
--- /dev/null
+++ b/build/.settings/org.eclipse.ltk.core.refactoring.prefs
@@ -0,0 +1,3 @@
+#Tue Aug 11 17:24:08 PDT 2009
+eclipse.preferences.version=1
+org.eclipse.ltk.core.refactoring.enable.project.refactoring.history=false
diff --git a/build/.unoproject b/build/.unoproject
new file mode 100644
index 0000000..14682c6
--- /dev/null
+++ b/build/.unoproject
@@ -0,0 +1,12 @@
+#UNO project configuration file
+#Thu Jun 21 19:38:57 EDT 2012
+project.srcdir=/source
+regclassname=org.zotero.integration.ooo.comp.RegistrationHandler
+javaversion=java4
+project.sdk=340m1
+project.ooo=LibreOffice 3.4
+project.implementation=comp
+project.build=build
+project.language=Java
+project.prefix=org.zotero.integration.ooo
+project.idl=/idl
diff --git a/build/META-INF/MANIFEST.MF b/build/META-INF/MANIFEST.MF
new file mode 100644
index 0000000..107c90a
--- /dev/null
+++ b/build/META-INF/MANIFEST.MF
@@ -0,0 +1,3 @@
+Manifest-Version: 1.0
+RegistrationClassName: org.zotero.integration.ooo.comp.RegistrationHandler
+Class-Path: external_jars/jackson-core-2.0.2.jar external_jars/jackson-databind-2.0.2.jar external_jars/jackson-annotations-2.0.2.jar external_jars/jna.jar
diff --git a/build/Zotero.jardesc b/build/Zotero.jardesc
new file mode 100644
index 0000000..d0b6f2a
--- /dev/null
+++ b/build/Zotero.jardesc
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<jardesc>
+ <jar path="Zotero OpenOffice Integration/oxt/Zotero.jar"/>
+ <options buildIfNeeded="true" compress="true" descriptionLocation="/Zotero OpenOffice Integration/Zotero.jardesc" exportErrors="true" exportWarnings="true" includeDirectoryEntries="false" overwrite="false" saveDescription="true" storeRefactorings="false" useSourceFolders="false"/>
+ <storedRefactorings deprecationInfo="true" structuralOnly="false"/>
+ <selectedProjects/>
+ <manifest generateManifest="false" manifestLocation="/Zotero OpenOffice Integration/META-INF/MANIFEST.MF" manifestVersion="1.0" reuseManifest="true" saveManifest="true" usesManifest="true">
+ <sealing sealJar="true">
+ <packagesToSeal>
+ <package handleIdentifier="=Zotero OpenOffice.org Integration/source&lt;org.zotero.integration.ooo.comp"/>
+ </packagesToSeal>
+ <packagesToUnSeal/>
+ </sealing>
+ </manifest>
+ <selectedElements exportClassFiles="true" exportJavaFiles="false" exportOutputFolder="false">
+ <javaElement handleIdentifier="=Zotero OpenOffice Integration/source"/>
+ </selectedElements>
+</jardesc>
diff --git a/build/buildoxt.sh b/build/buildoxt.sh
new file mode 100755
index 0000000..f151033
--- /dev/null
+++ b/build/buildoxt.sh
@@ -0,0 +1,18 @@
+#!/bin/bash
+
+CWD="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
+
+# Copy external jars
+mkdir -p $CWD/oxt/external_jars
+cp -r $CWD/lib/*jar $CWD/oxt/external_jars
+
+# Fix MANIFEST.MF
+zip $CWD/oxt/Zotero.jar $CWD/META-INF/MANIFEST.MF
+
+# Zip up oxt
+cd $CWD/oxt
+rm -f ../../install/Zotero_OpenOffice_Integration.oxt
+zip -r ../../install/Zotero_OpenOffice_Integration.oxt * -x \*/.svn/\* -x \*/.DS_Store
+
+# Clean up
+rm -rf Zotero.jar external_jars \ No newline at end of file
diff --git a/build/oxt/Addons.xcu b/build/oxt/Addons.xcu
new file mode 100644
index 0000000..7cc0ed2
--- /dev/null
+++ b/build/oxt/Addons.xcu
@@ -0,0 +1,161 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<oor:component-data xmlns:oor="http://openoffice.org/2001/registry" xmlns:xs="http://www.w3.org/2001/XMLSchema" oor:name="Addons" oor:package="org.openoffice.Office">
+ <node oor:name="AddonUI">
+
+ <node oor:name="OfficeToolBar">
+ <node oor:name="Zotero.OfficeToolBar" oor:op="replace">
+ <prop oor:name="Title" oor:type="xs:string">
+ <value>Zotero</value>
+ </prop>
+ <node oor:name="m1" oor:op="replace">
+ <prop oor:name="Context" oor:type="xs:string">
+ <value>com.sun.star.text.TextDocument, com.sun.star.text.GlobalDocument</value>
+ </prop>
+ <prop oor:name="URL" oor:type="xs:string">
+ <value>service:org.zotero.integration.ooo.ZoteroOpenOfficeIntegration?addEditCitation</value>
+ </prop>
+ <prop oor:name="Title" oor:type="xs:string">
+ <value>Add/Edit Citation</value>
+ </prop>
+ <prop oor:name="Target" oor:type="xs:string">
+ <value>_self</value>
+ </prop>
+ </node>
+ <node oor:name="m3" oor:op="replace">
+ <prop oor:name="Context" oor:type="xs:string">
+ <value>com.sun.star.text.TextDocument, com.sun.star.text.GlobalDocument</value>
+ </prop>
+ <prop oor:name="URL" oor:type="xs:string">
+ <value>service:org.zotero.integration.ooo.ZoteroOpenOfficeIntegration?addEditBibliography</value>
+ </prop>
+ <prop oor:name="Title" oor:type="xs:string">
+ <value>Add/Edit Bibliography</value>
+ </prop>
+ <prop oor:name="Target" oor:type="xs:string">
+ <value>_self</value>
+ </prop>
+ </node>
+ <node oor:name="m5" oor:op="replace">
+ <prop oor:name="Context" oor:type="xs:string">
+ <value>com.sun.star.text.TextDocument, com.sun.star.text.GlobalDocument</value>
+ </prop>
+ <prop oor:name="URL" oor:type="xs:string">
+ <value>private:separator</value>
+ </prop>
+ </node>
+ <node oor:name="m6" oor:op="replace">
+ <prop oor:name="Context" oor:type="xs:string">
+ <value>com.sun.star.text.TextDocument, com.sun.star.text.GlobalDocument</value>
+ </prop>
+ <prop oor:name="URL" oor:type="xs:string">
+ <value>service:org.zotero.integration.ooo.ZoteroOpenOfficeIntegration?refresh</value>
+ </prop>
+ <prop oor:name="Title" oor:type="xs:string">
+ <value>Refresh</value>
+ </prop>
+ <prop oor:name="Target" oor:type="xs:string">
+ <value>_self</value>
+ </prop>
+ </node>
+ <node oor:name="m7" oor:op="replace">
+ <prop oor:name="Context" oor:type="xs:string">
+ <value>com.sun.star.text.TextDocument, com.sun.star.text.GlobalDocument</value>
+ </prop>
+ <prop oor:name="URL" oor:type="xs:string">
+ <value>service:org.zotero.integration.ooo.ZoteroOpenOfficeIntegration?setDocPrefs</value>
+ </prop>
+ <prop oor:name="Title" oor:type="xs:string">
+ <value>Set Document Preferences</value>
+ </prop>
+ <prop oor:name="Target" oor:type="xs:string">
+ <value>_self</value>
+ </prop>
+ </node>
+ <node oor:name="m8" oor:op="replace">
+ <prop oor:name="Context" oor:type="xs:string">
+ <value>com.sun.star.text.TextDocument, com.sun.star.text.GlobalDocument</value>
+ </prop>
+ <prop oor:name="URL" oor:type="xs:string">
+ <value>service:org.zotero.integration.ooo.ZoteroOpenOfficeIntegration?removeCodes</value>
+ </prop>
+ <prop oor:name="Title" oor:type="xs:string">
+ <value>Unlink Citations</value>
+ </prop>
+ <prop oor:name="Target" oor:type="xs:string">
+ <value>_self</value>
+ </prop>
+ </node>
+ </node>
+ </node>
+
+ <node oor:name="Images">
+ <node oor:name="Zotero.Images.addEditCitation" oor:op="replace">
+ <prop oor:name="URL" oor:type="xs:string">
+ <value>service:org.zotero.integration.ooo.ZoteroOpenOfficeIntegration?addEditCitation</value>
+ </prop>
+ <node oor:name="UserDefinedImages">
+ <prop oor:name="ImageSmallURL">
+ <value>%origin%/icons/addEditCitation_16.png</value>
+ </prop>
+ <prop oor:name="ImageBigURL">
+ <value>%origin%/icons/addEditCitation_26.png</value>
+ </prop>
+ </node>
+ </node>
+ <node oor:name="Zotero.Images.addEditBibliography" oor:op="replace">
+ <prop oor:name="URL" oor:type="xs:string">
+ <value>service:org.zotero.integration.ooo.ZoteroOpenOfficeIntegration?addEditBibliography</value>
+ </prop>
+ <node oor:name="UserDefinedImages">
+ <prop oor:name="ImageSmallURL">
+ <value>%origin%/icons/addEditBibliography_16.png</value>
+ </prop>
+ <prop oor:name="ImageBigURL">
+ <value>%origin%/icons/addEditBibliography_26.png</value>
+ </prop>
+ </node>
+ </node>
+ <node oor:name="Zotero.Images.setDocPrefs" oor:op="replace">
+ <prop oor:name="URL" oor:type="xs:string">
+ <value>service:org.zotero.integration.ooo.ZoteroOpenOfficeIntegration?setDocPrefs</value>
+ </prop>
+ <node oor:name="UserDefinedImages">
+ <prop oor:name="ImageSmallURL">
+ <value>%origin%/icons/setDocPrefs_16.png</value>
+ </prop>
+ <prop oor:name="ImageBigURL">
+ <value>%origin%/icons/setDocPrefs_26.png</value>
+ </prop>
+ </node>
+ </node>
+ <node oor:name="Zotero.Images.refresh" oor:op="replace">
+ <prop oor:name="URL" oor:type="xs:string">
+ <value>service:org.zotero.integration.ooo.ZoteroOpenOfficeIntegration?refresh</value>
+ </prop>
+ <node oor:name="UserDefinedImages">
+ <prop oor:name="ImageSmallURL">
+ <value>%origin%/icons/refresh_16.png</value>
+ </prop>
+ <prop oor:name="ImageBigURL">
+ <value>%origin%/icons/refresh_26.png</value>
+ </prop>
+ </node>
+ </node>
+ <node oor:name="Zotero.Images.removeCodes" oor:op="replace">
+ <prop oor:name="URL" oor:type="xs:string">
+ <value>service:org.zotero.integration.ooo.ZoteroOpenOfficeIntegration?removeCodes</value>
+ </prop>
+ <node oor:name="UserDefinedImages">
+ <prop oor:name="ImageSmallURL">
+ <value>%origin%/icons/removeCodes_16.png</value>
+ </prop>
+ <prop oor:name="ImageBigURL">
+ <value>%origin%/icons/removeCodes_26.png</value>
+ </prop>
+ </node>
+ </node>
+ </node>
+
+ </node>
+</oor:component-data>
+
diff --git a/build/oxt/Addons_AOO4.xcu b/build/oxt/Addons_AOO4.xcu
new file mode 100644
index 0000000..33f68ce
--- /dev/null
+++ b/build/oxt/Addons_AOO4.xcu
@@ -0,0 +1,161 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<oor:component-data xmlns:oor="http://openoffice.org/2001/registry" xmlns:xs="http://www.w3.org/2001/XMLSchema" oor:name="Addons" oor:package="org.openoffice.Office">
+ <node oor:name="AddonUI">
+
+ <node oor:name="OfficeToolBar">
+ <node oor:name="Zotero.OfficeToolBar.AOO4" oor:op="replace">
+ <prop oor:name="Title" oor:type="xs:string">
+ <value xml:lang="en-US">Zotero</value>
+ </prop>
+ <node oor:name="ToolBarItems">
+ <node oor:name="m1" oor:op="replace">
+ <prop oor:name="Context" oor:type="xs:string">
+ <value>com.sun.star.text.TextDocument, com.sun.star.text.GlobalDocument</value>
+ </prop>
+ <prop oor:name="URL" oor:type="xs:string">
+ <value>service:org.zotero.integration.ooo.ZoteroOpenOfficeIntegration?addEditCitation</value>
+ </prop>
+ <prop oor:name="Title" oor:type="xs:string">
+ <value>Add/Edit Citation</value>
+ </prop>
+ <prop oor:name="Target" oor:type="xs:string">
+ <value>_self</value>
+ </prop>
+ </node>
+ <node oor:name="m3" oor:op="replace">
+ <prop oor:name="Context" oor:type="xs:string">
+ <value>com.sun.star.text.TextDocument, com.sun.star.text.GlobalDocument</value>
+ </prop>
+ <prop oor:name="URL" oor:type="xs:string">
+ <value>service:org.zotero.integration.ooo.ZoteroOpenOfficeIntegration?addEditBibliography</value>
+ </prop>
+ <prop oor:name="Title" oor:type="xs:string">
+ <value>Add/Edit Bibliography</value>
+ </prop>
+ <prop oor:name="Target" oor:type="xs:string">
+ <value>_self</value>
+ </prop>
+ </node>
+ <node oor:name="m5" oor:op="replace">
+ <prop oor:name="Context" oor:type="xs:string">
+ <value>com.sun.star.text.TextDocument, com.sun.star.text.GlobalDocument</value>
+ </prop>
+ <prop oor:name="URL" oor:type="xs:string">
+ <value>private:separator</value>
+ </prop>
+ </node>
+ <node oor:name="m6" oor:op="replace">
+ <prop oor:name="Context" oor:type="xs:string">
+ <value>com.sun.star.text.TextDocument, com.sun.star.text.GlobalDocument</value>
+ </prop>
+ <prop oor:name="URL" oor:type="xs:string">
+ <value>service:org.zotero.integration.ooo.ZoteroOpenOfficeIntegration?refresh</value>
+ </prop>
+ <prop oor:name="Title" oor:type="xs:string">
+ <value>Refresh</value>
+ </prop>
+ <prop oor:name="Target" oor:type="xs:string">
+ <value>_self</value>
+ </prop>
+ </node>
+ <node oor:name="m7" oor:op="replace">
+ <prop oor:name="Context" oor:type="xs:string">
+ <value>com.sun.star.text.TextDocument, com.sun.star.text.GlobalDocument</value>
+ </prop>
+ <prop oor:name="URL" oor:type="xs:string">
+ <value>service:org.zotero.integration.ooo.ZoteroOpenOfficeIntegration?setDocPrefs</value>
+ </prop>
+ <prop oor:name="Title" oor:type="xs:string">
+ <value>Set Document Preferences</value>
+ </prop>
+ <prop oor:name="Target" oor:type="xs:string">
+ <value>_self</value>
+ </prop>
+ </node>
+ <node oor:name="m8" oor:op="replace">
+ <prop oor:name="Context" oor:type="xs:string">
+ <value>com.sun.star.text.TextDocument, com.sun.star.text.GlobalDocument</value>
+ </prop>
+ <prop oor:name="URL" oor:type="xs:string">
+ <value>service:org.zotero.integration.ooo.ZoteroOpenOfficeIntegration?removeCodes</value>
+ </prop>
+ <prop oor:name="Title" oor:type="xs:string">
+ <value>Unlink Citations</value>
+ </prop>
+ <prop oor:name="Target" oor:type="xs:string">
+ <value>_self</value>
+ </prop>
+ </node>
+ </node>
+ </node>
+ </node>
+
+ <node oor:name="Images">
+ <node oor:name="Zotero.Images.addEditCitation" oor:op="replace">
+ <prop oor:name="URL" oor:type="xs:string">
+ <value>service:org.zotero.integration.ooo.ZoteroOpenOfficeIntegration?addEditCitation</value>
+ </prop>
+ <node oor:name="UserDefinedImages">
+ <prop oor:name="ImageSmallURL">
+ <value>%origin%/icons/addEditCitation_16.png</value>
+ </prop>
+ <prop oor:name="ImageBigURL">
+ <value>%origin%/icons/addEditCitation_26.png</value>
+ </prop>
+ </node>
+ </node>
+ <node oor:name="Zotero.Images.addEditBibliography" oor:op="replace">
+ <prop oor:name="URL" oor:type="xs:string">
+ <value>service:org.zotero.integration.ooo.ZoteroOpenOfficeIntegration?addEditBibliography</value>
+ </prop>
+ <node oor:name="UserDefinedImages">
+ <prop oor:name="ImageSmallURL">
+ <value>%origin%/icons/addEditBibliography_16.png</value>
+ </prop>
+ <prop oor:name="ImageBigURL">
+ <value>%origin%/icons/addEditBibliography_26.png</value>
+ </prop>
+ </node>
+ </node>
+ <node oor:name="Zotero.Images.setDocPrefs" oor:op="replace">
+ <prop oor:name="URL" oor:type="xs:string">
+ <value>service:org.zotero.integration.ooo.ZoteroOpenOfficeIntegration?setDocPrefs</value>
+ </prop>
+ <node oor:name="UserDefinedImages">
+ <prop oor:name="ImageSmallURL">
+ <value>%origin%/icons/setDocPrefs_16.png</value>
+ </prop>
+ <prop oor:name="ImageBigURL">
+ <value>%origin%/icons/setDocPrefs_26.png</value>
+ </prop>
+ </node>
+ </node>
+ <node oor:name="Zotero.Images.refresh" oor:op="replace">
+ <prop oor:name="URL" oor:type="xs:string">
+ <value>service:org.zotero.integration.ooo.ZoteroOpenOfficeIntegration?refresh</value>
+ </prop>
+ <node oor:name="UserDefinedImages">
+ <prop oor:name="ImageSmallURL">
+ <value>%origin%/icons/refresh_16.png</value>
+ </prop>
+ <prop oor:name="ImageBigURL">
+ <value>%origin%/icons/refresh_26.png</value>
+ </prop>
+ </node>
+ </node>
+ <node oor:name="Zotero.Images.removeCodes" oor:op="replace">
+ <prop oor:name="URL" oor:type="xs:string">
+ <value>service:org.zotero.integration.ooo.ZoteroOpenOfficeIntegration?removeCodes</value>
+ </prop>
+ <node oor:name="UserDefinedImages">
+ <prop oor:name="ImageSmallURL">
+ <value>%origin%/icons/removeCodes_16.png</value>
+ </prop>
+ <prop oor:name="ImageBigURL">
+ <value>%origin%/icons/removeCodes_26.png</value>
+ </prop>
+ </node>
+ </node>
+ </node>
+ </node>
+</oor:component-data>
diff --git a/build/oxt/META-INF/manifest.xml b/build/oxt/META-INF/manifest.xml
new file mode 100644
index 0000000..1c5d014
--- /dev/null
+++ b/build/oxt/META-INF/manifest.xml
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<manifest:manifest xmlns:manifest="http://openoffice.org/2001/manifest">
+ <manifest:file-entry manifest:full-path="pkg-desc/pkg-description.txt" manifest:media-type="application/vnd.sun.star.package-bundle-description"/>
+ <manifest:file-entry manifest:full-path="Addons.xcu" manifest:media-type="application/vnd.sun.star.configuration-data"/>
+ <manifest:file-entry manifest:full-path="Addons_AOO4.xcu" manifest:media-type="application/vnd.sun.star.configuration-data"/>
+ <manifest:file-entry manifest:full-path="Zotero/" manifest:media-type="application/vnd.sun.star.basic-library"/>
+ <manifest:file-entry manifest:full-path="Office/UI/CalcWindowState.xcu" manifest:media-type="application/vnd.sun.star.configuration-data"/>
+ <manifest:file-entry manifest:full-path="Office/UI/StartModuleWindowState.xcu" manifest:media-type="application/vnd.sun.star.configuration-data"/>
+ <manifest:file-entry manifest:full-path="Office/UI/WriterWindowState.xcu" manifest:media-type="application/vnd.sun.star.configuration-data"/>
+ <manifest:file-entry manifest:full-path="Office/UI/BaseWindowState.xcu" manifest:media-type="application/vnd.sun.star.configuration-data"/>
+ <manifest:file-entry manifest:full-path="Office/UI/ImpressWindowState.xcu" manifest:media-type="application/vnd.sun.star.configuration-data"/>
+ <manifest:file-entry manifest:full-path="Office/UI/BasicIDEWindowState.xcu" manifest:media-type="application/vnd.sun.star.configuration-data"/>
+ <manifest:file-entry manifest:full-path="Office/UI/MathWindowState.xcu" manifest:media-type="application/vnd.sun.star.configuration-data"/>
+ <manifest:file-entry manifest:full-path="Office/UI/DrawWindowState.xcu" manifest:media-type="application/vnd.sun.star.configuration-data"/>
+ <manifest:file-entry manifest:full-path="Zotero.jar" manifest:media-type="application/vnd.sun.star.uno-component;type=Java"/>
+</manifest:manifest>
diff --git a/build/oxt/Office/UI/BaseWindowState.xcu b/build/oxt/Office/UI/BaseWindowState.xcu
new file mode 100644
index 0000000..b682240
--- /dev/null
+++ b/build/oxt/Office/UI/BaseWindowState.xcu
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<oor:component-data xmlns:oor="http://openoffice.org/2001/registry"
+ xmlns:xs="http://www.w3.org/2001/XMLSchema"
+ oor:name="BaseWindowState"
+ oor:package="org.openoffice.Office.UI">
+ <node oor:name="UIElements">
+ <node oor:name="States">
+ <node oor:name="private:resource/toolbar/addon_Zotero.OfficeToolBar" oor:op="replace">
+ <prop oor:name="UIName" oor:type="xs:string">
+ <value>Zotero</value>
+ </prop>
+ </node>
+ </node>
+ </node>
+</oor:component-data>
diff --git a/build/oxt/Office/UI/BasicIDEWindowState.xcu b/build/oxt/Office/UI/BasicIDEWindowState.xcu
new file mode 100644
index 0000000..564555f
--- /dev/null
+++ b/build/oxt/Office/UI/BasicIDEWindowState.xcu
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<oor:component-data xmlns:oor="http://openoffice.org/2001/registry"
+ xmlns:xs="http://www.w3.org/2001/XMLSchema"
+ oor:name="BasicIDEWindowState"
+ oor:package="org.openoffice.Office.UI">
+ <node oor:name="UIElements">
+ <node oor:name="States">
+ <node oor:name="private:resource/toolbar/addon_Zotero.OfficeToolBar" oor:op="replace">
+ <prop oor:name="UIName" oor:type="xs:string">
+ <value>Zotero</value>
+ </prop>
+ </node>
+ </node>
+ </node>
+</oor:component-data>
diff --git a/build/oxt/Office/UI/CalcWindowState.xcu b/build/oxt/Office/UI/CalcWindowState.xcu
new file mode 100644
index 0000000..16c4720
--- /dev/null
+++ b/build/oxt/Office/UI/CalcWindowState.xcu
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<oor:component-data xmlns:oor="http://openoffice.org/2001/registry"
+ xmlns:xs="http://www.w3.org/2001/XMLSchema"
+ oor:name="CalcWindowState"
+ oor:package="org.openoffice.Office.UI">
+ <node oor:name="UIElements">
+ <node oor:name="States">
+ <node oor:name="private:resource/toolbar/addon_Zotero.OfficeToolBar" oor:op="replace">
+ <prop oor:name="UIName" oor:type="xs:string">
+ <value>Zotero</value>
+ </prop>
+ </node>
+ </node>
+ </node>
+</oor:component-data>
diff --git a/build/oxt/Office/UI/DrawWindowState.xcu b/build/oxt/Office/UI/DrawWindowState.xcu
new file mode 100644
index 0000000..088d931
--- /dev/null
+++ b/build/oxt/Office/UI/DrawWindowState.xcu
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<oor:component-data xmlns:oor="http://openoffice.org/2001/registry"
+ xmlns:xs="http://www.w3.org/2001/XMLSchema"
+ oor:name="DrawWindowState"
+ oor:package="org.openoffice.Office.UI">
+ <node oor:name="UIElements">
+ <node oor:name="States">
+ <node oor:name="private:resource/toolbar/addon_Zotero.OfficeToolBar" oor:op="replace">
+ <prop oor:name="UIName" oor:type="xs:string">
+ <value>Zotero</value>
+ </prop>
+ </node>
+ </node>
+ </node>
+</oor:component-data>
diff --git a/build/oxt/Office/UI/ImpressWindowState.xcu b/build/oxt/Office/UI/ImpressWindowState.xcu
new file mode 100644
index 0000000..924652c
--- /dev/null
+++ b/build/oxt/Office/UI/ImpressWindowState.xcu
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<oor:component-data xmlns:oor="http://openoffice.org/2001/registry"
+ xmlns:xs="http://www.w3.org/2001/XMLSchema"
+ oor:name="ImpressWindowState"
+ oor:package="org.openoffice.Office.UI">
+ <node oor:name="UIElements">
+ <node oor:name="States">
+ <node oor:name="private:resource/toolbar/addon_Zotero.OfficeToolBar" oor:op="replace">
+ <prop oor:name="UIName" oor:type="xs:string">
+ <value>Zotero</value>
+ </prop>
+ </node>
+ </node>
+ </node>
+</oor:component-data>
diff --git a/build/oxt/Office/UI/MathWindowState.xcu b/build/oxt/Office/UI/MathWindowState.xcu
new file mode 100644
index 0000000..007e948
--- /dev/null
+++ b/build/oxt/Office/UI/MathWindowState.xcu
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<oor:component-data xmlns:oor="http://openoffice.org/2001/registry"
+ xmlns:xs="http://www.w3.org/2001/XMLSchema"
+ oor:name="MathWindowState"
+ oor:package="org.openoffice.Office.UI">
+ <node oor:name="UIElements">
+ <node oor:name="States">
+ <node oor:name="private:resource/toolbar/addon_Zotero.OfficeToolBar" oor:op="replace">
+ <prop oor:name="UIName" oor:type="xs:string">
+ <value>Zotero</value>
+ </prop>
+ </node>
+ </node>
+ </node>
+</oor:component-data>
diff --git a/build/oxt/Office/UI/StartModuleWindowState.xcu b/build/oxt/Office/UI/StartModuleWindowState.xcu
new file mode 100644
index 0000000..e79cdcd
--- /dev/null
+++ b/build/oxt/Office/UI/StartModuleWindowState.xcu
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<oor:component-data xmlns:oor="http://openoffice.org/2001/registry"
+ xmlns:xs="http://www.w3.org/2001/XMLSchema"
+ oor:name="StartModuleWindowState"
+ oor:package="org.openoffice.Office.UI">
+ <node oor:name="UIElements">
+ <node oor:name="States">
+ <node oor:name="private:resource/toolbar/addon_Zotero.OfficeToolBar" oor:op="replace">
+ <prop oor:name="UIName" oor:type="xs:string">
+ <value>Zotero</value>
+ </prop>
+ </node>
+ </node>
+ </node>
+</oor:component-data>
diff --git a/build/oxt/Office/UI/WriterWindowState.xcu b/build/oxt/Office/UI/WriterWindowState.xcu
new file mode 100644
index 0000000..e411513
--- /dev/null
+++ b/build/oxt/Office/UI/WriterWindowState.xcu
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<oor:component-data xmlns:oor="http://openoffice.org/2001/registry"
+ xmlns:xs="http://www.w3.org/2001/XMLSchema"
+ oor:name="WriterWindowState"
+ oor:package="org.openoffice.Office.UI">
+ <node oor:name="UIElements">
+ <node oor:name="States">
+ <node oor:name="private:resource/toolbar/addon_Zotero.OfficeToolBar" oor:op="replace">
+ <prop oor:name="UIName" oor:type="xs:string">
+ <value>Zotero</value>
+ </prop>
+ </node>
+ </node>
+ </node>
+</oor:component-data>
diff --git a/build/oxt/Zotero/Zotero.xba b/build/oxt/Zotero/Zotero.xba
new file mode 100644
index 0000000..33a73d2
--- /dev/null
+++ b/build/oxt/Zotero/Zotero.xba
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE script:module PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "module.dtd">
+<script:module xmlns:script="http://openoffice.org/2000/script" script:name="Zotero" script:language="StarBasic">
+Sub ZoteroAddEditBibliography()
+ createUnoService(&quot;org.zotero.integration.ooo.ZoteroOpenOfficeIntegration&quot;).trigger(&quot;addEditBibliography&quot;)
+End Sub
+
+Sub ZoteroAddEditCitation()
+ createUnoService(&quot;org.zotero.integration.ooo.ZoteroOpenOfficeIntegration&quot;).trigger(&quot;addEditCitation&quot;)
+End Sub
+
+Sub ZoteroRefresh()
+ createUnoService(&quot;org.zotero.integration.ooo.ZoteroOpenOfficeIntegration&quot;).trigger(&quot;refresh&quot;)
+End Sub
+
+Sub ZoteroRemoveCodes()
+ createUnoService(&quot;org.zotero.integration.ooo.ZoteroOpenOfficeIntegration&quot;).trigger(&quot;removeCodes&quot;)
+End Sub
+
+Sub ZoteroSetDocPrefs()
+ createUnoService(&quot;org.zotero.integration.ooo.ZoteroOpenOfficeIntegration&quot;).trigger(&quot;setDocPrefs&quot;)
+End Sub
+</script:module>
diff --git a/build/oxt/Zotero/dialog.xlb b/build/oxt/Zotero/dialog.xlb
new file mode 100644
index 0000000..8d36908
--- /dev/null
+++ b/build/oxt/Zotero/dialog.xlb
@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE library:library PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "library.dtd">
+<library:library xmlns:library="http://openoffice.org/2000/library" library:name="Zotero" library:readonly="false" library:passwordprotected="false"/> \ No newline at end of file
diff --git a/build/oxt/Zotero/script.xlb b/build/oxt/Zotero/script.xlb
new file mode 100644
index 0000000..21fbe25
--- /dev/null
+++ b/build/oxt/Zotero/script.xlb
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE library:library PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "library.dtd">
+<library:library xmlns:library="http://openoffice.org/2000/library" library:name="Zotero" library:readonly="false" library:passwordprotected="false">
+ <library:element library:name="Zotero"/>
+</library:library> \ No newline at end of file
diff --git a/build/oxt/description.xml b/build/oxt/description.xml
new file mode 100644
index 0000000..2f156cc
--- /dev/null
+++ b/build/oxt/description.xml
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<description xmlns="http://openoffice.org/extensions/description/2006"
+xmlns:d="http://openoffice.org/extensions/description/2006"
+xmlns:xlink="http://www.w3.org/1999/xlink">
+
+ <version value="5.0.6"/>
+
+ <identifier value="org.Zotero.integration.openoffice" />
+
+ <dependencies>
+ <OpenOffice.org-minimal-version value="4.1" d:name="OpenOffice.org 4.1"/>
+ </dependencies>
+
+ <update-information>
+ <src xlink:href="https://www.zotero.org/download/update-OOo.xml" />
+ </update-information>
+
+ <publisher>
+ <name xlink:href="https://www.zotero.org/" lang="en">Corporation for Digital Scholarship</name>
+ </publisher>
+
+ <release-notes>
+ <src xlink:href="https://www.zotero.org/documentation/changelog" lang="en" />
+ </release-notes>
+
+ <display-name>
+ <name lang="en">Zotero LibreOffice Integration</name>
+ </display-name>
+
+ <extension-description>
+ <src xlink:href="pkg-desc/pkg-description.txt" lang="en" />
+ </extension-description>
+</description>
diff --git a/build/oxt/icons/addEditBibliography_16.png b/build/oxt/icons/addEditBibliography_16.png
new file mode 100644
index 0000000..90a0bbb
--- /dev/null
+++ b/build/oxt/icons/addEditBibliography_16.png
Binary files differ
diff --git a/build/oxt/icons/addEditBibliography_26.png b/build/oxt/icons/addEditBibliography_26.png
new file mode 100644
index 0000000..eee4c68
--- /dev/null
+++ b/build/oxt/icons/addEditBibliography_26.png
Binary files differ
diff --git a/build/oxt/icons/addEditCitation_16.png b/build/oxt/icons/addEditCitation_16.png
new file mode 100644
index 0000000..2b0b86e
--- /dev/null
+++ b/build/oxt/icons/addEditCitation_16.png
Binary files differ
diff --git a/build/oxt/icons/addEditCitation_26.png b/build/oxt/icons/addEditCitation_26.png
new file mode 100644
index 0000000..faa694e
--- /dev/null
+++ b/build/oxt/icons/addEditCitation_26.png
Binary files differ
diff --git a/build/oxt/icons/refresh_16.png b/build/oxt/icons/refresh_16.png
new file mode 100644
index 0000000..971177e
--- /dev/null
+++ b/build/oxt/icons/refresh_16.png
Binary files differ
diff --git a/build/oxt/icons/refresh_26.png b/build/oxt/icons/refresh_26.png
new file mode 100644
index 0000000..0fc482d
--- /dev/null
+++ b/build/oxt/icons/refresh_26.png
Binary files differ
diff --git a/build/oxt/icons/removeCodes_16.png b/build/oxt/icons/removeCodes_16.png
new file mode 100644
index 0000000..cc3ead4
--- /dev/null
+++ b/build/oxt/icons/removeCodes_16.png
Binary files differ
diff --git a/build/oxt/icons/removeCodes_26.png b/build/oxt/icons/removeCodes_26.png
new file mode 100644
index 0000000..dc5e64c
--- /dev/null
+++ b/build/oxt/icons/removeCodes_26.png
Binary files differ
diff --git a/build/oxt/icons/setDocPrefs_16.png b/build/oxt/icons/setDocPrefs_16.png
new file mode 100644
index 0000000..06a9964
--- /dev/null
+++ b/build/oxt/icons/setDocPrefs_16.png
Binary files differ
diff --git a/build/oxt/icons/setDocPrefs_26.png b/build/oxt/icons/setDocPrefs_26.png
new file mode 100644
index 0000000..cd0de3e
--- /dev/null
+++ b/build/oxt/icons/setDocPrefs_26.png
Binary files differ
diff --git a/build/oxt/pkg-desc/pkg-description.txt b/build/oxt/pkg-desc/pkg-description.txt
new file mode 100644
index 0000000..248d190
--- /dev/null
+++ b/build/oxt/pkg-desc/pkg-description.txt
@@ -0,0 +1 @@
+Integrates Zotero, an open source research tool, with LibreOffice
diff --git a/build/package.properties b/build/package.properties
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/build/package.properties
diff --git a/build/source/org/zotero/integration/ooo/comp/Application.java b/build/source/org/zotero/integration/ooo/comp/Application.java
new file mode 100644
index 0000000..60b4c87
--- /dev/null
+++ b/build/source/org/zotero/integration/ooo/comp/Application.java
@@ -0,0 +1,98 @@
+/*
+ ***** BEGIN LICENSE BLOCK *****
+
+ Copyright (c) 2017 Zotero
+ Center for History and New Media
+ George Mason University, Fairfax, Virginia, USA
+ http://zotero.org
+
+ Zotero is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Zotero is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with Zotero. If not, see <http://www.gnu.org/licenses/>.
+
+ ***** END LICENSE BLOCK *****
+*/
+
+package org.zotero.integration.ooo.comp;
+
+import java.util.HashMap;
+
+import com.sun.star.beans.PropertyValue;
+import com.sun.star.container.XNameAccess;
+import com.sun.star.frame.XDesktop;
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.uno.XComponentContext;
+
+public class Application {
+ static XMultiServiceFactory factory;
+ static XDesktop desktop;
+ static String ooName;
+ static String ooVersion;
+ static XComponentContext ctx;
+ static SaveEventListener saveEventListener;
+ private static HashMap <Integer, Document> documents = new HashMap<Integer, Document>();
+ private static int lastDocumentID = 0;
+
+ public Application(XComponentContext aCtx) throws Exception {
+ ctx = aCtx;
+ if(desktop == null) init();
+ }
+
+ public Document getActiveDocument() throws Exception {
+ return getDocument(getActiveDocumentID());
+ }
+
+ public int getActiveDocumentID() throws Exception {
+ if(lastDocumentID == Integer.MAX_VALUE) lastDocumentID = 0;
+ Integer documentID = ++lastDocumentID;
+ Document document;
+ try {
+ document = new Document(this, documentID);
+ } catch(Exception e) {
+ init();
+ document = new Document(this, documentID);
+ }
+ documents.put(documentID, document);
+ return documentID;
+ }
+
+ public Document getDocument(int documentID) {
+ return documents.get(documentID);
+ }
+
+ public void documentComplete(int documentID) {
+ documents.remove(documentID);
+ }
+
+ private void init() throws Exception {
+ // get factory and desktop
+ factory = (XMultiServiceFactory) UnoRuntime.queryInterface(XMultiServiceFactory.class, ctx.getServiceManager());
+ desktop = (XDesktop) UnoRuntime.queryInterface(XDesktop.class,
+ factory.createInstance("com.sun.star.frame.Desktop"));
+
+ // get ooName
+ XMultiServiceFactory configProvider = (XMultiServiceFactory) UnoRuntime.queryInterface(XMultiServiceFactory.class,
+ factory.createInstance("com.sun.star.configuration.ConfigurationProvider"));
+ PropertyValue nodepath = new PropertyValue();
+ nodepath.Name = "nodepath";
+ nodepath.Value = "/org.openoffice.Setup/Product";
+ XNameAccess settings = (XNameAccess) UnoRuntime.queryInterface(XNameAccess.class,
+ configProvider.createInstanceWithArguments(
+ "com.sun.star.configuration.ConfigurationAccess", new Object[] {nodepath}));
+ ooName = (String) settings.getByName("ooName");
+ ooVersion = (String) settings.getByName("ooSetupVersion");
+
+ // create event listener if necessary
+ if(saveEventListener == null) saveEventListener = new SaveEventListener();
+ }
+} \ No newline at end of file
diff --git a/build/source/org/zotero/integration/ooo/comp/Bookmark.java b/build/source/org/zotero/integration/ooo/comp/Bookmark.java
new file mode 100644
index 0000000..f47ec4e
--- /dev/null
+++ b/build/source/org/zotero/integration/ooo/comp/Bookmark.java
@@ -0,0 +1,87 @@
+/*
+ ***** BEGIN LICENSE BLOCK *****
+
+ Copyright (c) 2017 Zotero
+ Center for History and New Media
+ George Mason University, Fairfax, Virginia, USA
+ http://zotero.org
+
+ Zotero is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Zotero is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with Zotero. If not, see <http://www.gnu.org/licenses/>.
+
+ ***** END LICENSE BLOCK *****
+*/
+
+package org.zotero.integration.ooo.comp;
+
+import com.sun.star.container.XNamed;
+import com.sun.star.text.XTextContent;
+import com.sun.star.uno.UnoRuntime;
+
+public class Bookmark extends ReferenceMark {
+ public Bookmark(Document aDoc, XNamed aMark, String aCode) throws IllegalArgumentException {
+ super(aDoc, aMark, aCode);
+ isDisposable = true;
+ }
+
+ public void delete() throws Exception {
+ doc.properties.setProperty(rawCode, "");
+ super.delete();
+ }
+
+ public void removeCode() throws Exception {
+ doc.properties.setProperty(rawCode, "");
+ super.removeCode();
+ }
+
+ public void setCode(String code) throws Exception {
+ doc.properties.setProperty(rawCode, Document.PREFIXES[0]+code);
+ }
+
+ public String getCode() throws Exception {
+ String property = doc.properties.getProperty(rawCode);
+
+ // necessary since OOo adds a number to copy and pasted citations
+ if(property == "") {
+ for(int i=1; i<=3 && property == ""; i++) {
+ property = doc.properties.getProperty(rawCode.substring(0, rawCode.length()-i));
+ }
+
+ if(property == "") {
+ return "";
+ } else {
+ doc.properties.setProperty(rawCode, property);
+ }
+ }
+
+ for(String prefix : Document.PREFIXES) {
+ int index = property.indexOf(prefix);
+ if(index != -1) {
+ return property.substring(index+prefix.length());
+ }
+ }
+ throw new Exception("Invalid code prefix");
+ }
+
+ protected void prepareMultiline() throws Exception {}
+
+ protected void reattachMark() throws Exception {
+ // Re-create bookmark
+ super.removeCode();
+ named = (XNamed) UnoRuntime.queryInterface(XNamed.class,
+ doc.docFactory.createInstance("com.sun.star.text.Bookmark"));
+ named.setName(rawCode);
+ textContent = (XTextContent) UnoRuntime.queryInterface(XTextContent.class, named);
+ textContent.attach(range);
+ }
+}
diff --git a/build/source/org/zotero/integration/ooo/comp/Comm.java b/build/source/org/zotero/integration/ooo/comp/Comm.java
new file mode 100644
index 0000000..038fcff
--- /dev/null
+++ b/build/source/org/zotero/integration/ooo/comp/Comm.java
@@ -0,0 +1,73 @@
+/*
+ ***** BEGIN LICENSE BLOCK *****
+
+ Copyright (c) 2017 Zotero
+ Center for History and New Media
+ George Mason University, Fairfax, Virginia, USA
+ http://zotero.org
+
+ Zotero is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Zotero is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with Zotero. If not, see <http://www.gnu.org/licenses/>.
+
+ ***** END LICENSE BLOCK *****
+*/
+
+package org.zotero.integration.ooo.comp;
+
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.SynchronousQueue;
+
+class Comm {
+ static final int API_VERSION = 3;
+ static final String COMMUNICATION_ERROR_STRING = "LibreOffice could not communicate with Zotero. "+
+ "Please ensure Zotero is open and set to an online state and try again.";
+ static final String OLD_VERSION_STRING = "The version of the Zotero LibreOffice "+
+ "Integration component installed within LibreOffice, OpenOffice.org, or NeoOffice does not "+
+ "appear to match the version installed in Zotero. Please ensure both "+
+ "components are up to date and try again.";
+ static Application application;
+ static BlockingQueue<CommFrame> writeQueue = new SynchronousQueue<CommFrame>();
+ static private Thread serverThread;
+
+ /**
+ * Sends a command to the writing thread to write to the Zotero socket
+ * Should be called from the main OOo thread
+ * @param command
+ */
+ static void sendCommand(String command) {
+ // Execute command
+ if(serverThread == null || !serverThread.isAlive()) {
+ serverThread = new Thread(new CommServer());
+ serverThread.start();
+ }
+
+ try {
+ writeQueue.put(new CommCommand(command));
+ } catch (InterruptedException e) {
+ return;
+ }
+ }
+
+ static void showError(String errString, Exception exception) {
+ try {
+ application.getActiveDocument().displayAlert(errString, 0, 0);
+ } catch (Exception e1) {
+ // Called if we couldn't get the active document to display a dialog.
+ e1.printStackTrace();
+ }
+
+ if(exception != null) {
+ exception.printStackTrace();
+ }
+ }
+} \ No newline at end of file
diff --git a/build/source/org/zotero/integration/ooo/comp/CommCommand.java b/build/source/org/zotero/integration/ooo/comp/CommCommand.java
new file mode 100644
index 0000000..18af84d
--- /dev/null
+++ b/build/source/org/zotero/integration/ooo/comp/CommCommand.java
@@ -0,0 +1,49 @@
+/*
+ ***** BEGIN LICENSE BLOCK *****
+
+ Copyright (c) 2017 Zotero
+ Center for History and New Media
+ George Mason University, Fairfax, Virginia, USA
+ http://zotero.org
+
+ Zotero is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Zotero is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with Zotero. If not, see <http://www.gnu.org/licenses/>.
+
+ ***** END LICENSE BLOCK *****
+*/
+
+
+package org.zotero.integration.ooo.comp;
+
+import java.io.UnsupportedEncodingException;
+
+public class CommCommand implements CommFrame {
+ private String mCommand;
+
+ CommCommand(String aCommand) {
+ mCommand = "\""+aCommand+"\"";
+ }
+
+ public int getTransactionID() {
+ return 0;
+ }
+
+ public byte[] getBytes() {
+ try {
+ return mCommand.getBytes("UTF-8");
+ } catch (UnsupportedEncodingException e) {
+ return mCommand.getBytes();
+ }
+ }
+
+}
diff --git a/build/source/org/zotero/integration/ooo/comp/CommFrame.java b/build/source/org/zotero/integration/ooo/comp/CommFrame.java
new file mode 100644
index 0000000..b58c7b6
--- /dev/null
+++ b/build/source/org/zotero/integration/ooo/comp/CommFrame.java
@@ -0,0 +1,30 @@
+/*
+ ***** BEGIN LICENSE BLOCK *****
+
+ Copyright (c) 2017 Zotero
+ Center for History and New Media
+ George Mason University, Fairfax, Virginia, USA
+ http://zotero.org
+
+ Zotero is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Zotero is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with Zotero. If not, see <http://www.gnu.org/licenses/>.
+
+ ***** END LICENSE BLOCK *****
+*/
+
+package org.zotero.integration.ooo.comp;
+
+interface CommFrame {
+ int getTransactionID();
+ byte[] getBytes();
+}
diff --git a/build/source/org/zotero/integration/ooo/comp/CommMessage.java b/build/source/org/zotero/integration/ooo/comp/CommMessage.java
new file mode 100644
index 0000000..872765c
--- /dev/null
+++ b/build/source/org/zotero/integration/ooo/comp/CommMessage.java
@@ -0,0 +1,157 @@
+/*
+ ***** BEGIN LICENSE BLOCK *****
+
+ Copyright (c) 2017 Zotero
+ Center for History and New Media
+ George Mason University, Fairfax, Virginia, USA
+ http://zotero.org
+
+ Zotero is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Zotero is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with Zotero. If not, see <http://www.gnu.org/licenses/>.
+
+ ***** END LICENSE BLOCK *****
+*/
+
+package org.zotero.integration.ooo.comp;
+
+import java.text.ParseException;
+import java.util.ArrayList;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+class CommMessage implements CommFrame {
+ static ObjectMapper objectMapper = new ObjectMapper();
+ private byte[] mInputBytes;
+ private byte[] mOutputBytes;
+ private int mTransactionID;
+
+ CommMessage(int aTransactionID, byte aBytes[]) {
+ mTransactionID = aTransactionID;
+ mInputBytes = aBytes;
+ }
+
+ /**
+ * Gets the transaction ID for this message
+ */
+ public int getTransactionID() {
+ return mTransactionID;
+ }
+
+ /**
+ * Gets the response to the message encapsulated by this CommMessage
+ */
+ @SuppressWarnings("unchecked")
+ public byte[] getBytes() {
+ if(mOutputBytes == null) {
+ try {
+ // Parse message
+ ArrayList<Object> message = objectMapper.readValue(mInputBytes, 0, mInputBytes.length, ArrayList.class);
+
+ // Execute the command
+ mOutputBytes = objectMapper.writeValueAsBytes(execute(message));
+ } catch(Exception e) {
+ String errString = Document.getErrorString(e);
+ try {
+ mOutputBytes = ("ERR:"+errString).getBytes("UTF-8");
+ } catch(Exception e1) {
+ mOutputBytes = "ERR:An unexpected exception occurred".getBytes();
+ }
+ }
+ }
+ return mOutputBytes;
+ }
+
+ @SuppressWarnings("unchecked")
+ private Object execute(ArrayList<Object> message) throws Exception {
+ String command = (String) message.get(0);
+ ArrayList<Object> args = (ArrayList<Object>) message.get(1);
+
+ if(command.equals("Application_getActiveDocument")) {
+ Object[] out = {Comm.API_VERSION, Comm.application.getActiveDocumentID()};
+ return out;
+ } else {
+ int documentID = (Integer) args.get(0);
+ Document document = Comm.application.getDocument(documentID);
+
+ if(command.equals("Document_displayAlert")) {
+ return document.displayAlert((String) args.get(1), (Integer) args.get(2), (Integer) args.get(3));
+ } else if(command.equals("Document_activate")) {
+ document.activate();
+ } else if(command.equals("Document_canInsertField")) {
+ return document.canInsertField((String) args.get(1));
+ } else if(command.equals("Document_cursorInField")) {
+ ReferenceMark field = document.cursorInField((String) args.get(1));
+ if(field != null) {
+ Object[] out = {document.mMarkManager.getIDForMark(field), field.getCode(), field.getNoteIndex()};
+ return out;
+ }
+ } else if(command.equals("Document_getDocumentData")) {
+ return document.getDocumentData();
+ } else if(command.equals("Document_setDocumentData")) {
+ document.setDocumentData((String) args.get(1));
+ } else if(command.equals("Document_insertField")) {
+ ReferenceMark field = document.insertField((String) args.get(1), (Integer) args.get(2));
+ Object[] out = {document.mMarkManager.getIDForMark(field), field.getCode(), field.getNoteIndex()};
+ return out;
+ } else if(command.equals("Document_getFields")) {
+ ArrayList<ReferenceMark> fields = document.getFields((String) args.get(1));
+
+ // get codes and rawCodes
+ int numFields = fields.size();
+ int[] fieldIndices = new int[numFields];
+ String[] fieldCodes = new String[numFields];
+ int[] noteIndices = new int[numFields];
+
+ for(int i=0; i<numFields; i++) {
+ ReferenceMark field = fields.get(i);
+ fieldIndices[i] = document.mMarkManager.getIDForMark(field);
+ fieldCodes[i] = field.getCode();
+ noteIndices[i] = field.getNoteIndex();
+ }
+
+ Object[] out = {fieldIndices, fieldCodes, noteIndices};
+ return out;
+ } else if(command.equals("Document_setBibliographyStyle")) {
+ ArrayList<Number> arrayList = (ArrayList<Number>) args.get(5);
+ document.setBibliographyStyle((Integer) args.get(1), (Integer) args.get(2),
+ (Integer) args.get(3), (Integer) args.get(4), arrayList, (Integer) args.get(6));
+ } else if(command.equals("Document_cleanup")) {
+ document.cleanup();
+ } else if(command.equals("Document_complete")) {
+ document.complete();
+ } else if(command.startsWith("Field_")) {
+ ReferenceMark field = document.mMarkManager.getMarkForID((Integer) args.get(1));
+ if(command.equals("Field_delete")) {
+ field.delete();
+ } else if(command.equals("Field_select")) {
+ field.select();
+ } else if(command.equals("Field_removeCode")) {
+ field.removeCode();
+ } else if(command.equals("Field_getText")) {
+ return field.getText();
+ } else if(command.equals("Field_setText")) {
+ field.setText((String) args.get(2), (Boolean) args.get(3));
+ } else if(command.equals("Field_getCode")) {
+ return field.getCode();
+ } else if(command.equals("Field_setCode")) {
+ field.setCode((String) args.get(2));
+ } else if(command.equals("Field_convert")) {
+ document.convert(field, (String) args.get(2), (Integer) args.get(3));
+ }
+ } else {
+ throw new ParseException(command, 0);
+ }
+ }
+ return null;
+ }
+}
diff --git a/build/source/org/zotero/integration/ooo/comp/CommReader.java b/build/source/org/zotero/integration/ooo/comp/CommReader.java
new file mode 100644
index 0000000..e84ca86
--- /dev/null
+++ b/build/source/org/zotero/integration/ooo/comp/CommReader.java
@@ -0,0 +1,69 @@
+/*
+ ***** BEGIN LICENSE BLOCK *****
+
+ Copyright (c) 2017 Zotero
+ Center for History and New Media
+ George Mason University, Fairfax, Virginia, USA
+ http://zotero.org
+
+ Zotero is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Zotero is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with Zotero. If not, see <http://www.gnu.org/licenses/>.
+
+ ***** END LICENSE BLOCK *****
+*/
+
+package org.zotero.integration.ooo.comp;
+
+import java.io.DataInputStream;
+import java.io.EOFException;
+import java.io.IOException;
+import java.net.Socket;
+
+public class CommReader implements Runnable {
+ Socket mSocket;
+ DataInputStream mInputStream;
+
+ public CommReader(Socket aSocket) throws IOException {
+ mSocket = aSocket;
+ mInputStream = new DataInputStream(aSocket.getInputStream());
+ }
+
+ public void run() {
+ try {
+ while(true) {
+ int transactionID = mInputStream.readInt();
+ int length = mInputStream.readInt();
+ byte[] readBytes = new byte[length];
+ mInputStream.readFully(readBytes);
+ try {
+ Comm.writeQueue.put(new CommMessage(transactionID, readBytes));
+ } catch (InterruptedException e) {
+ continue;
+ }
+ }
+ } catch (EOFException e) {
+ // Called when Zotero is closed to disconnect from the channel
+ try {
+ mSocket.close();
+ } catch (IOException e1) {}
+ return;
+ } catch (IOException e) {
+ // We have to ignore this too, since it can sometimes wrap a SocketException
+ try {
+ mSocket.close();
+ } catch (IOException e1) {}
+ return;
+ }
+ }
+
+}
diff --git a/build/source/org/zotero/integration/ooo/comp/CommServer.java b/build/source/org/zotero/integration/ooo/comp/CommServer.java
new file mode 100644
index 0000000..9b614be
--- /dev/null
+++ b/build/source/org/zotero/integration/ooo/comp/CommServer.java
@@ -0,0 +1,106 @@
+/*
+ ***** BEGIN LICENSE BLOCK *****
+
+ Copyright (c) 2017 Zotero
+ Center for History and New Media
+ George Mason University, Fairfax, Virginia, USA
+ http://zotero.org
+
+ Zotero is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Zotero is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with Zotero. If not, see <http://www.gnu.org/licenses/>.
+
+ ***** END LICENSE BLOCK *****
+*/
+
+package org.zotero.integration.ooo.comp;
+
+import java.io.BufferedOutputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.net.ConnectException;
+import java.net.Socket;
+import java.net.SocketException;
+
+public class CommServer implements Runnable {
+ /**
+ * Called when new data is received to handle interfacing with Java methods
+ */
+ public void run() {
+ Socket socket;
+ CommFrame deferredFrame = null;
+
+ while(true) {
+ DataOutputStream outputStream;
+ try {
+ // Open socket and output stream
+ socket = new Socket("127.0.0.1", 23116);
+ socket.setTcpNoDelay(true);
+ outputStream = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream(), 16384));
+
+ // Start another thread to read from the socket
+ new Thread(new CommReader(socket)).start();
+ } catch (ConnectException e) {
+ try {
+ socket = new Socket("127.0.0.1", 19876);
+ socket.close();
+ Comm.writeQueue.poll();
+ Comm.showError(Comm.OLD_VERSION_STRING, null);
+ } catch(Exception e1) {
+ Comm.writeQueue.poll();
+ Comm.showError(Comm.COMMUNICATION_ERROR_STRING, null);
+ }
+ return;
+ } catch (Exception e) {
+ Comm.writeQueue.poll();
+ Comm.showError(Document.getErrorString(e), e);
+ return;
+ }
+
+ try {
+ // Start write loop
+ while(true) {
+ CommFrame frame;
+ if(deferredFrame == null) {
+ try {
+ frame = Comm.writeQueue.take();
+ } catch (InterruptedException e) {
+ continue;
+ }
+ } else {
+ frame = deferredFrame;
+ deferredFrame = null;
+ }
+
+ byte[] payload = frame.getBytes();
+ //ZoteroOpenOfficeIntegrationImpl.debugPrint("Writing "+new String(payload));
+
+ try {
+ outputStream.writeInt(frame.getTransactionID());
+ outputStream.writeInt(payload.length);
+ outputStream.write(payload);
+ outputStream.flush();
+ } catch(SocketException e) {
+ deferredFrame = frame;
+ break;
+ } catch(IOException e) {
+ Comm.showError(Comm.COMMUNICATION_ERROR_STRING, e);
+ }
+ }
+ } catch (Exception e) {
+ Comm.writeQueue.poll();
+ Comm.showError(Document.getErrorString(e), e);
+ return;
+ }
+ }
+ }
+}
diff --git a/build/source/org/zotero/integration/ooo/comp/Document.java b/build/source/org/zotero/integration/ooo/comp/Document.java
new file mode 100644
index 0000000..f8a32ee
--- /dev/null
+++ b/build/source/org/zotero/integration/ooo/comp/Document.java
@@ -0,0 +1,566 @@
+/*
+ ***** BEGIN LICENSE BLOCK *****
+
+ Copyright (c) 2017 Zotero
+ Center for History and New Media
+ George Mason University, Fairfax, Virginia, USA
+ http://zotero.org
+
+ Zotero is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Zotero is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with Zotero. If not, see <http://www.gnu.org/licenses/>.
+
+ ***** END LICENSE BLOCK *****
+*/
+
+package org.zotero.integration.ooo.comp;
+
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Random;
+import java.util.stream.Collectors;
+
+import com.sun.jna.Platform;
+import com.sun.star.awt.MessageBoxButtons;
+import com.sun.star.awt.MessageBoxType;
+import com.sun.star.awt.XMessageBox;
+import com.sun.star.awt.XMessageBoxFactory;
+import com.sun.star.awt.XWindowPeer;
+import com.sun.star.beans.PropertyValue;
+import com.sun.star.beans.XPropertySet;
+import com.sun.star.container.XEnumeration;
+import com.sun.star.container.XEnumerationAccess;
+import com.sun.star.container.XIndexAccess;
+import com.sun.star.container.XNameAccess;
+import com.sun.star.container.XNameContainer;
+import com.sun.star.container.XNamed;
+import com.sun.star.document.XUndoManager;
+import com.sun.star.document.XUndoManagerSupplier;
+import com.sun.star.frame.XController;
+import com.sun.star.frame.XDesktop;
+import com.sun.star.frame.XFrame;
+import com.sun.star.lang.XComponent;
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.lang.XServiceInfo;
+import com.sun.star.style.LineSpacing;
+import com.sun.star.style.LineSpacingMode;
+import com.sun.star.style.TabAlign;
+import com.sun.star.style.TabStop;
+import com.sun.star.style.XStyle;
+import com.sun.star.style.XStyleFamiliesSupplier;
+import com.sun.star.text.XBookmarksSupplier;
+import com.sun.star.text.XParagraphCursor;
+import com.sun.star.text.XReferenceMarksSupplier;
+import com.sun.star.text.XText;
+import com.sun.star.text.XTextContent;
+import com.sun.star.text.XTextCursor;
+import com.sun.star.text.XTextDocument;
+import com.sun.star.text.XTextRange;
+import com.sun.star.text.XTextRangeCompare;
+import com.sun.star.text.XTextSection;
+import com.sun.star.text.XTextSectionsSupplier;
+import com.sun.star.text.XTextViewCursor;
+import com.sun.star.text.XTextViewCursorSupplier;
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.util.InvalidStateException;
+
+public class Document {
+ static final int NOTE_FOOTNOTE = 1;
+ static final int NOTE_ENDNOTE = 2;
+
+ Application app;
+ int ID;
+ XTextRangeCompare textRangeCompare;
+ XTextDocument textDocument;
+ XText text;
+ XDesktop desktop;
+ XMultiServiceFactory docFactory;
+ XMultiServiceFactory factory;
+ XFrame frame;
+ XController controller;
+ XComponent component;
+ String runtimeUID;
+ Properties properties;
+ MarkManager mMarkManager;
+ XUndoManager undoManager;
+
+ private static boolean checkExperimentalMode = true;
+ private static boolean statusExperimentalMode = false;
+
+ static final String[] PREFIXES = {"ZOTERO_", " CSL_", " ADDIN ZOTERO_"};
+ static final String[] PREFS_PROPERTIES = {"ZOTERO_PREF", "CSL_PREF"};
+ static final String FIELD_PLACEHOLDER = "{Citation}";
+ static final String BOOKMARK_REFERENCE_PROPERTY = "ZOTERO_BREF_";
+ static final String UNDO_RECORD_NAME = "Zotero Action";
+
+ static final int BOOKMARK_ADD_CHARS = 12;
+ static final int REFMARK_ADD_CHARS = 10;
+ static final String BIBLIOGRAPHY_CODE = "BIBL";
+
+ static final double MM_PER_100_TWIP = 25.4/1440*100;
+
+ static String ERROR_STRING = "An error occurred communicating with Zotero:";
+ static String SAVE_WARNING_STRING = "This document contains Zotero ReferenceMarks. Upon reopening the document, Zotero will be unable to edit existing citations or add new references to the bibliography.\n\nTo save Zotero citation information, please select the \"ODF Text Document\" format when saving, or switch to Bookmarks in the Zotero Document Preferences.";
+ TextTableManager textTableManager;
+
+ public Document(Application anApp, int anID) throws Exception {
+ app = anApp;
+ ID = anID;
+ factory = Application.factory;
+ desktop = Application.desktop;
+ frame = desktop.getCurrentFrame();
+ component = desktop.getCurrentComponent();
+ controller = frame.getController();
+ docFactory = (XMultiServiceFactory) UnoRuntime.queryInterface(XMultiServiceFactory.class, component);
+ textDocument = (XTextDocument) UnoRuntime.queryInterface(XTextDocument.class, component);
+ text = textDocument.getText();
+ textRangeCompare = (XTextRangeCompare) UnoRuntime.queryInterface(XTextRangeCompare.class, text);
+ properties = new Properties(component);
+ runtimeUID = (String) ((XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, component)).getPropertyValue("RuntimeUID");
+ mMarkManager = new MarkManager(this);
+ XUndoManagerSupplier ums = (XUndoManagerSupplier) UnoRuntime.queryInterface(XUndoManagerSupplier.class, component);
+ undoManager = ums.getUndoManager();
+ undoManager.enterUndoContext(UNDO_RECORD_NAME);
+ }
+
+ public void cleanup() {}
+
+ public void complete() throws InvalidStateException {
+ undoManager.leaveUndoContext();
+ app.documentComplete(ID);
+ }
+
+ public int displayAlert(String text, int icon, int buttons) throws Exception {
+ if (Platform.isMac()) return displayAlertMacOS(text, icon, buttons);
+ // figure out appropriate buttons
+ int ooButtons = MessageBoxButtons.BUTTONS_OK;
+ if(buttons == 1) {
+ ooButtons = MessageBoxButtons.BUTTONS_OK_CANCEL + MessageBoxButtons.DEFAULT_BUTTON_OK;
+ } else if(buttons == 2) {
+ ooButtons = MessageBoxButtons.BUTTONS_YES_NO + MessageBoxButtons.DEFAULT_BUTTON_YES;
+ } else if(buttons == 3) {
+ ooButtons = MessageBoxButtons.BUTTONS_YES_NO_CANCEL + MessageBoxButtons.DEFAULT_BUTTON_YES;
+ } else {
+ ooButtons = MessageBoxButtons.BUTTONS_OK;
+ }
+
+ XWindowPeer xWindow = (XWindowPeer) UnoRuntime.queryInterface(XWindowPeer.class, frame.getContainerWindow());
+ XMessageBoxFactory xToolkit = (XMessageBoxFactory) UnoRuntime.queryInterface(XMessageBoxFactory.class, xWindow.getToolkit());
+ MessageBoxType[] boxTypes = {MessageBoxType.ERRORBOX, MessageBoxType.MESSAGEBOX, MessageBoxType.WARNINGBOX};
+
+ if (boxTypes[icon] == MessageBoxType.MESSAGEBOX && ooButtons != MessageBoxButtons.BUTTONS_OK) {
+ // MessageBox ignores ooButtons and only displays the OK button in LO 4.2+, so we change to WarningBox
+ icon = 2;
+ }
+
+ XMessageBox box = xToolkit.createMessageBox(xWindow, boxTypes[icon], ooButtons, "Zotero Integration", text);
+
+ short result = box.execute();
+
+ if(buttons == 2) {
+ return (result == 3 ? 0 : 1);
+ } if(buttons == 3 && result == 3) {
+ return 1;
+ } else if(buttons == 0) {
+ return 0;
+ }
+ return result;
+ }
+
+ /**
+ * Solution for https://github.com/zotero/zotero-libreoffice-integration/issues/21
+ * https://bugs.documentfoundation.org/show_bug.cgi?id=106292
+ */
+ public int displayAlertMacOS(String text, int icon, int buttons) throws Exception {
+ String script = "osascript -e \"tell app \\\"LibreOffice\\\" to display dialog \\\"" + text + "\\\"";
+ script += " with title \\\"Zotero Integration\\\" with icon " + icon + " buttons ";
+ switch (buttons) {
+ case 3:
+ script += "{\\\"Yes\\\", \\\"No\\\", \\\"Cancel\\\"} default button 1";
+ break;
+ case 2:
+ script += "{\\\"Yes\\\", \\\"No\\\"} default button 1";
+ break;
+ case 1:
+ script += "{\\\"OK\\\", \\\"Cancel\\\"}";
+ break;
+ default:
+ script += "{\\\"OK\\\"}";
+ break;
+ }
+ // prints to stderr on cancel which also returns 1
+ script += "\" 2>&1";
+ Process p = new ProcessBuilder("/bin/bash", "-c", script).start();
+ p.waitFor();
+ String output = new BufferedReader(new InputStreamReader(p.getInputStream()))
+ .lines().collect(Collectors.joining("\n"));
+
+ // ofc they spelt it 'canceled'
+ if (p.exitValue() != 0 && !output.contains("User canceled")) {
+ System.out.println(script);
+ System.out.println(output);
+ throw new RuntimeException();
+ }
+
+ if (output.contains("Yes")) {
+ if (buttons == 3) return 2;
+ else return 1;
+ } else if (output.contains("No")) {
+ if (buttons == 3) return 1;
+ else return 0;
+ } else if (output.contains("OK") && buttons == 1) {
+ return 1;
+ } else {
+ return 0;
+ }
+ }
+
+ public void activate() throws Exception {
+ if(System.getProperty("os.name").equals("Mac OS X")) {
+ Runtime runtime = Runtime.getRuntime();
+ runtime.exec(new String[] {"/usr/bin/osascript", "-e", "tell application \""+Application.ooName+"\" to activate"});
+ }
+ }
+
+ public boolean canInsertField(String fieldType) throws Exception {
+ // first, check if cursor is in the bibliography (no sense offering to replace it)
+ XTextViewCursor selection = getSelection();
+ XTextSection section = (XTextSection) UnoRuntime.queryInterface(XTextSection.class, selection);
+ if(section != null) {
+ XNamed sectionNamed = (XNamed) UnoRuntime.queryInterface(XNamed.class, section);
+ String name = sectionNamed.getName();
+ for(String prefix : PREFIXES) {
+ if(name.contains(prefix)) {
+ return false;
+ }
+ }
+ }
+
+ // Also make sure that the cursor is not in any other place we can't insert a citation
+ String position = getRangePosition(selection);
+
+ if(position.equals("SwXTextFrame")) {
+ displayAlert("Citations in text frames will be formatted as if they appear at the end of the document.", 2, 0);
+ return true;
+ }
+
+ return (position.equals("SwXBodyText") || position.equals("SwXCell")
+ || (!fieldType.equals("Bookmark") && position.equals("SwXFootnote")));
+ }
+
+ public ReferenceMark cursorInField(String fieldType) throws Exception {
+ // create two text cursors containing the selection
+ XTextViewCursor selectionCursor = getSelection();
+ XText text = selectionCursor.getText();
+ XParagraphCursor paragraphCursor1 = (XParagraphCursor) UnoRuntime.queryInterface(XParagraphCursor.class,
+ text.createTextCursorByRange(selectionCursor));
+ XParagraphCursor paragraphCursor2 = (XParagraphCursor) UnoRuntime.queryInterface(XParagraphCursor.class,
+ text.createTextCursorByRange(selectionCursor));
+
+ // extend one cursor to the beginning of the paragraph and one to the end
+ paragraphCursor1.goLeft((short) 1, false);
+ paragraphCursor1.gotoStartOfParagraph(true);
+ paragraphCursor2.gotoEndOfParagraph(true);
+
+ // get enumerator corresponding to first cursor
+ XEnumerationAccess enumeratorAccess = (XEnumerationAccess) UnoRuntime.queryInterface(XEnumerationAccess.class, paragraphCursor1);
+ Object nextElement = enumeratorAccess.createEnumeration().nextElement();
+ enumeratorAccess = (XEnumerationAccess) UnoRuntime.queryInterface(XEnumerationAccess.class, nextElement);
+ XEnumeration enumerator = enumeratorAccess.createEnumeration();
+
+ while(enumerator.hasMoreElements()) {
+ // look for a ReferenceMark or Bookmark
+ XPropertySet textProperties = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, enumerator.nextElement());
+ String textPropertyType = (String) textProperties.getPropertyValue("TextPortionType");
+ if(textPropertyType.equals(fieldType)) {
+ ReferenceMark mark = mMarkManager.getMark(textProperties.getPropertyValue(fieldType), fieldType);
+
+ if(mark != null) {
+ // check second enumerator for the same field
+ enumeratorAccess = (XEnumerationAccess) UnoRuntime.queryInterface(XEnumerationAccess.class, paragraphCursor2);
+ nextElement = enumeratorAccess.createEnumeration().nextElement();
+ enumeratorAccess = (XEnumerationAccess) UnoRuntime.queryInterface(XEnumerationAccess.class, nextElement);
+ XEnumeration enumerator2 = enumeratorAccess.createEnumeration();
+ while(enumerator2.hasMoreElements()) {
+ textProperties = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, enumerator2.nextElement());
+ textPropertyType = (String) textProperties.getPropertyValue("TextPortionType");
+ if(textPropertyType.equals(fieldType)) {
+ if(mark == mMarkManager.getMark(textProperties.getPropertyValue(fieldType), fieldType)) {
+ return mark;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return null;
+ }
+
+ public String getDocumentData() throws Exception {
+ if(checkExperimentalMode) {
+ if(Application.ooName.equals("LibreOffice")) {
+ try {
+ String[] splitVersion = Application.ooVersion.split("\\.");
+ int firstDigit = Integer.parseInt(splitVersion[0]);
+ if(firstDigit == 3 && Integer.parseInt(splitVersion[1]) >= 5) {
+ XMultiServiceFactory configProvider = (XMultiServiceFactory) UnoRuntime.queryInterface(XMultiServiceFactory.class,
+ factory.createInstance("com.sun.star.configuration.ConfigurationProvider"));
+ PropertyValue nodepath = new PropertyValue();
+ nodepath.Name = "nodepath";
+ nodepath.Value = "/org.openoffice.Office.Common/Misc";
+ Object configurationAccess = configProvider.createInstanceWithArguments("com.sun.star.configuration.ConfigurationAccess",
+ new Object[] {nodepath});
+ XNameAccess nameAccess = (XNameAccess) UnoRuntime.queryInterface(XNameAccess.class, configurationAccess);
+ statusExperimentalMode = (Boolean) nameAccess.getByName("ExperimentalMode");
+ }
+ } catch(Exception e) {}
+ }
+ checkExperimentalMode = false;
+ }
+
+ if(statusExperimentalMode) {
+ displayAlert("\"Experimental (unstable) features\" are currently enabled in the LibreOffice preferences. In LibreOffice 3.5 and later, one of these experimental features is broken and prevents Zotero from operating properly.\n\nDisable \"Experimental (unstable) features\" in the LibreOffice preferences and restart LibreOffice.", 0, 0);
+ throw new Exception("ExceptionAlreadyDisplayed");
+ }
+
+ String data;
+ for(String prefsProperty : PREFS_PROPERTIES) {
+ data = properties.getProperty(prefsProperty);
+ if(data != "") return data;
+ }
+ return "";
+ }
+
+ public void setDocumentData(String data) throws Exception {
+ properties.setProperty(PREFS_PROPERTIES[0], data);
+ }
+
+ public ArrayList<ReferenceMark> getFields(String fieldType) throws Exception {
+ ArrayList<ReferenceMark> marks = new ArrayList<ReferenceMark>();
+
+ // get all ReferenceMarks/Bookmarks
+ if(fieldType.equals("ReferenceMark")) {
+ // add save event listener if necessary
+ Application.saveEventListener.attachTo(component, runtimeUID);
+
+ XReferenceMarksSupplier referenceMarksSupplier = (XReferenceMarksSupplier)
+ UnoRuntime.queryInterface(XReferenceMarksSupplier.class, component);
+ XIndexAccess markIndexAccess = (XIndexAccess) UnoRuntime.queryInterface(XIndexAccess.class,
+ referenceMarksSupplier.getReferenceMarks());
+ int count = markIndexAccess.getCount();
+ for(int i = 0; i<count; i++) {
+ ReferenceMark mark = mMarkManager.getMark(markIndexAccess.getByIndex(i), fieldType);
+ if(mark != null) marks.add(mark);
+ }
+
+ XTextSectionsSupplier textSectionSupplier = (XTextSectionsSupplier)
+ UnoRuntime.queryInterface(XTextSectionsSupplier.class, component);
+ markIndexAccess = (XIndexAccess) UnoRuntime.queryInterface(XIndexAccess.class,
+ textSectionSupplier.getTextSections());
+ count = markIndexAccess.getCount();
+ for(int i = 0; i<count; i++) {
+ ReferenceMark mark = mMarkManager.getMark(markIndexAccess.getByIndex(i), fieldType);
+ if(mark != null) marks.add(mark);
+ }
+ } else if(fieldType.equals("Bookmark")) {
+ // remove save event listener if necessary
+ Application.saveEventListener.detachFrom(component, runtimeUID);
+
+ XBookmarksSupplier bookmarksSupplier = (XBookmarksSupplier)
+ UnoRuntime.queryInterface(XBookmarksSupplier.class, component);
+ XNameAccess markNameAccess = (XNameAccess) UnoRuntime.queryInterface(XNameAccess.class,
+ bookmarksSupplier.getBookmarks());
+ String[] markNames = markNameAccess.getElementNames();
+
+ for(int i = 0; i<markNames.length; i++) {
+ String name = markNames[i];
+
+ for(String prefix : Document.PREFIXES) {
+ if(name.contains(prefix)) {
+ ReferenceMark mark = mMarkManager.getMark(markNameAccess.getByName(name), fieldType);
+ if(mark != null) marks.add(mark);
+ break;
+ }
+ }
+ }
+ } else {
+ throw new Exception("Invalid field type "+fieldType);
+ }
+
+ Collections.sort(marks);
+ return marks;
+ }
+
+ public ReferenceMark insertField(String fieldType, int noteType) throws Exception {
+ // duplicate selection cursor
+ XTextViewCursor selectionCursor = getSelection();
+ XTextCursor rangeToInsert = (XParagraphCursor) UnoRuntime.queryInterface(XParagraphCursor.class,
+ selectionCursor.getText().createTextCursorByRange(selectionCursor));
+
+ return insertMarkAtRange(fieldType, noteType, rangeToInsert, null, null);
+ }
+
+ public void convert(ReferenceMark mark, String fieldType, int noteType) throws Exception {
+ XTextCursor range = mark.getReplacementCursor();
+
+ boolean isBookmark = mark instanceof Bookmark;
+ if(isBookmark && fieldType.equals("Bookmark")) {
+ // convert from one bookmark type to another
+ insertMarkAtRange(fieldType, noteType, range, null, mark.rawCode);
+ } else if(!isBookmark && fieldType.equals("ReferenceMark")) {
+ // convert from one referenceMark type to another
+ insertMarkAtRange(fieldType, noteType, range, mark.rawCode, null);
+ } else {
+ String code = mark.getCode();
+ ReferenceMark newMark = insertMarkAtRange(fieldType, noteType, range, null, null);
+ newMark.setCode(code);
+ }
+ }
+
+ public void setBibliographyStyle(int firstLineIndent, int bodyIndent, int lineSpacing,
+ int entrySpacing, ArrayList<Number> arrayList, int tabStopCount) throws Exception {
+ XStyleFamiliesSupplier styleFamilies = (XStyleFamiliesSupplier) UnoRuntime.queryInterface(
+ XStyleFamiliesSupplier.class, component);
+ XNameAccess styleFamilyNames = styleFamilies.getStyleFamilies();
+ XNameAccess paraStyleNames = (XNameAccess) UnoRuntime.queryInterface(
+ XNameAccess.class, styleFamilyNames.getByName("ParagraphStyles"));
+ XPropertySet styleProps;
+
+ try {
+ // use "Bibliography 1" if available
+ styleProps = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class,
+ paraStyleNames.getByName("Bibliography 1"));
+ } catch(Exception e) {
+ // otherwise, create it
+ XStyle style = (XStyle) UnoRuntime.queryInterface(XStyle.class,
+ docFactory.createInstance("com.sun.star.style.ParagraphStyle"));
+ XNameContainer styleNameContainer = (XNameContainer) UnoRuntime.queryInterface(XNameContainer.class,
+ styleFamilyNames.getByName("ParagraphStyles"));
+ styleNameContainer.insertByName("Bibliography 1", style);
+ style.setParentStyle("Default");
+ styleProps = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, style);
+ }
+
+ // first line indent
+ styleProps.setPropertyValue("ParaFirstLineIndent", (int) (firstLineIndent*MM_PER_100_TWIP));
+
+ // indent
+ styleProps.setPropertyValue("ParaLeftMargin", (int) (bodyIndent*MM_PER_100_TWIP));
+
+ // line spacing
+ LineSpacing lineSpacingStruct = new LineSpacing();
+ lineSpacingStruct.Mode = LineSpacingMode.MINIMUM;
+ lineSpacingStruct.Height = (short) (lineSpacing*MM_PER_100_TWIP);
+ styleProps.setPropertyValue("ParaLineSpacing", lineSpacingStruct);
+
+ // entry spacing
+ styleProps.setPropertyValue("ParaBottomMargin", (int) (entrySpacing*MM_PER_100_TWIP));
+
+ // tab stops
+ TabStop[] tabStopStruct = new TabStop[tabStopCount];
+ for(int i=0; i<tabStopCount; i++) {
+ tabStopStruct[i] = new TabStop();
+ tabStopStruct[i].Position = (int) (arrayList.get(i).intValue()*MM_PER_100_TWIP);
+ tabStopStruct[i].Alignment = TabAlign.LEFT;
+ }
+ styleProps.setPropertyValue("ParaTabStops", tabStopStruct);
+
+ // this takes less than half as many lines in py-appscript!
+ }
+
+ public XTextViewCursor getSelection() {
+ XTextViewCursorSupplier supplier = (XTextViewCursorSupplier) UnoRuntime.queryInterface(XTextViewCursorSupplier.class, controller);
+ return supplier.getViewCursor();
+ }
+
+ private ReferenceMark insertMarkAtRange(String fieldType, int noteType, XTextCursor rangeToInsert, String code, String customBookmarkName) throws Exception {
+ XNamed mark;
+ String rawCode;
+
+ // handle null code
+ if(code == null) {
+ code = PREFIXES[0];
+ }
+
+ // make footnote or endnote if cursor is in body text and a note style is selected
+ if(noteType != 0 && getRangePosition(rangeToInsert).equals("SwXBodyText")) {
+ Object note;
+ if(noteType == NOTE_FOOTNOTE) {
+ note = docFactory.createInstance("com.sun.star.text.Footnote");
+ } else {
+ note = docFactory.createInstance("com.sun.star.text.Endnote");
+ }
+ XTextContent noteTextContent = (XTextContent) UnoRuntime.queryInterface(XTextContent.class, note);
+ rangeToInsert.getText().insertTextContent(rangeToInsert, noteTextContent, true);
+ XTextRange noteTextRange = (XTextRange) UnoRuntime.queryInterface(XTextRange.class, note);
+ rangeToInsert = noteTextRange.getText().createTextCursorByRange(noteTextRange);
+ }
+
+ rangeToInsert.setString(FIELD_PLACEHOLDER);
+
+ // create mark
+ if(fieldType.equals("ReferenceMark")) {
+ mark = (XNamed) UnoRuntime.queryInterface(XNamed.class,
+ docFactory.createInstance("com.sun.star.text.ReferenceMark"));
+ rawCode = code + " RND" + Document.getRandomString(Document.REFMARK_ADD_CHARS);
+ mark.setName(rawCode);
+ } else if(fieldType.equals("Bookmark")) {
+ // determine appropriate name for the bookmark
+ rawCode = customBookmarkName;
+ if(rawCode == null) {
+ rawCode = BOOKMARK_REFERENCE_PROPERTY+getRandomString(BOOKMARK_ADD_CHARS);
+ }
+
+ mark = (XNamed) UnoRuntime.queryInterface(XNamed.class,
+ docFactory.createInstance("com.sun.star.text.Bookmark"));
+ mark.setName(rawCode);
+ } else {
+ throw new Exception("Invalid field type "+fieldType);
+ }
+
+ // attach field to range
+ XTextContent markContent = (XTextContent) UnoRuntime.queryInterface(XTextContent.class, mark);
+ markContent.attach(rangeToInsert);
+
+ ReferenceMark newMark = mMarkManager.getMark(mark, fieldType);
+ if(fieldType.equals("Bookmark") && customBookmarkName == null) {
+ // set code for a bookmark
+ newMark.setCode(code);
+ }
+ return newMark;
+ }
+
+ private String getRangePosition(XTextRange selection) {
+ XServiceInfo serviceInfo = (XServiceInfo) UnoRuntime.queryInterface(XServiceInfo.class, selection.getText());
+ return serviceInfo.getImplementationName();
+ }
+
+ private static final String randomCharacterSet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
+ private static Random rand = null;
+ static String getRandomString(int len) {
+ if(rand == null) rand = new Random();
+ StringBuilder sb = new StringBuilder(len);
+ for(int i = 0; i < len; i++) sb.append(randomCharacterSet.charAt(rand.nextInt(randomCharacterSet.length())));
+ return sb.toString();
+ }
+
+ static String getErrorString(Exception e) {
+ StringWriter sw = new StringWriter();
+ e.printStackTrace(new PrintWriter(sw));
+ return "An error occurred communicating with Zotero:\n"+sw.toString();
+ }
+} \ No newline at end of file
diff --git a/build/source/org/zotero/integration/ooo/comp/MarkManager.java b/build/source/org/zotero/integration/ooo/comp/MarkManager.java
new file mode 100644
index 0000000..97a53bc
--- /dev/null
+++ b/build/source/org/zotero/integration/ooo/comp/MarkManager.java
@@ -0,0 +1,117 @@
+/*
+ ***** BEGIN LICENSE BLOCK *****
+
+ Copyright (c) 2017 Zotero
+ Center for History and New Media
+ George Mason University, Fairfax, Virginia, USA
+ http://zotero.org
+
+ Zotero is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Zotero is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with Zotero. If not, see <http://www.gnu.org/licenses/>.
+
+ ***** END LICENSE BLOCK *****
+*/
+
+package org.zotero.integration.ooo.comp;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.IdentityHashMap;
+
+import com.sun.star.container.XNamed;
+import com.sun.star.uno.UnoRuntime;
+
+public class MarkManager {
+ private HashMap<String, ReferenceMark> mMarksByName;
+ private ArrayList<ReferenceMark> mMarksByID;
+ private IdentityHashMap<ReferenceMark, Integer> mIDsByMark;
+ private Document mDoc;
+
+ MarkManager(Document aDoc) {
+ mDoc = aDoc;
+ mMarksByName = new HashMap<String, ReferenceMark>();
+ mMarksByID = new ArrayList<ReferenceMark>();
+ mIDsByMark = new IdentityHashMap<ReferenceMark, Integer>();
+ }
+
+ /**
+ * Updates internal hashes to accommodate renaming of a mark
+ * @param aOldName The old name of the mark
+ * @param aNewName The new name of the mark
+ */
+ void renameMark(String aOldName, String aNewName) {
+ ReferenceMark oldMark = mMarksByName.get(aOldName);
+ mMarksByName.remove(aOldName);
+ mMarksByName.put(aNewName, oldMark);
+ }
+
+ /**
+ * Gets the ID of a ReferenceMark
+ * @param aMark
+ * @return
+ */
+ int getIDForMark(ReferenceMark aMark) {
+ return mIDsByMark.get(aMark);
+ }
+
+ /**
+ * Gets a ReferenceMark given an ID
+ * @param ID
+ * @return
+ */
+ ReferenceMark getMarkForID(int ID) {
+ return mMarksByID.get(ID);
+ }
+
+ /**
+ * Gets a ReferenceMark given an UNO object corresponding to it
+ * @param aMark UNO object corresponding to ReferenceMark (or Bookmark)
+ * @param aFieldType "ReferenceMark" or "Bookmark"
+ * @return
+ */
+ ReferenceMark getMark(Object aMark, String aFieldType) {
+ if(aMark == null) {
+ return null;
+ }
+
+ XNamed named = (XNamed) UnoRuntime.queryInterface(XNamed.class, aMark);
+ String name = named.getName();
+
+ // Return hashed mark if it exists
+ ReferenceMark retMark = mMarksByName.get(name);
+ if(retMark != null) {
+ return retMark;
+ }
+
+ // Create new mark
+ for(String prefix : Document.PREFIXES) {
+ if(name.contains(prefix)) {
+ try {
+ if(aFieldType.equals("ReferenceMark")) {
+ retMark = new ReferenceMark(mDoc, named, name);
+ } else if(aFieldType.equals("Bookmark")) {
+ retMark = new Bookmark(mDoc, named, name);
+ } else {
+ return null;
+ }
+ mMarksByName.put(name, retMark);
+ mIDsByMark.put(retMark, mMarksByID.size());
+ mMarksByID.add(retMark);
+ } catch (IllegalArgumentException e) {}
+ return retMark;
+ }
+ }
+
+ return null;
+ }
+}
diff --git a/build/source/org/zotero/integration/ooo/comp/Properties.java b/build/source/org/zotero/integration/ooo/comp/Properties.java
new file mode 100644
index 0000000..512b5ab
--- /dev/null
+++ b/build/source/org/zotero/integration/ooo/comp/Properties.java
@@ -0,0 +1,100 @@
+/*
+ ***** BEGIN LICENSE BLOCK *****
+
+ Copyright (c) 2017 Zotero
+ Center for History and New Media
+ George Mason University, Fairfax, Virginia, USA
+ http://zotero.org
+
+ Zotero is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Zotero is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with Zotero. If not, see <http://www.gnu.org/licenses/>.
+
+ ***** END LICENSE BLOCK *****
+*/
+
+package org.zotero.integration.ooo.comp;
+
+import com.sun.star.beans.NotRemoveableException;
+import com.sun.star.beans.PropertyExistException;
+import com.sun.star.beans.UnknownPropertyException;
+import com.sun.star.beans.XPropertyContainer;
+import com.sun.star.beans.XPropertySet;
+import com.sun.star.document.XDocumentPropertiesSupplier;
+import com.sun.star.lang.XComponent;
+import com.sun.star.uno.Any;
+import com.sun.star.uno.UnoRuntime;
+
+public class Properties {
+ private static final int MAX_PROPERTY_LENGTH = 255;
+ private XPropertySet propertySet;
+ private XPropertyContainer propertyContainer;
+
+ public Properties(XComponent component) {
+ XDocumentPropertiesSupplier docInfoSupplier = (XDocumentPropertiesSupplier) UnoRuntime.queryInterface(XDocumentPropertiesSupplier.class, component);
+ XPropertyContainer docProperties = docInfoSupplier.getDocumentProperties().getUserDefinedProperties();
+ propertySet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, docProperties);
+ propertyContainer = (XPropertyContainer) UnoRuntime.queryInterface(XPropertyContainer.class, docProperties);
+ }
+
+ public String getProperty(String propertyName) throws Exception {
+ int i = 0;
+ String propertyValue = "";
+ Object val;
+
+ while(true) {
+ i++;
+ try {
+ val = propertySet.getPropertyValue(propertyName+"_"+i);
+ } catch(UnknownPropertyException e) {
+ break;
+ }
+
+ if(val.getClass() == Any.class && val.equals(Any.VOID)) {
+ break;
+ } else {
+ propertyValue += val;
+ }
+ }
+
+ return propertyValue;
+ }
+
+ public void setProperty(String propertyName, String propertyValue) throws Exception {
+ int i = 0;
+ int propertyLength = propertyValue.length();
+
+ while(propertyLength > i*MAX_PROPERTY_LENGTH) {
+ i = i + 1;
+ String docPropertyName = propertyName+"_"+i;
+ String docPropertyValue = propertyValue.substring((i-1)*MAX_PROPERTY_LENGTH, Math.min(i*MAX_PROPERTY_LENGTH, propertyLength));
+ try {
+ propertyContainer.addProperty(docPropertyName, (short) 0, "");
+ } catch(PropertyExistException e) {}
+ propertySet.setPropertyValue(docPropertyName, docPropertyValue);
+ }
+
+ while(true) {
+ i = i + 1;
+ try {
+ String docPropertyName = propertyName+"_"+i;
+ try {
+ propertyContainer.removeProperty(docPropertyName);
+ } catch(NotRemoveableException e) {
+ propertySet.setPropertyValue(docPropertyName, "");
+ }
+ } catch(UnknownPropertyException e) {
+ break;
+ }
+ }
+ }
+}
diff --git a/build/source/org/zotero/integration/ooo/comp/ReferenceMark.java b/build/source/org/zotero/integration/ooo/comp/ReferenceMark.java
new file mode 100644
index 0000000..8709144
--- /dev/null
+++ b/build/source/org/zotero/integration/ooo/comp/ReferenceMark.java
@@ -0,0 +1,520 @@
+/*
+ ***** BEGIN LICENSE BLOCK *****
+
+ Copyright (c) 2017 Zotero
+ Center for History and New Media
+ George Mason University, Fairfax, Virginia, USA
+ http://zotero.org
+
+ Zotero is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Zotero is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with Zotero. If not, see <http://www.gnu.org/licenses/>.
+
+ ***** END LICENSE BLOCK *****
+*/
+
+package org.zotero.integration.ooo.comp;
+
+import java.io.UnsupportedEncodingException;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import com.sun.star.beans.PropertyValue;
+import com.sun.star.beans.UnknownPropertyException;
+import com.sun.star.beans.XMultiPropertyStates;
+import com.sun.star.beans.XPropertySet;
+import com.sun.star.container.XNamed;
+import com.sun.star.document.XDocumentInsertable;
+import com.sun.star.frame.XDispatchHelper;
+import com.sun.star.frame.XDispatchProvider;
+import com.sun.star.lang.WrappedTargetException;
+import com.sun.star.lang.XComponent;
+import com.sun.star.lang.XServiceInfo;
+import com.sun.star.text.ControlCharacter;
+import com.sun.star.text.XFootnote;
+import com.sun.star.text.XSimpleText;
+import com.sun.star.text.XText;
+import com.sun.star.text.XTextContent;
+import com.sun.star.text.XTextCursor;
+import com.sun.star.text.XTextRange;
+import com.sun.star.text.XTextRangeCompare;
+import com.sun.star.uno.Any;
+import com.sun.star.uno.UnoRuntime;
+
+public class ReferenceMark implements Comparable<ReferenceMark> {
+ // NOTE: This list must be sorted. See the API docs for XMultiPropertySet for more details.
+ private static final String[] PROPERTIES_CHANGE_TO_DEFAULT =
+ {"CharCaseMap", "CharEscapement", "CharEscapementHeight", "CharPosture", "CharUnderline", "CharWeight"};
+
+ protected Document doc;
+ protected XTextRangeCompare textRangeCompare;
+ protected XTextContent textContent;
+ XTextRange range;
+ protected XText text;
+ protected XNamed named;
+ protected boolean isNote;
+ XTextContent table;
+ protected boolean isTextSection;
+ protected boolean isDisposable;
+ String rawCode;
+
+ public ReferenceMark(Document aDoc, XNamed aMark, String aCode) throws IllegalArgumentException {
+ doc = aDoc;
+ textContent = (XTextContent) UnoRuntime.queryInterface(XTextContent.class, aMark);
+ range = textContent.getAnchor();
+ if(range == null) {
+ throw new IllegalArgumentException("no anchor for textContent");
+ }
+ text = range.getText();
+ named = aMark;
+
+ XServiceInfo serviceInfo = (XServiceInfo) UnoRuntime.queryInterface(XServiceInfo.class, text);
+ isNote = serviceInfo.supportsService("com.sun.star.text.Footnote");
+ if(serviceInfo.supportsService("com.sun.star.text.CellProperties")) {
+ // is in a table
+ try {
+ table = (XTextContent) UnoRuntime.queryInterface(XTextContent.class,
+ ((XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, range)).getPropertyValue("TextTable"));
+ } catch (UnknownPropertyException e) {
+ throw new IllegalArgumentException("TextTable property unknown on an apparent TextTable");
+ } catch (WrappedTargetException e) {
+ throw new IllegalArgumentException("WrappedTargetException on an apparent TextTable");
+ }
+ } else {
+ table = null;
+ }
+ serviceInfo = (XServiceInfo) UnoRuntime.queryInterface(XServiceInfo.class, aMark);
+ isTextSection = serviceInfo.supportsService("com.sun.star.text.TextSection");
+ isDisposable = isTextSection;
+
+ serviceInfo = (XServiceInfo) UnoRuntime.queryInterface(XServiceInfo.class, aMark);
+
+ textRangeCompare = (XTextRangeCompare) UnoRuntime.queryInterface(XTextRangeCompare.class, text);
+
+ rawCode = aCode;
+ }
+
+ public void delete() throws Exception {
+ if(isWholeRange()) {
+ ((XComponent) UnoRuntime.queryInterface(XComponent.class, text)).dispose();
+ } else {
+ XTextCursor dupRange = text.createTextCursorByRange(range);
+ text.removeTextContent(textContent);
+ range = dupRange;
+
+ // dispose of a Bookmark or TextSection
+ if(isDisposable) {
+ ((XComponent) UnoRuntime.queryInterface(XComponent.class, textContent)).dispose();
+ }
+ }
+ }
+
+ public void removeCode() throws Exception {
+ if(isDisposable) {
+ ((XComponent) UnoRuntime.queryInterface(XComponent.class, textContent)).dispose();
+ } else {
+ String oldContents = range.getString();
+ if(oldContents.equals("")) {
+ // One cannot simply overwrite an empty ReferenceMark
+ XTextCursor dupRange = text.createTextCursorByRange(range);
+ text.removeTextContent(textContent);
+ range = dupRange;
+ } else {
+ // TODO: won't work with formatted text
+ range.setString(oldContents);
+ }
+ }
+ }
+
+ public void select() throws Exception {
+ XTextCursor cursor = doc.getSelection();
+ cursor.gotoRange(range, false);
+ if(isTextSection) {
+ cursor.goLeft((short) 1, true);
+ }
+ }
+
+ public String getText() throws Exception {
+ return range.getString();
+ }
+
+ public void setText(String textString, boolean isRich) throws Exception {
+ boolean isBibliography = getCode().startsWith("BIBL");
+ XTextCursor viewCursor = doc.getSelection();
+
+ if(isBibliography) {
+ prepareMultiline();
+ }
+
+ XTextCursor cursor = text.createTextCursorByRange(range);
+ if(!isBibliography && range.getString().equals("")) {
+ // One cannot simply overwrite an empty ReferenceMark
+ text.removeTextContent(textContent);
+ }
+ range = cursor;
+
+ if(!isBibliography) {
+ // move citation to its own paragraph so its formatting isn't altered automatically
+ // because of the text on either side of it
+ if(isRich) {
+ int previousLen = range.getString().length();
+ text.insertControlCharacter(range, ControlCharacter.PARAGRAPH_BREAK, false);
+ text.insertControlCharacter(range.getEnd(), ControlCharacter.PARAGRAPH_BREAK, false);
+ cursor.collapseToStart();
+
+ // But don't move the cursor to the note
+ if (!isNote) {
+ // LibreOffice crashes while inserting RTF if we don't move the viewCursor here.
+ // Affects Ubuntu and maybe MacOS.
+ // Don't ask me why it crashes though.
+ viewCursor.gotoRange((XTextRange) cursor, false);
+ viewCursor.goLeft((short)1, false);
+ }
+
+ moveCursorRight(cursor, previousLen);
+ }
+ }
+
+ XMultiPropertyStates rangePropStates = (XMultiPropertyStates) UnoRuntime.queryInterface(XMultiPropertyStates.class, cursor);
+ rangePropStates.setPropertiesToDefault(PROPERTIES_CHANGE_TO_DEFAULT);
+
+ if(isRich) {
+ XPropertySet rangeProps = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, range);
+
+ if(isBibliography) {
+ /*// Add a new line to the start of the bibliography so that the paragraph format
+ // for the first entry will be correct. Without the new line, when converting
+ // citation styles, the first entry of the bibliography will keep the same paragraph
+ // formatting as the previous citation style
+ textString = "{\\rtf\\\n" + textString.substring(6);*/
+ insertRTF(textString, cursor);
+ // Remove the new line from the bibliography (added above). Have to remove the
+ // new line before the textSection and then adjust the range so the new line
+ // starting the textSection is outside of the range so that the
+ // paragraph formatting of the first entry remains unchanged. Also remove the
+ // extra new line at the end of the textSection.
+ String rangeString = cursor.getString();
+ int previousLen = rangeString.length();
+ int removeLastNewLine = 0;
+ if(rangeString.codePointAt(previousLen-1) == 10) {
+ removeLastNewLine = 1;
+ XTextCursor dupRange = text.createTextCursorByRange(range);
+ dupRange.collapseToEnd();
+ dupRange.goLeft((short) 1, true);
+ dupRange.setString("");
+ }
+ cursor.collapseToStart();
+ moveCursorRight(cursor, previousLen-removeLastNewLine);
+ rangeProps.setPropertyValue("ParaStyleName", "Bibliography 1");
+ } else {
+ String oldParaStyle = (String) rangeProps.getPropertyValue("ParaStyleName");
+
+ insertRTF(textString, cursor);
+
+ // Inserting RTF in LibreOffice 4 resets the style to the document default, so
+ // we set it back to whatever it was before we inserted the RTF. However,
+ // setting the paragraph style will reset superscript and other character
+ // properties specified by the style, so we need to explicitly preserve these.
+ Object[] oldPropertyValues = new Object[PROPERTIES_CHANGE_TO_DEFAULT.length];
+ for(int i=0; i<PROPERTIES_CHANGE_TO_DEFAULT.length; i++) {
+ Object result = rangeProps.getPropertyValue(PROPERTIES_CHANGE_TO_DEFAULT[i]);
+ oldPropertyValues[i] = result instanceof Any ? ((Any) result).getObject() : result;
+ }
+ rangeProps.setPropertyValue("ParaStyleName", oldParaStyle);
+ for(int i=0; i<PROPERTIES_CHANGE_TO_DEFAULT.length; i++) {
+ if(oldPropertyValues[i] != null) {
+ rangeProps.setPropertyValue(PROPERTIES_CHANGE_TO_DEFAULT[i], oldPropertyValues[i]);
+ }
+ }
+ }
+ } else {
+ range.setString(textString);
+ }
+
+ reattachMark();
+
+ if(!isBibliography) {
+ if(isRich) {
+ // remove previously added paragraphs
+ XTextCursor dupRange;
+ dupRange = text.createTextCursorByRange(range);
+ dupRange.collapseToEnd();
+ dupRange.goRight((short) 1, true);
+ String str = dupRange.getString();
+ // getString() returns different newline characters for different OSes
+ if(str.equals("\n") || str.equals("\r\n")) {
+ dupRange.setString("");
+ }
+ dupRange.goLeft((short) 1, true);
+ str = dupRange.getString();
+ if(str.equals("\n") || str.equals("\r\n")) {
+ dupRange.setString("");
+ }
+
+ if (!isNote) {
+ // Restoring cursor position from crash-prevention jiggle
+ viewCursor.gotoRange(dupRange, false);
+ viewCursor.collapseToEnd();
+ }
+
+ dupRange = text.createTextCursorByRange(range);
+ dupRange.collapseToStart();
+ dupRange.goLeft((short) 1, true);
+ dupRange.setString("");
+ }
+
+ getOutOfField();
+ }
+ }
+
+ public void setCode(String code) throws Exception {
+ String oldRawCode = rawCode;
+ rawCode = Document.PREFIXES[0] + code + " RND" + Document.getRandomString(Document.REFMARK_ADD_CHARS);
+ doc.mMarkManager.renameMark(oldRawCode, rawCode);
+ if(isTextSection) {
+ named.setName(rawCode);
+ } else {
+ // The only way to rename a ReferenceMark is to delete it and add it again
+ removeCode();
+ reattachMark();
+ }
+ }
+
+ public String getCode() throws Exception {
+ int rnd = rawCode.lastIndexOf(" RND");
+ if(rnd == -1) rnd = rawCode.length()-6; // for compatibility with old, pre-release Python plug-in
+ for(String prefix : Document.PREFIXES) {
+ int index = rawCode.indexOf(prefix);
+ if(index != -1) {
+ if(rnd > 0) {
+ return rawCode.substring(index+prefix.length(), rnd);
+ } else {
+ return rawCode;
+ }
+ }
+ }
+
+ throw new Exception("Invalid code prefix");
+ }
+
+ public Integer getNoteIndex() throws Exception {
+ if(isNote) {
+ // Only works for numbered notes; won't work if a note is referenced by a letter
+ try {
+ return Integer.parseInt(((XFootnote) UnoRuntime.queryInterface(XFootnote.class, text)).getAnchor().getString());
+ } catch(NumberFormatException e) {}
+ }
+ return 0;
+ }
+
+ public boolean equals(Object o) {
+ // impossible to have two ReferenceMarks/Bookmarks with the same name
+ return ((ReferenceMark) o).rawCode.equals(rawCode);
+ }
+
+ public int hashCode() {
+ return rawCode.hashCode();
+ }
+
+ XTextRange getDocumentRange() {
+ if(isNote) {
+ return ((XTextContent) UnoRuntime.queryInterface(XTextContent.class, text)).getAnchor();
+ } else if(table != null) {
+ String tableName = ((XNamed) UnoRuntime.queryInterface(XNamed.class, table)).getName();
+ if(doc.textTableManager == null) doc.textTableManager = new TextTableManager(doc.textDocument);
+ return doc.textTableManager.getRangeForTable(tableName);
+ } else {
+ return range;
+ }
+ }
+
+ public int compareTo(ReferenceMark o) {
+ XTextRange range1, range2;
+ range1 = getDocumentRange();
+ range2 = o.getDocumentRange();
+
+ int cmp = 0;
+ try {
+ cmp = doc.textRangeCompare.compareRegionStarts(range2, range1);
+ } catch (com.sun.star.lang.IllegalArgumentException e) {
+ // Assume that all ranges we don't recognize come at the end of the document
+ try {
+ doc.textRangeCompare.compareRegionStarts(range1, range1);
+ return -1;
+ } catch (com.sun.star.lang.IllegalArgumentException e1) {
+ try {
+ doc.textRangeCompare.compareRegionStarts(range2, range2);
+ return 1;
+ } catch (com.sun.star.lang.IllegalArgumentException e2) {
+ return 0;
+ }
+ }
+ }
+
+ if(cmp == 0) {
+ if(isNote && o.isNote) {
+ try {
+ cmp = textRangeCompare.compareRegionStarts(o.range, range);
+ } catch (Exception e) {
+ //doc.displayAlert(Document.getErrorString(e), 0, 0);
+ e.printStackTrace();
+ return 0;
+ }
+ } else if(table != null && o.table != null) {
+ // This ought to mean they are both in the same table
+
+ // First, get cell names
+ XPropertySet cell1 = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, text);
+ XPropertySet cell2 = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, o.text);
+ String cell1Name, cell2Name;
+ try {
+ cell1Name = (String) cell1.getPropertyValue("CellName");
+ cell2Name = (String) cell2.getPropertyValue("CellName");
+ } catch (Exception e) {
+ //doc.displayAlert(Document.getErrorString(e), 0, 0);
+ e.printStackTrace();
+ return 0;
+ }
+
+ if(cell1Name.equals(cell2Name)) {
+ // should be in the same cell; compare ranges directly
+ try {
+ cmp = textRangeCompare.compareRegionStarts(o.range, range);
+ } catch (Exception e) {
+ //doc.displayAlert(Document.getErrorString(e), 0, 0);
+ e.printStackTrace();
+ return 0;
+ }
+ } else {
+ // different cells in the same table
+ // split apart names with regular expressions
+ Pattern p = Pattern.compile("([^0-9]+)([0-9]+)");
+ Matcher m1 = p.matcher(cell1Name);
+ Matcher m2 = p.matcher(cell2Name);
+ if(!m1.matches() || !m2.matches()) {
+ return cell1Name.compareTo(cell2Name);
+ }
+ Integer int1 = Integer.parseInt(m1.group(2));
+ Integer int2 = Integer.parseInt(m2.group(2));
+ if(int1 == int2) {
+ // compare column numbers
+ return m1.group(1).compareTo(m2.group(1));
+ } else {
+ // compare row numbers
+ return int1.compareTo(int2);
+ }
+ }
+ }
+ }
+
+ return cmp;
+ }
+
+ XTextCursor getReplacementCursor() throws Exception {
+ if(isWholeRange()) {
+ XFootnote footnote = (XFootnote) UnoRuntime.queryInterface(XFootnote.class, text);
+ return doc.text.createTextCursorByRange(footnote.getAnchor());
+ } else {
+ XTextCursor cursor = text.createTextCursorByRange(range);
+ if(isDisposable) {
+ // dispose of text section
+ ((XComponent) UnoRuntime.queryInterface(XComponent.class, textContent)).dispose();
+ }
+ return cursor;
+ }
+ }
+
+ protected void prepareMultiline() throws Exception {
+ if(!isTextSection) { // need to convert to TextSection
+ delete();
+
+ // add a paragraph before creating multiline field at end of document
+ // if this is not done, it's hard to add text after the TextSection
+ if(doc.textRangeCompare.compareRegionEnds(doc.text.getEnd(), range.getEnd()) == 0) {
+ doc.text.insertControlCharacter(doc.text.getEnd(), ControlCharacter.PARAGRAPH_BREAK, false);
+ doc.text.insertControlCharacter(doc.text.getEnd(), ControlCharacter.PARAGRAPH_BREAK, false);
+ XTextCursor cursor = doc.text.createTextCursorByRange(doc.text.getEnd());
+ cursor.goLeft((short) 1, false);
+ cursor.goLeft((short) 1, true);
+ range = cursor;
+ }
+
+ named = (XNamed) UnoRuntime.queryInterface(XNamed.class,
+ doc.docFactory.createInstance("com.sun.star.text.TextSection"));
+ named.setName(rawCode);
+ textContent = (XTextContent) UnoRuntime.queryInterface(XTextContent.class, named);
+ textContent.attach(range);
+
+ isTextSection = true;
+ isDisposable = true;
+ }
+ }
+
+ protected void reattachMark() throws Exception {
+ if(isTextSection) return;
+
+ named = (XNamed) UnoRuntime.queryInterface(XNamed.class,
+ doc.docFactory.createInstance("com.sun.star.text.ReferenceMark"));
+ named.setName(rawCode);
+ textContent = (XTextContent) UnoRuntime.queryInterface(XTextContent.class, named);
+ textContent.attach(range);
+ }
+
+ protected void moveCursorRight(XTextCursor cursor, int length) {
+ short step;
+ for(int i=length; i>0; i-=step) {
+ step = (short) Math.min(i, 32767);
+ cursor.goRight(step, true);
+ }
+ }
+
+ private boolean isWholeRange() throws Exception {
+ if(isNote) {
+ // delete footnote, if this is the only thing in it
+ XSimpleText noteSimpleText = (XSimpleText) UnoRuntime.queryInterface(XSimpleText.class, text);
+ XTextRange noteRange = (XTextRange) UnoRuntime.queryInterface(XTextRange.class, noteSimpleText);
+
+ return (textRangeCompare.compareRegionStarts(range, noteRange) == 0 && textRangeCompare.compareRegionEnds(range, noteRange) == 0);
+ }
+ return false;
+ }
+
+ private void getOutOfField() {
+ try {
+ XTextCursor cursor = doc.getSelection();
+ if(cursor.isCollapsed() && textRangeCompare.compareRegionEnds(cursor, range) == 0) {
+ cursor.gotoRange(range.getEnd(), false);
+ XDispatchProvider dispatchProvider = (XDispatchProvider) UnoRuntime.
+ queryInterface(XDispatchProvider.class, doc.controller);
+ XDispatchHelper dispatchHelper = (XDispatchHelper) UnoRuntime.
+ queryInterface(XDispatchHelper.class, doc.factory.createInstance("com.sun.star.frame.DispatchHelper"));
+ dispatchHelper.executeDispatch(dispatchProvider, ".uno:ResetAttributes", "", 0, new PropertyValue[] {});
+ }
+ } catch(Exception e) {}
+ }
+
+ private void insertRTF(String text, XTextCursor cursor) throws Exception {
+ PropertyValue filterName = new PropertyValue();
+ filterName.Name = "FilterName";
+ filterName.Value = "Rich Text Format";
+ PropertyValue inputStream = new PropertyValue();
+ inputStream.Name = "InputStream";
+ try {
+ inputStream.Value = new StringInputStream(text.getBytes("ISO-8859-1"));
+ } catch (UnsupportedEncodingException e) {
+ return;
+ }
+
+ ((XDocumentInsertable) UnoRuntime.queryInterface(XDocumentInsertable.class, cursor)).
+ insertDocumentFromURL("private:stream", new PropertyValue[] {filterName, inputStream});
+ }
+}
diff --git a/build/source/org/zotero/integration/ooo/comp/RegistrationHandler.classes b/build/source/org/zotero/integration/ooo/comp/RegistrationHandler.classes
new file mode 100644
index 0000000..0f9005a
--- /dev/null
+++ b/build/source/org/zotero/integration/ooo/comp/RegistrationHandler.classes
@@ -0,0 +1 @@
+org.zotero.integration.ooo.comp.ZoteroOpenOfficeIntegrationImpl
diff --git a/build/source/org/zotero/integration/ooo/comp/RegistrationHandler.java b/build/source/org/zotero/integration/ooo/comp/RegistrationHandler.java
new file mode 100644
index 0000000..8870c61
--- /dev/null
+++ b/build/source/org/zotero/integration/ooo/comp/RegistrationHandler.java
@@ -0,0 +1,176 @@
+/*************************************************************************
+ *
+ * The Contents of this file are made available subject to the terms of
+ * either of the GNU Lesser General Public License Version 2.1
+ *
+ * Sun Microsystems Inc., October, 2000
+ *
+ *
+ * GNU Lesser General Public License Version 2.1
+ * =============================================
+ * Copyright 2000 by Sun Microsystems, Inc.
+ * 901 San Antonio Road, Palo Alto, CA 94303, USA
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License version 2.1, as published by the Free Software Foundation.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
+ * MA 02111-1307 USA
+ *
+ * The Initial Developer of the Original Code is: Sun Microsystems, Inc..
+ *
+ * Copyright: 2002 by Sun Microsystems, Inc.
+ *
+ * All Rights Reserved.
+ *
+ * Contributor(s): Cedric Bosdonnat
+ *
+ *
+ ************************************************************************/
+package org.zotero.integration.ooo.comp;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.LineNumberReader;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+
+import com.sun.star.lang.XSingleComponentFactory;
+import com.sun.star.registry.XRegistryKey;
+
+/**
+ * Component main registration class.
+ *
+ * <p><strong>This class should not be modified.</strong></p>
+ *
+ * @author Cedric Bosdonnat aka. cedricbosdo
+ *
+ */
+public class RegistrationHandler {
+
+ /**
+ * Get a component factory for the implementations handled by this class.
+ *
+ * <p>This method calls all the methods of the same name from the classes listed
+ * in the <code>RegistrationHandler.classes</code> file. <strong>This method
+ * should not be modified.</strong></p>
+ *
+ * @param pImplementationName the name of the implementation to create.
+ *
+ * @return the factory which can create the implementation.
+ */
+ @SuppressWarnings("unchecked")
+ public static XSingleComponentFactory __getComponentFactory(String sImplementationName ) {
+ XSingleComponentFactory xFactory = null;
+
+ Class[] classes = findServicesImplementationClasses();
+
+ int i = 0;
+ while (i < classes.length && xFactory == null) {
+ Class clazz = classes[i];
+ if ( sImplementationName.equals( clazz.getCanonicalName() ) ) {
+ try {
+ Class[] getTypes = new Class[]{String.class};
+ Method getFactoryMethod = clazz.getMethod("__getComponentFactory", getTypes);
+ Object o = getFactoryMethod.invoke(null, sImplementationName);
+ xFactory = (XSingleComponentFactory)o;
+ } catch (Exception e) {
+ // Nothing to do: skip
+ System.err.println("Error happened");
+ e.printStackTrace();
+ }
+ }
+ i++;
+ }
+ return xFactory;
+ }
+
+ /**
+ * Writes the services implementation informations to the UNO registry.
+ *
+ * <p>This method calls all the methods of the same name from the classes listed
+ * in the <code>RegistrationHandler.classes</code> file. <strong>This method
+ * should not be modified.</strong></p>
+ *
+ * @param pRegistryKey the root registry key where to write the informations.
+ *
+ * @return <code>true</code> if the informations have been successfully written
+ * to the registry key, <code>false</code> otherwise.
+ */
+ @SuppressWarnings("unchecked")
+ public static boolean __writeRegistryServiceInfo(XRegistryKey xRegistryKey ) {
+ Class[] classes = findServicesImplementationClasses();
+
+ boolean success = true;
+ int i = 0;
+ while (i < classes.length && success) {
+ Class clazz = classes[i];
+ try {
+ Class[] writeTypes = new Class[]{XRegistryKey.class};
+ Method getFactoryMethod = clazz.getMethod("__writeRegistryServiceInfo", writeTypes);
+ Object o = getFactoryMethod.invoke(null, xRegistryKey);
+ success = success && ((Boolean)o).booleanValue();
+ } catch (Exception e) {
+ success = false;
+ e.printStackTrace();
+ }
+ i++;
+ }
+ return success;
+ }
+
+ /**
+ * @return all the UNO implementation classes.
+ */
+ @SuppressWarnings("unchecked")
+ private static Class[] findServicesImplementationClasses() {
+ ArrayList<Class> classes = new ArrayList<Class>();
+
+ InputStream in = RegistrationHandler.class.getResourceAsStream("RegistrationHandler.classes");
+ LineNumberReader reader = new LineNumberReader(new InputStreamReader(in));
+
+ try {
+ String line = reader.readLine();
+ while (line != null) {
+ if (!line.equals("")) {
+ line = line.trim();
+ try {
+ Class clazz = Class.forName(line);
+
+ Class[] writeTypes = new Class[]{XRegistryKey.class};
+ Class[] getTypes = new Class[]{String.class};
+
+ Method writeRegMethod = clazz.getMethod("__writeRegistryServiceInfo", writeTypes);
+ Method getFactoryMethod = clazz.getMethod("__getComponentFactory", getTypes);
+
+ if (writeRegMethod != null && getFactoryMethod != null) {
+ classes.add(clazz);
+ }
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ line = reader.readLine();
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ } finally {
+ try {
+ reader.close();
+ in.close();
+ } catch (Exception e) {};
+ }
+
+ return classes.toArray(new Class[classes.size()]);
+ }
+}
diff --git a/build/source/org/zotero/integration/ooo/comp/SaveEventListener.java b/build/source/org/zotero/integration/ooo/comp/SaveEventListener.java
new file mode 100644
index 0000000..f9af786
--- /dev/null
+++ b/build/source/org/zotero/integration/ooo/comp/SaveEventListener.java
@@ -0,0 +1,104 @@
+/*
+ ***** BEGIN LICENSE BLOCK *****
+
+ Copyright (c) 2017 Zotero
+ Center for History and New Media
+ George Mason University, Fairfax, Virginia, USA
+ http://zotero.org
+
+ Zotero is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Zotero is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with Zotero. If not, see <http://www.gnu.org/licenses/>.
+
+ ***** END LICENSE BLOCK *****
+*/
+
+package org.zotero.integration.ooo.comp;
+
+import java.util.Hashtable;
+
+import com.sun.star.awt.MessageBoxButtons;
+import com.sun.star.awt.MessageBoxType;
+import com.sun.star.awt.XMessageBox;
+import com.sun.star.awt.XMessageBoxFactory;
+import com.sun.star.awt.XWindowPeer;
+import com.sun.star.beans.UnknownPropertyException;
+import com.sun.star.beans.XPropertySet;
+import com.sun.star.document.EventObject;
+import com.sun.star.document.XEventBroadcaster;
+import com.sun.star.document.XEventListener;
+import com.sun.star.frame.XFrame;
+import com.sun.star.frame.XModel;
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.lang.WrappedTargetException;
+import com.sun.star.lang.XComponent;
+
+class SaveEventListener implements XEventListener {
+ Hashtable<String, Boolean> attachedDocuments;
+
+ SaveEventListener() {
+ attachedDocuments = new Hashtable<String, Boolean>();
+ }
+
+ public void notifyEvent(EventObject event) {
+ if(event.EventName.equals("OnSaveAsDone") || event.EventName.equals("OnSaveDone")) {
+ // check if document is saved in OpenDocument format
+ XModel component = (XModel) UnoRuntime.queryInterface(XModel.class, event.Source);
+ String docURL = component.getURL();
+ if(docURL.endsWith(".odt") || docURL.endsWith(".oxt") || docURL.endsWith(".sxw") || docURL.endsWith(".fodt")) return;
+
+ // if not, complain
+ XFrame frame = Application.desktop.getCurrentFrame();
+ XWindowPeer xWindow = (XWindowPeer) UnoRuntime.queryInterface(XWindowPeer.class, frame.getContainerWindow());
+ XMessageBoxFactory xToolkit = (XMessageBoxFactory) UnoRuntime.queryInterface(XMessageBoxFactory.class, xWindow.getToolkit());
+ XMessageBox box = xToolkit.createMessageBox(xWindow, MessageBoxType.WARNINGBOX,
+ MessageBoxButtons.BUTTONS_OK, "Zotero Integration",
+ Document.SAVE_WARNING_STRING);
+ box.execute();
+ }
+ }
+
+ public void disposing(com.sun.star.lang.EventObject event) {
+ XComponent component = (XComponent) UnoRuntime.queryInterface(XComponent.class, event.Source);
+ String runtimeUID;
+ try {
+ runtimeUID = (String) ((XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, component)).getPropertyValue("RuntimeUID");
+ detachFrom(component, runtimeUID);
+ } catch (UnknownPropertyException e) {
+ } catch (WrappedTargetException e) {}
+ }
+
+ /**
+ * Attaches event listener to a specified document
+ * @param component Document to attach to
+ */
+ void attachTo(XComponent component, String runtimeUID) {
+ if(attachedDocuments.containsKey(runtimeUID)) return;
+ XEventBroadcaster eventBroadcaster = (XEventBroadcaster) UnoRuntime.queryInterface(XEventBroadcaster.class, component);
+ if(eventBroadcaster != null) {
+ eventBroadcaster.addEventListener(this);
+ attachedDocuments.put(runtimeUID, true);
+ }
+ }
+
+ /**
+ * Detaches event listener from a specified document
+ * @param component Document to detach from
+ */
+ void detachFrom(XComponent component, String runtimeUID) {
+ if(attachedDocuments.containsKey(runtimeUID)) {
+ XEventBroadcaster eventBroadcaster = (XEventBroadcaster) UnoRuntime.queryInterface(XEventBroadcaster.class, component);
+ eventBroadcaster.removeEventListener(this);
+ attachedDocuments.remove(runtimeUID);
+ }
+ }
+}
diff --git a/build/source/org/zotero/integration/ooo/comp/StringInputStream.java b/build/source/org/zotero/integration/ooo/comp/StringInputStream.java
new file mode 100644
index 0000000..85b638d
--- /dev/null
+++ b/build/source/org/zotero/integration/ooo/comp/StringInputStream.java
@@ -0,0 +1,106 @@
+/*
+ ***** BEGIN LICENSE BLOCK *****
+
+ Copyright (c) 2017 Zotero
+ Center for History and New Media
+ George Mason University, Fairfax, Virginia, USA
+ http://zotero.org
+
+ Zotero is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Zotero is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with Zotero. If not, see <http://www.gnu.org/licenses/>.
+
+ ***** END LICENSE BLOCK *****
+*/
+
+package org.zotero.integration.ooo.comp;
+
+import java.io.ByteArrayInputStream;
+
+import com.sun.star.io.BufferSizeExceededException;
+import com.sun.star.io.NotConnectedException;
+import com.sun.star.io.XInputStream;
+import com.sun.star.io.XSeekable;
+
+/**
+* <a href="http://www.oooforum.org/forum/viewtopic.phtml?t=13205">OOInputStream from the thread <b>OOo-Java: Using XInputStream...</b></a>
+*/
+public class StringInputStream extends ByteArrayInputStream implements XInputStream, XSeekable {
+
+ public StringInputStream(byte[] buf) {
+ super(buf);
+ }
+
+
+ //
+ // Implement XInputStream
+ //
+
+ public int readBytes(byte[][] buffer, int bufferSize) throws NotConnectedException, BufferSizeExceededException, com.sun.star.io.IOException {
+ int numberOfReadBytes;
+ try {
+ byte[] bytes = new byte[bufferSize];
+ numberOfReadBytes = super.read(bytes);
+ if(numberOfReadBytes > 0) {
+ if(numberOfReadBytes < bufferSize) {
+ byte[] smallerBuffer = new byte[numberOfReadBytes];
+ System.arraycopy(bytes, 0, smallerBuffer, 0, numberOfReadBytes);
+ bytes = smallerBuffer;
+ }
+ }
+ else {
+ bytes = new byte[0];
+ numberOfReadBytes = 0;
+ }
+
+ buffer[0]=bytes;
+ return numberOfReadBytes;
+ }
+ catch (java.io.IOException e) {
+ throw new com.sun.star.io.IOException(e.getMessage(),this);
+ }
+ }
+
+ public int readSomeBytes(byte[][] buffer, int bufferSize) throws NotConnectedException, BufferSizeExceededException, com.sun.star.io.IOException {
+ return readBytes(buffer, bufferSize);
+ }
+
+ public void skipBytes(int skipLength) throws NotConnectedException, BufferSizeExceededException, com.sun.star.io.IOException {
+ skip(skipLength);
+ }
+
+ public void closeInput() throws NotConnectedException, com.sun.star.io.IOException {
+ try {
+ close();
+ }
+ catch (java.io.IOException e) {
+ throw new com.sun.star.io.IOException(e.getMessage(), this);
+ }
+ }
+
+
+ //
+ // Implement XSeekable
+ //
+
+ public long getLength() throws com.sun.star.io.IOException {
+ return count;
+ }
+
+ public long getPosition() throws com.sun.star.io.IOException {
+ return pos;
+ }
+
+ public void seek(long position) throws IllegalArgumentException, com.sun.star.io.IOException {
+ pos = (int) position;
+ }
+} \ No newline at end of file
diff --git a/build/source/org/zotero/integration/ooo/comp/TextTableManager.java b/build/source/org/zotero/integration/ooo/comp/TextTableManager.java
new file mode 100644
index 0000000..f89b2ea
--- /dev/null
+++ b/build/source/org/zotero/integration/ooo/comp/TextTableManager.java
@@ -0,0 +1,74 @@
+/*
+ ***** BEGIN LICENSE BLOCK *****
+
+ Copyright (c) 2017 Zotero
+ Center for History and New Media
+ George Mason University, Fairfax, Virginia, USA
+ http://zotero.org
+
+ Zotero is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Zotero is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with Zotero. If not, see <http://www.gnu.org/licenses/>.
+
+ ***** END LICENSE BLOCK *****
+*/
+
+package org.zotero.integration.ooo.comp;
+
+import java.util.HashMap;
+
+import com.sun.star.container.NoSuchElementException;
+import com.sun.star.container.XEnumeration;
+import com.sun.star.container.XEnumerationAccess;
+import com.sun.star.container.XNamed;
+import com.sun.star.lang.WrappedTargetException;
+import com.sun.star.lang.XServiceInfo;
+import com.sun.star.text.XTextDocument;
+import com.sun.star.text.XTextRange;
+import com.sun.star.text.XTextTable;
+import com.sun.star.uno.UnoRuntime;
+
+class TextTableManager {
+ HashMap<String, XTextRange> hash = new HashMap<String, XTextRange>();
+
+ TextTableManager(XTextDocument textDocument) {
+ // This mess derived from http://www.oooforum.org/forum/viewtopic.phtml?t=60451
+ // (thanks to Zotero contributor Iannz and forum member KRzYamaneko)
+ XEnumerationAccess xParaAccess = UnoRuntime.queryInterface(
+ XEnumerationAccess.class, textDocument.getText());
+ XEnumeration xParaEnum = xParaAccess.createEnumeration();
+ XTextRange lastTextRange = null;
+ XTextRange result = null;
+ while (result == null && xParaEnum.hasMoreElements()) {
+ Object elt;
+ try {
+ elt = xParaEnum.nextElement();
+ } catch (NoSuchElementException e) {
+ continue;
+ } catch (WrappedTargetException e) {
+ continue;
+ }
+ XServiceInfo xInfo = UnoRuntime.queryInterface(XServiceInfo.class, elt);
+ if (xInfo.supportsService("com.sun.star.text.TextTable")) {
+ XTextTable xTable = UnoRuntime.queryInterface(XTextTable.class, elt);
+ XNamed xTextTableName = UnoRuntime.queryInterface(XNamed.class, xTable);
+ hash.put(xTextTableName.getName(), lastTextRange.getEnd());
+ } else { // it's a paragraph => no bug to get XTextRange
+ lastTextRange = UnoRuntime.queryInterface(XTextRange.class, elt);
+ }
+ }
+ }
+
+ XTextRange getRangeForTable(String tableName) {
+ return hash.get(tableName);
+ }
+}
diff --git a/build/source/org/zotero/integration/ooo/comp/ZoteroOpenOfficeIntegrationImpl.java b/build/source/org/zotero/integration/ooo/comp/ZoteroOpenOfficeIntegrationImpl.java
new file mode 100644
index 0000000..b5c7919
--- /dev/null
+++ b/build/source/org/zotero/integration/ooo/comp/ZoteroOpenOfficeIntegrationImpl.java
@@ -0,0 +1,139 @@
+/*
+ ***** BEGIN LICENSE BLOCK *****
+
+ Copyright (c) 2017 Zotero
+ Center for History and New Media
+ George Mason University, Fairfax, Virginia, USA
+ http://zotero.org
+
+ Zotero is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Zotero is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with Zotero. If not, see <http://www.gnu.org/licenses/>.
+
+ ***** END LICENSE BLOCK *****
+*/
+
+package org.zotero.integration.ooo.comp;
+
+import com.sun.jna.Library;
+import com.sun.jna.Native;
+import com.sun.jna.Platform;
+import com.sun.star.lang.XSingleComponentFactory;
+import com.sun.star.lib.uno.helper.Factory;
+import com.sun.star.lib.uno.helper.WeakBase;
+import com.sun.star.registry.XRegistryKey;
+import com.sun.star.uno.XComponentContext;
+
+
+public final class ZoteroOpenOfficeIntegrationImpl extends WeakBase
+ implements com.sun.star.task.XJobExecutor,
+ com.sun.star.lang.XServiceInfo
+{
+ private static final String m_implementationName = ZoteroOpenOfficeIntegrationImpl.class.getName();
+ private static final String[] m_serviceNames = {
+ "org.zotero.integration.ooo.ZoteroOpenOfficeIntegration" };
+ private static final String[] WINDOW_NAMES = { "ZoteroMessageWindow", "FirefoxMessageWindow",
+ "MinefieldMessageWindow", "BrowserMessageWindow" };
+ private static final String[] ACTIVATE_FOR_COMMANDS = { "addCitation", "editCitation",
+ "editBibliography", "setDocPrefs" };
+
+ public interface CLibrary extends Library {
+ CLibrary INSTANCE = (Platform.isWindows() ?
+ (CLibrary) Native.loadLibrary("user32", CLibrary.class)
+ : null);
+
+ int FindWindowA(String lpClassName, String lpWindowName);
+ boolean SetForegroundWindow(int hWnd);
+ }
+
+ public static void debugPrint(String msg) {
+ System.out.println("ZoteroOpenOfficeIntegration: "+msg);
+ }
+
+ public ZoteroOpenOfficeIntegrationImpl( XComponentContext context ) throws Exception
+ {
+ Comm.application = new Application(context);
+ debugPrint("Service initialized");
+ };
+
+ public static XSingleComponentFactory __getComponentFactory( String sImplementationName ) {
+ XSingleComponentFactory xFactory = null;
+
+ if ( sImplementationName.equals( m_implementationName ) )
+ xFactory = Factory.createComponentFactory(ZoteroOpenOfficeIntegrationImpl.class, m_serviceNames);
+ return xFactory;
+ }
+
+ public static boolean __writeRegistryServiceInfo( XRegistryKey xRegistryKey ) {
+ return Factory.writeRegistryServiceInfo(m_implementationName,
+ m_serviceNames,
+ xRegistryKey);
+ }
+
+ // com.sun.star.lang.XServiceInfo:
+ public String getImplementationName() {
+ return m_implementationName;
+ }
+
+ public boolean supportsService( String sService ) {
+ int len = m_serviceNames.length;
+
+ for( int i=0; i < len; i++) {
+ if (sService.equals(m_serviceNames[i]))
+ return true;
+ }
+ return false;
+ }
+
+ public String[] getSupportedServiceNames() {
+ return m_serviceNames;
+ }
+
+ public void trigger(String command) {
+ if(Platform.isWindows()) {
+ boolean activateWindow = false;
+ for(String cmd : ACTIVATE_FOR_COMMANDS) {
+ if(command.equals(cmd)) {
+ activateWindow = true;
+ break;
+ }
+ }
+
+ if(activateWindow) {
+ debugPrint("Activating window");
+ // Look for Firefox/Zotero window
+ int hWnd = 0;
+ for(String window : WINDOW_NAMES) {
+ hWnd = CLibrary.INSTANCE.FindWindowA(window, null);
+ if(hWnd != 0) break;
+ }
+
+ // Activate window
+ if(hWnd != 0) {
+ CLibrary.INSTANCE.SetForegroundWindow(hWnd);
+ }
+ }
+ }
+
+ debugPrint("Executing "+command);
+ try {
+ } catch(Exception e) {
+ e.printStackTrace();
+ }
+
+ try {
+ Comm.sendCommand(command);
+ } catch(Exception e) {
+ Comm.showError(Comm.COMMUNICATION_ERROR_STRING, e);
+ }
+ }
+}
diff --git a/chrome.manifest b/chrome.manifest
new file mode 100644
index 0000000..6f6344a
--- /dev/null
+++ b/chrome.manifest
@@ -0,0 +1,14 @@
+overlay chrome://browser/content/browser.xul chrome://zotero-openoffice-integration/content/overlay.xul
+overlay chrome://zotero/content/standalone/standalone.xul chrome://zotero-openoffice-integration/content/overlay.xul
+overlay chrome://zotero/content/preferences/preferences.xul chrome://zotero-openoffice-integration/content/preferences.xul
+overlay chrome://zotero/content/preferences/preferences.xul#cite chrome://zotero-openoffice-integration/content/preferences.xul
+
+content zotero-openoffice-integration chrome/
+resource zotero-openoffice-integration resource/
+
+interfaces components/zoteroIntegration.xpt
+
+component {f43193a1-7060-41a3-8e82-481d58b71e6f} components/zoteroOpenOfficeIntegration.js
+contract @zotero.org/Zotero/integration/initializer?agent=OpenOffice;1 {f43193a1-7060-41a3-8e82-481d58b71e6f}
+component {8478cd98-5ba0-4848-925a-75adffff2dbf} components/zoteroOpenOfficeIntegration.js
+contract @zotero.org/Zotero/integration/application?agent=OpenOffice;1 {8478cd98-5ba0-4848-925a-75adffff2dbf}
diff --git a/chrome/install.js b/chrome/install.js
new file mode 100644
index 0000000..44852aa
--- /dev/null
+++ b/chrome/install.js
@@ -0,0 +1,518 @@
+/*
+ ***** BEGIN LICENSE BLOCK *****
+
+ Copyright (c) 2011 Zotero
+ Center for History and New Media
+ George Mason University, Fairfax, Virginia, USA
+ http://zotero.org
+
+ Zotero is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Zotero is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with Zotero. If not, see <http://www.gnu.org/licenses/>.
+
+ ***** END LICENSE BLOCK *****
+*/
+
+const UNOPKG_RELPATHS = {
+ Mac:[
+ "Contents/MacOS/unopkg"
+ ],
+ Win:[
+ "program\\unopkg.exe"
+ ],
+ Other:[
+ "program/unopkg"
+ ]
+};
+
+var javaCommonCheckComplete = false;
+var wizard, platform, bashProc, neededPackages;
+var breadcrumbs = [];
+
+/*** ROUTINES RUN ON LOAD ***/
+
+/**
+ * Called on initial wizard load
+ */
+function onLoad() {
+ wizard = document.documentElement;
+ javaCommonCheckRun = false;
+
+ for(var param in window.arguments[0].wrappedJSObject) window[param] = window.arguments[0].wrappedJSObject[param];
+
+ if(Zotero.isWin) {
+ checkJRE();
+ } else if(!Zotero.isMac) {
+ wizard.getPageById("intro").next = "java-common";
+
+ checkJavaCommon(function(success) {
+ // if openoffice.org-java-common check succeeds, we don't need to show the page for it
+ javaCommonCheckComplete = true;
+
+ if(success) {
+ wizard.getPageById("intro").next = "openoffice-installations";
+ wizard.getPageById("java-common").next = "openoffice-installations";
+ } else {
+ wizard.getPageById("intro").next = "java-common";
+ wizard.getPageById("java-common").next = "java-common-install";
+ document.getElementById("java-common-required").hidden = false;
+ document.getElementById("java-common-progress").hidden = true;
+ document.getElementById("java-common-packages").textContent = neededPackages.join("\n");
+ }
+
+ if(wizard.currentPage.pageid === "java-common") {
+ wizard.canAdvance = true;
+ if(success) wizard.advance();
+ }
+ });
+ } else {
+ checkMacJDK().then(function(success) {
+ if (!success) {
+ wizard.getPageById("intro").next = "jdk-required";
+ }
+ });
+ }
+}
+
+/**
+ * Check for openoffice.org-java-common and prompt user to install if necessary, or else hide
+ * java-common-page
+ */
+function checkJavaCommon(callback) {
+ neededPackages = [];
+
+ // check for dpkg
+ var dpkg = ZoteroOpenOfficeIntegration.getFile("/usr/bin/dpkg");
+ if(!dpkg.exists()) {
+ callback(true);
+ return;
+ }
+
+ // check for bash
+ var bash = ZoteroOpenOfficeIntegration.getFile("/bin/bash");
+ if(!bash.exists()) {
+ callback(true);
+ return;
+ }
+
+ // check for java
+ var java = ZoteroOpenOfficeIntegration.getFile("/usr/bin/java");
+ var success1 = java.exists();
+ if(!success1) neededPackages.push("default-jre");
+
+ // init processes
+ bashProc = Components.classes["@mozilla.org/process/util;1"].
+ createInstance(Components.interfaces.nsIProcess);
+ bashProc.init(bash);
+
+ checkJavaCommonPkg("openoffice.org-writer", "openoffice.org-java-common", function(success2) {
+ checkJavaCommonPkg("libreoffice-writer", "libreoffice-java-common", function(success3) {
+ callback(success1 && success2 && success3);
+ });
+ });
+}
+
+var checkMacJDK = Zotero.Promise.coroutine(function* () {
+ var success = false;
+ try {
+ success = yield Zotero.Utilities.Internal.exec('/bin/bash/', ['-c', '/usr/libexec/java_home | grep -e "jdk"']);
+ } catch (e) {
+ Zotero.logError(e);
+ }
+ return success;
+});
+
+function checkJavaCommonPkg(pkgMain, pkgRequired, callback) {
+ // check for openoffice.org-writer with openoffice.org-java-common available but not installed
+ bashProc.runAsync(["-c", "dpkg -l '"+pkgMain.replace(".", "\\.")+"' | grep '^ii '"], 2, {"observe":function(subject1, topic1) {
+ if(topic1 === "process-finished" && !bashProc.exitValue) {
+ Zotero.debug("ZoteroOpenOfficeIntegration: "+pkgMain+" is installed");
+ // only care if openoffice.org-writer is installed; otherwise, we are probably not using
+ // default packages and probably have Java
+ bashProc.runAsync(
+ ["-c", "[ `apt-cache search '"+pkgRequired.replace(".", "\\.")+"' | wc -l` != 0 ]"], 2,
+ {"observe":function(subject2, topic2) {
+ // only care if openoffice.org-java-common is available for install; otherwise, we
+ // are probably using packages that include Java
+ if(topic2 === "process-finished" && !bashProc.exitValue) {
+ Zotero.debug("ZoteroOpenOfficeIntegration: "+pkgRequired+" is available");
+ bashProc.runAsync(["-c", "dpkg -l | grep '"+pkgRequired.replace(".", "\\.")+"'"], 2,
+ {"observe":function(subject3, topic3) {
+ wizard.canAdvance = true;
+ if(topic3 === "process-failed" || bashProc.exitValue) {
+ Zotero.debug("ZoteroOpenOfficeIntegration: "+pkgRequired+" is not installed");
+ neededPackages.push(pkgRequired);
+ callback(false);
+ } else {
+ Zotero.debug("ZoteroOpenOfficeIntegration: "+pkgRequired+" is installed");
+ callback(true);
+ }
+ }});
+ } else {
+ Zotero.debug("ZoteroOpenOfficeIntegration: "+pkgRequired+" is unavailable");
+ callback(true);
+ }
+ }});
+ } else {
+ Zotero.debug("ZoteroOpenOfficeIntegration: "+pkgMain+" is not installed");
+ callback(true);
+ }
+ }});
+}
+
+/**
+ * Check if JRE is required on Windows
+ */
+function checkJRE() {
+ var isInstalled = false,
+ wrk = Components.classes["@mozilla.org/windows-registry-key;1"]
+ .createInstance(Components.interfaces.nsIWindowsRegKey);
+
+ try {
+ wrk.open(Components.interfaces.nsIWindowsRegKey.ROOT_KEY_LOCAL_MACHINE,
+ "Software\\JavaSoft\\Java Runtime Environment",
+ Components.interfaces.nsIWindowsRegKey.ACCESS_READ | Components.interfaces.nsIWindowsRegKey.WOW64_32);
+ isInstalled = isInstalled || !!wrk.readStringValue("CurrentVersion");
+ } catch (e) {
+ Zotero.debug("32-bit java not found. Checking 64-bit");
+ } finally {
+ wrk.close();
+ }
+
+ if (!isInstalled) {
+ try {
+ wrk.open(Components.interfaces.nsIWindowsRegKey.ROOT_KEY_LOCAL_MACHINE,
+ "Software\\JavaSoft\\Java Runtime Environment",
+ Components.interfaces.nsIWindowsRegKey.ACCESS_READ | Components.interfaces.nsIWindowsRegKey.WOW64_64);
+ isInstalled = isInstalled || !!wrk.readStringValue("CurrentVersion");
+ } catch (e) {
+ Zotero.debug("64-bit java not found.");
+ }
+ finally {
+ wrk.close();
+ }
+ }
+
+ if (isInstalled) {
+ wizard.getPageById("intro").next = "openoffice-installations";
+
+ if(wizard.currentPage.pageid === "jre-required") {
+ wizard.canAdvance = true;
+ wizard.advance();
+ }
+ } else {
+ wizard.getPageById("intro").next = "jre-required";
+ }
+}
+
+/*** intro-page ***/
+
+/**
+ * Called when java-common wizardpage is shown
+ */
+function introPageShown() {
+ document.documentElement.canAdvance = true;
+}
+
+/*** java-common-page ***/
+
+/**
+ * Called when java-common wizardpage is shown
+ */
+function javaCommonPageShown() {
+ wizard.canAdvance = javaCommonCheckComplete;
+}
+
+/*** java-common-install-page ***/
+
+/**
+ * Called when java-common-install wizardpage is shown
+ */
+function javaCommonInstallPageShown() {
+ wizard.canAdvance = false;
+ wizard.canRewind = false;
+ document.getElementById("java-common-install-progress").hidden = false;
+ document.getElementById("java-common-install-error").hidden = true;
+
+ var proc = Components.classes["@mozilla.org/process/util;1"].
+ createInstance(Components.interfaces.nsIProcess);
+
+ // first try to install via apturl
+ var apturl = ZoteroOpenOfficeIntegration.getFile("/usr/bin/apturl");
+ if(apturl.exists()) {
+ proc.init(apturl);
+ proc.runAsync(["apt:"+neededPackages.join(",")], 1, {"observe":function(subject, topic) {
+ checkJavaCommon(javaCommonVerifyInstallationCallback);
+ wizard.canAdvance = true;
+ wizard.canRewind = true;
+ }});
+ } else {
+ // if no apturl, try to install via xterm
+ var xterm = ZoteroOpenOfficeIntegration.getFile("/usr/bin/xterm");
+ if(xterm.exists()) {
+ proc.init(xterm);
+ proc.runAsync(["-e", "sudo apt-get install "+neededPackages.join(" ")+"; sleep 2;"], 2,
+ {"observe":function(subject, topic) {
+ checkJavaCommon(javaCommonVerifyInstallationCallback);
+ wizard.canAdvance = true;
+ wizard.canRewind = true;
+ }});
+ } else {
+ document.getElementById("java-common-install-progress").hidden = true;
+ document.getElementById("java-common-install-error").hidden = false;
+ wizard.canAdvance = true;
+ wizard.canRewind = true;
+ }
+ }
+}
+
+function javaCommonVerifyInstallationCallback(success) {
+ if(success) {
+ // if install appears to have succeeded
+ wizard.getPageById("intro").next = "openoffice-installations";
+ wizard.advance();
+ } else {
+ // if install appears to have failed
+ document.getElementById("java-common-install-progress").hidden = true;
+ document.getElementById("java-common-install-error").hidden = false;
+ }
+}
+
+/*** jre-required page ***/
+
+/**
+ * Called when jre-required wizardpage is shown
+ */
+function jreRequiredPageShown() {
+ wizard.canAdvance = false;
+}
+
+/*** openoffice-installations-page ***/
+
+/**
+ * Called when openoffice-installations wizardpage is shown
+ */
+function openofficeInstallationsPageShown() {
+ wizard.canAdvance = false;
+
+ var installations = ZoteroOpenOfficeIntegration.getInstallations();
+
+ // add installations to listbox
+ var listbox = document.getElementById("installations-listbox");
+ while(listbox.hasChildNodes()) listbox.removeChild(listbox.firstChild);
+ for(var installation in installations) {
+ var itemNode = document.createElement("listitem");
+ itemNode.setAttribute("type", "checkbox");
+ itemNode.setAttribute("label", installation);
+ if(installations[installation] !== false) {
+ itemNode.setAttribute("checked", "true");
+ wizard.canAdvance = true;
+ }
+ listbox.appendChild(itemNode);
+ }
+}
+
+/**
+ * Called to add an LibreOffice installation directory
+ */
+function openofficeInstallationsAddDirectory() {
+ var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(Components.interfaces.nsIFilePicker);
+
+ // show dialog to select directory
+ if(Zotero.isMac) {
+ fp.init(window, "Select the LibreOffice application", Components.interfaces.nsIFilePicker.modeOpen);
+ fp.appendFilter("Mac OS X Application Bundle", "*.app");
+ } else {
+ fp.init(window, "Select the LibreOffice installation directory", Components.interfaces.nsIFilePicker.modeGetFolder);
+ }
+
+ if(fp.show() === Components.interfaces.nsIFilePicker.returnOK) {
+ // find unopkg executable
+ var unopkg = fp.file.clone();
+ unopkg = unopkg.QueryInterface(Components.interfaces.nsILocalFile);
+ unopkg.appendRelativePath(UNOPKG_RELPATHS[ZoteroOpenOfficeIntegration.platform]);
+
+ if(!unopkg.exists()) {
+ unopkg = fp.file.clone().parent;
+ unopkg = unopkg.QueryInterface(Components.interfaces.nsILocalFile);
+ unopkg.appendRelativePath(UNOPKG_RELPATHS[ZoteroOpenOfficeIntegration.platform]);
+ }
+
+ if(!unopkg.exists()) {
+ var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
+ .getService(Components.interfaces.nsIPromptService);
+ promptService.alert(window, "unopkg Not Found", "The unopkg executable could not be "+
+ "found in the selected LibreOffice installation directory. Please ensure that "+
+ "you have selected the correct directory and try again.");
+ }
+
+ // ensure unopkg is not already in list
+ var listbox = document.getElementById("installations-listbox");
+ var nodes = listbox.childNodes;
+ for(var i=0; i<nodes.length; i++) {
+ if(nodes[i].label === unopkg.path) return;
+ }
+
+ // add unopkg to list
+ var itemNode = document.createElement("listitem");
+ itemNode.setAttribute("type", "checkbox");
+ itemNode.setAttribute("label", unopkg.path);
+ itemNode.setAttribute("checked", "true");
+ listbox.appendChild(itemNode);
+
+ wizard.canAdvance = true;
+ }
+}
+
+/**
+ * Called to reveal LibreOffice extension for manual installation
+ */
+function openofficeInstallationsManualInstallation() {
+ // clear saved unopkg paths so we force manual install on upgrade
+ ZoteroPluginInstaller.prefBranch.setCharPref(
+ ZoteroOpenOfficeIntegration.UNOPKG_PATHS_PREF, "{}");
+
+ // get oxt path and set it in the dialog
+ var oxtPath = ZoteroOpenOfficeIntegration.getOxtPath();
+ document.getElementById("installation-manual-path").textContent = oxtPath.path;
+ try {
+ oxtPath.QueryInterface(Components.interfaces.nsILocalFile).reveal();
+ } catch(e) {
+ Zotero.logError(e);
+ }
+
+ // we were successful and installation was complete
+ ZoteroPluginInstaller.success();
+ showInstallationComplete("manual");
+}
+
+/**
+ * Called when an LibreOffice installation is checked or unchecked
+ */
+function openofficeInstallationsListboxSelectionChanged() {
+ var listbox = document.getElementById("installations-listbox");
+ for (let node of listbox.childNodes) {
+ if(node.checked) {
+ wizard.canAdvance = true;
+ return;
+ }
+ }
+ wizard.canAdvance = false;
+}
+
+/**
+ * Called to specify what should be shown on installation-complete-page
+ * @param {String} vboxToShow Which vbox should be visible
+ */
+function showInstallationComplete(vboxToShow) {
+ // show correct description
+ for (let vbox of ["manual", "error", "successful"]) {
+ var vboxElem = document.getElementById("installation-"+vbox);
+ vboxElem.hidden = vbox != vboxToShow;
+ }
+
+ // show correct label
+ const msgs = {
+ "error":"Installation Failed",
+ "manual":"Manual Installation",
+ "successful":"Installation Successful"
+ };
+ wizard.getPageById("installation-complete").setAttribute("label", msgs[vboxToShow]);
+
+ // go to installation complete page
+ wizard.goTo("installation-complete");
+ wizard.canAdvance = true;
+ wizard.canRewind = true;
+}
+
+/*** installing-page ***/
+
+/**
+ * Called when installing-page wizardpage is shown
+ */
+function installingPageShown() {
+ wizard.canAdvance = false;
+ wizard.canRewind = false;
+
+ var listbox = document.getElementById("installations-listbox");
+ var paths = {};
+ for (let node of listbox.childNodes) {
+ paths[node.label] = !!node.checked;
+ }
+ ZoteroOpenOfficeIntegration.installComponents(paths,
+ function(success) {
+ showInstallationComplete(success ? "successful" : "error");
+ ZoteroPluginInstaller[success ? "success" : "error"]();
+ });
+}
+
+/*** installation-complete-page ***/
+
+function reportErrors() {
+ var errors = Zotero.getErrors(true);
+ var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
+ .getService(Components.interfaces.nsIWindowWatcher);
+ var data = {
+ msg: Zotero.getString('errorReport.followingErrors', Zotero.appName),
+ e: errors.join('\n\n'),
+ askForSteps: true
+ };
+ var io = { wrappedJSObject: { Zotero: Zotero, data: data } };
+ var win = ww.openWindow(null, "chrome://zotero/content/errorReport.xul",
+ "zotero-error-report", "chrome,centerscreen,modal", io);
+}
+
+/*** WIZARD BUTTON HANDLERS ***/
+
+function wizardCancelled() {
+ if(wizard.currentPage.pageid != "installation-complete") {
+ var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
+ .getService(Components.interfaces.nsIPromptService);
+ var cancel = promptService.confirm(window, "Zotero LibreOffice Integration", "Are you sure you want "+
+ "to cancel Zotero LibreOffice Integration installation? To "+
+ "install later, visit the Cite pane of the Zotero preferences.");
+ if(cancel) {
+ ZoteroPluginInstaller.cancelled();
+ return true;
+ }
+ return false;
+ }
+}
+
+function wizardBack() {
+ var pageid = wizard.currentPage.pageid;
+
+ if(pageid === "java-common" || pageid === "jre-required") {
+ wizard.goTo("intro");
+ } else if(pageid === "java-common-install") {
+ wizard.goTo("java-common");
+ } else if(pageid === "openoffice-installations") {
+ wizard.goTo(wizard.getPageById("intro").next === "openoffice-installations" ? "intro" : wizard.getPageById("intro").next);
+ } else if(pageid === "installing" || pageid === "installation-complete") {
+ wizard.goTo("openoffice-installations");
+ } else {
+ throw "Don't know how to go back from "+pageid;
+ }
+}
+
+function activated() {
+ var pageid = wizard.currentPage.pageid;
+
+ if(pageid === "jre-required") {
+ checkJRE();
+ }
+}
+
+/*** EVENT LISTENERS ***/
+
+window.addEventListener("load", onLoad, false);
+window.addEventListener("activate", activated, false); \ No newline at end of file
diff --git a/chrome/install.xul b/chrome/install.xul
new file mode 100644
index 0000000..2bfc9c0
--- /dev/null
+++ b/chrome/install.xul
@@ -0,0 +1,147 @@
+<?xml version="1.0" ?>
+<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
+<?xml-stylesheet href="chrome://zotero/skin/zotero.css" type="text/css"?>
+<?xml-stylesheet href="chrome://zotero/skin/upgrade.css" type="text/css"?>
+<!DOCTYPE window SYSTEM "chrome://zotero/locale/zotero.dtd">
+
+<wizard xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
+ title="Zotero LibreOffice Plugin Installation" width="600"
+ height="450" id="installer" onwizardcancel="return wizardCancelled();"
+ onwizardback="wizardBack(); return false;">
+
+ <script src="chrome://zotero/content/include.js"/>
+ <script src="install.js"/>
+
+ <wizardpage pageid="intro" label="Introduction" onpageshow="introPageShown()"
+ next="openoffice-installations">
+ <description>
+ The Zotero LibreOffice Plugin makes it easy to insert Zotero
+ citations and bibliographies into LibreOffice documents.
+ </description>
+ <description>
+ This wizard will install the plugin into LibreOffice. It can be reinstalled later from the
+ Cite pane of the Zotero preferences.
+ </description>
+ </wizardpage>
+
+ <wizardpage pageid="java-common" onpageshow="javaCommonPageShown()"
+ label="Install Required Components" next="java-common-install">
+ <vbox id="java-common-progress" flex="1">
+ <label>Searching for Required Components…</label>
+ <progressmeter id="progress-indicator" mode="undetermined"/>
+ </vbox>
+ <vbox id="java-common-required" hidden="true" flex="1">
+ <description>
+ The Zotero LibreOffice Plugin requires the following packages:
+ </description>
+ <description id="java-common-packages" style="margin-left:0.5in"></description>
+ <description>
+ Press the “Next” button below to proceed with the installation.
+ </description>
+ </vbox>
+ </wizardpage>
+
+ <wizardpage pageid="java-common-install"
+ label="Install Required Components" onpageshow="javaCommonInstallPageShown()"
+ next="openoffice-installations">
+ <vbox id="java-common-install-progress" flex="1">
+ <label>Installing required packages…</label>
+ <progressmeter id="progress-indicator" mode="undetermined"/>
+ </vbox>
+ <description id="java-common-install-error" flex="1" hidden="true">
+ An error occurred installing required packages. While you can attempt to
+ install the Zotero LibreOffice Plugin anyway, it is unlikely to work.
+ Click Cancel to abort the installation process.
+ </description>
+ </wizardpage>
+
+ <wizardpage pageid="jre-required" onpageshow="jreRequiredPageShown()"
+ label="Install Required Components"
+ next="openoffice-installations">
+ <description>
+ The Zotero LibreOffice Plugin requires the Java
+ Runtime Environment. Visit <label class="zotero-text-link" href="https://java.com/inc/BrowserRedirect1.jsp">Java.com</label>
+ to download it.
+ </description>
+ </wizardpage>
+
+ <wizardpage pageid="jdk-required" onpageshow="jreRequiredPageShown()"
+ label="Install Required Components"
+ next="openoffice-installations">
+ <description>
+ The Zotero LibreOffice Plugin on macOS requires the Java
+ Development Kit. See the <label class="zotero-text-link" href="https://www.zotero.org/support/word_processor_plugin_troubleshooting#libreoffice_5_on_macos_1011no_response_from_plugin">Zotero documentation</label>
+ for more information.
+ </description>
+ </wizardpage>
+
+ <wizardpage pageid="openoffice-installations" extra1="Add Directory…"
+ extra2="Manual Installation" label="Select LibreOffice unopkg executable"
+ next="installing" onpageshow="openofficeInstallationsPageShown()">
+ <description>
+ Select LibreOffice installations from the list
+ below, or click “Add Installation” to locate the path to an LibreOffice installation
+ directory not shown in the list.
+ </description>
+ <description>
+ To open the directory containing the LibreOffice extension file for manual installation
+ from within LibreOffice, click “Manual Installation”.
+ </description>
+ <listbox height="150" id="installations-listbox" oncommand="openofficeInstallationsListboxSelectionChanged()"/>
+ <hbox pack="end">
+ <button label="Manual Installation" oncommand="openofficeInstallationsManualInstallation()"/>
+ <button label="Add Directory…" oncommand="openofficeInstallationsAddDirectory()"/>
+ </hbox>
+ </wizardpage>
+
+ <wizardpage pageid="installing" label="Installing…"
+ onpageshow="installingPageShown()" next="installation-complete">
+ <vbox id="installation-progress" flex="1">
+ <label>Installing the Zotero LibreOffice Plugin…</label>
+ <progressmeter id="progress-indicator" mode="undetermined"/>
+ </vbox>
+ </wizardpage>
+
+ <wizardpage pageid="installation-complete"
+ label="Installation Complete">
+ <description id="installation-successful">
+ The Zotero LibreOffice Plugin was installed successfully.
+ Depending on how LibreOffice is configured, it may be
+ necessary to restart your computer for changes to take effect.
+ </description>
+ <vbox id="installation-manual" hidden="true" flex="1">
+ <description>
+ You have elected to install the Zotero LibreOffice
+ Plugin manually. The directory containing the extension should now
+ be open. In case it isn’t, the full path to the extension is:
+ </description>
+ <description id="installation-manual-path"/>
+ <description>
+ You can install the extension by double-clicking it, or by opening LibreOffice,
+ selecting Tools → Extension Manager, clicking the Add button, and locating the file.
+ </description>
+ </vbox>
+ <vbox id="installation-error" hidden="true" flex="1">
+ <description>
+ An error occurred during the installation of the Zotero LibreOffice Plugin.
+ </description>
+ <description>
+ Click the “Previous” button and verify that the application path is correct. If you
+ continue to experience errors, click the “Manual Installation” button below to
+ manually install the component. The following screen will provide instructions on
+ how to proceed.
+ </description>
+ <description>
+ If this error persists, please review the
+ <label class="zotero-text-link" href="http://zotero.org/support/word_processor_plugin_installation_for_zotero_2.1#openoffice">troubleshooting instructions</label>.
+ If these do not resolve the issue you’re experiencing, click the button below to
+ submit an error report, and post the Report ID as well as the text of any errors you
+ experienced during manual installation to the <label class="text-link" href="https://forums.zotero.org/">Zotero Forums</label>.
+ </description>
+ <hbox pack="center">
+ <button label="Manual Installation" onclick="openofficeInstallationsManualInstallation()"/>
+ <button label="Submit Error Report…" onclick="reportErrors()"/>
+ </hbox>
+ </vbox>
+ </wizardpage>
+</wizard>
diff --git a/chrome/overlay.xul b/chrome/overlay.xul
new file mode 100644
index 0000000..c420ae5
--- /dev/null
+++ b/chrome/overlay.xul
@@ -0,0 +1,16 @@
+<?xml version="1.0"?>
+<overlay xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
+ <script type="application/x-javascript">
+ window.addEventListener("load", function() {
+ // initialize server
+ Components.classes["@zotero.org/Zotero/integration/initializer?agent=OpenOffice;1"].
+ getService(Components.interfaces.nsISupports);
+
+ // start plug-in installer
+ window.setTimeout(function() {
+ var Installer = Components.utils.import("resource://zotero-openoffice-integration/installer.jsm").Installer;
+ new Installer();
+ }, 1000);
+ }, false);
+ </script>
+</overlay>
diff --git a/chrome/preferences.xul b/chrome/preferences.xul
new file mode 100644
index 0000000..f689ef7
--- /dev/null
+++ b/chrome/preferences.xul
@@ -0,0 +1,27 @@
+<?xml version="1.0"?>
+<overlay id="openOfficeIntegration"
+ xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
+ <script>
+ <![CDATA[
+ (function() {
+ function showPane() {
+ try {
+ var installer = Components.utils.import("resource://zotero-openoffice-integration/installer.jsm").Installer;
+ (new installer(true)).showPreferences(document);
+ } catch(e) {
+ Zotero.logError(e);
+ }
+ }
+
+ document.addEventListener("DOMContentLoaded", function() {
+ var citePane = document.getElementById("zotero-prefpane-cite");
+ if(citePane.hasAttribute("src")) {
+ citePane.addEventListener("paneload", showPane, false);
+ } else {
+ showPane();
+ }
+ }, false);
+ })();
+ ]]>
+ </script>
+</overlay> \ No newline at end of file
diff --git a/chrome/progress.xul b/chrome/progress.xul
new file mode 100644
index 0000000..b4033d6
--- /dev/null
+++ b/chrome/progress.xul
@@ -0,0 +1,14 @@
+<?xml version="1.0" ?>
+<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
+<!DOCTYPE window SYSTEM "chrome://zotero/locale/zotero.dtd">
+
+<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
+ title="&zotero.progress.title;" width="300" height="30"
+ id="zotero-progress">
+ <vbox style="padding:10px">
+ <hbox align="stretch">
+ <label id="progress-label" flex="1"/>
+ </hbox>
+ <progressmeter id="progress-indicator" mode="undetermined" />
+ </vbox>
+</window>
diff --git a/components/zoteroOpenOfficeIntegration.js b/components/zoteroOpenOfficeIntegration.js
new file mode 100644
index 0000000..a444fa5
--- /dev/null
+++ b/components/zoteroOpenOfficeIntegration.js
@@ -0,0 +1,511 @@
+/*
+ ***** BEGIN LICENSE BLOCK *****
+
+ Copyright (c) 2017 Zotero
+ Center for History and New Media
+ George Mason University, Fairfax, Virginia, USA
+ http://zotero.org
+
+ Zotero is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Zotero is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with Zotero. If not, see <http://www.gnu.org/licenses/>.
+
+ ***** END LICENSE BLOCK *****
+*/
+
+"use strict";
+
+Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
+
+var Zotero;
+const API_VERSION = 3;
+const SERVER_PORT = 23116;
+
+var Comm = new function() {
+ var _observersRegistered = false, _converter, _lastDataListener,
+ mainThread;
+
+ /**
+ * Observes browser startup to initialize ZoteroOpenOfficeIntegration HTTP server
+ */
+ this.init = function() {
+ Zotero = Components.classes["@zotero.org/Zotero;1"]
+ .getService(Components.interfaces.nsISupports)
+ .wrappedJSObject;
+ mainThread = Zotero.mainThread;
+
+ if (Zotero.isConnector || Zotero.HTTP.browserIsOffline()) {
+ Zotero.debug('ZoteroOpenOfficeIntegration: Browser is offline or in connector mode -- not initializing communication server');
+ _registerObservers();
+ return;
+ }
+
+ // Initialize the converter
+ _converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"]
+ .createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
+ _converter.charset = "UTF-8";
+
+ // Start listening on socket
+ var serv = Components.classes["@mozilla.org/network/server-socket;1"]
+ .createInstance(Components.interfaces.nsIServerSocket),
+ servCompat = Components.classes["@mozilla.org/network/server-socket;1"]
+ .createInstance(Components.interfaces.nsIServerSocket);
+ try {
+ // Start main socket listener
+ serv.init(SERVER_PORT, true, -1);
+ serv.asyncListen({
+ "onSocketAccepted":function(socket, transport) {
+ Zotero.debug("ZoteroOpenOfficeIntegration: Connection received");
+
+ // Close old data listener
+ if(_lastDataListener) {
+ try {
+ _lastDataListener.onStopRequest();
+ } catch(e) {}
+ }
+
+ new DataListener(transport);
+ },
+ "onStopListening":function() {
+ Zotero.debug("ZoteroOpenOfficeIntegration: Communication server going offline");
+ }
+ });
+ Zotero.debug("ZoteroOpenOfficeIntegration: Communication server listening on 127.0.0.1:"+serv.port);
+
+ // Start listener for socket to let user know their LO extension is out of date
+ servCompat.init(19876, true, -1);
+ servCompat.asyncListen({
+ "onSocketAccepted":function(socket, transport) {
+ Comm.incompatibleVersion();
+ transport.close();
+ },
+ "onStopListening":function() {}
+ });
+ } catch(e) {
+ Zotero.logError(e);
+ Zotero.debug("ZoteroOpenOfficeIntegration: Not initializing communication server");
+ }
+
+ if(Zotero.addShutdownListener) {
+ Zotero.debug("ZoteroOpenOfficeIntegration: Registering shutdown listener");
+ Zotero.addShutdownListener(function() {
+ Zotero.debug("ZoteroOpenOfficeIntegration: Shutting down communication server");
+
+ // Close sockets
+ if(serv) serv.close();
+ if(servCompat) serv.close();
+ // Close data listener
+ if(_lastDataListener) {
+ try {
+ _lastDataListener.onStopRequest();
+ } catch(e) {}
+ }
+ });
+ }
+
+ _registerObservers();
+ }
+
+ /**
+ * Registers an observer to bring the server back online when Firefox comes online
+ */
+ function _registerObservers() {
+ if (_observersRegistered) return;
+
+ // Observer to enable integration when we go online
+ var onlineObserver = function(subject, topic, data) {
+ if (data == 'online' && !Zotero.isConnector) Comm.init();
+ };
+
+ // Observer to enable integration when we leave connector mode
+ var reloadObserver = function(subject, topic, data) {
+ if(!Zotero.isConnector) Comm.init();
+ }
+
+ var observerService =
+ Components.classes["@mozilla.org/observer-service;1"]
+ .getService(Components.interfaces.nsIObserverService);
+ observerService.addObserver(onlineObserver, "network:offline-status-changed", false);
+ observerService.addObserver(reloadObserver, "zotero-reloaded", false);
+
+ _observersRegistered = true;
+ }
+
+ /**
+ * Handles the actual acquisition of data
+ */
+ var DataListener = function(transport) {
+ this.iStream = transport.openInputStream(0, 0, 0);
+ this.oStream = transport.openOutputStream(Components.interfaces.nsITransport.OPEN_BLOCKING, 0, 0);
+
+ this.bStream = Components.classes["@mozilla.org/binaryinputstream;1"].
+ createInstance(Components.interfaces.nsIBinaryInputStream);
+ this.bStream.setInputStream(this.iStream);
+
+ this.boStream = Components.classes["@mozilla.org/binaryoutputstream;1"].
+ createInstance(Components.interfaces.nsIBinaryOutputStream);
+ this.boStream.setOutputStream(this.oStream);
+
+ this.pump = Components.classes["@mozilla.org/network/input-stream-pump;1"]
+ .createInstance(Components.interfaces.nsIInputStreamPump);
+ this.pump.init(this.iStream, -1, -1, 0, 0, false);
+ this.pump.asyncRead(this, null);
+ }
+
+ DataListener.prototype = {
+ "_transactionCallbacks":{
+ 0:[
+ function(payload) {
+ Zotero.Integration.execCommand("OpenOffice", payload, null)
+ },
+ function(errString) {
+ Zotero.logError(e);
+ }
+ ]
+ },
+ "_nextTransactionID":1,
+ "_frameHeader":"",
+ "_frameTransactionID":null,
+ "_frameRemaining":null,
+ "_frameContent":"",
+
+ /**
+ * Called when a request begins (although the request should have begun before
+ * the DataListener was generated)
+ */
+ "onStartRequest":function(request, context) {
+ },
+
+ /**
+ * Called when a request stops
+ */
+ "onStopRequest":function(request, context, status) {
+ this.iStream.close();
+ this.oStream.close();
+ },
+
+ /**
+ * Called when new data is available
+ */
+ "onDataAvailable":function(request, context, inputStream, offset, count) {
+ Zotero.debug("ZoteroOpenOfficeIntegration: "+count+" bytes available");
+
+ // Keep track of the last connection we read on
+ _lastDataListener = this;
+
+ while(count) {
+ if(this._frameRemaining !== null) {
+ if(count >= this._frameRemaining) {
+ this._frameContent += this.bStream.readBytes(this._frameRemaining);
+ count -= this._frameRemaining;
+ this._frameRemaining = 0;
+ this._processFrame();
+ } else {
+ this._frameContent += this.bStream.readBytes(count);
+ this._frameRemaining -= count;
+ return;
+ }
+ } else {
+ var readBytes = Math.min(8-this._frameHeader.length, count);
+ this._frameHeader += this.bStream.readBytes(readBytes);
+ if(this._frameHeader.length !== 8) return;
+ this._frameTransactionID = this._readUint32(this._frameHeader, 0);
+ this._frameRemaining = this._readUint32(this._frameHeader, 4);
+ count -= readBytes;
+ }
+ }
+ },
+
+ /**
+ * Converts 4 characters of a string to a uint32 (big endian)
+ */
+ "_readUint32":function(string, offset) {
+ return (string.charCodeAt(offset) << 24)
+ + (string.charCodeAt(offset+1) << 16)
+ + (string.charCodeAt(offset+2) << 8)
+ + string.charCodeAt(offset+3);
+ },
+
+ /**
+ * Processes a completed frame
+ */
+ "_processFrame":function() {
+ this._frameHeader = "";
+ this._frameRemaining = null;
+ var input = _converter.ConvertToUnicode(this._frameContent);
+ this._frameContent = "";
+
+ Zotero.debug("ZoteroOpenOfficeIntegration: Read "+this._frameTransactionID+" "+input);
+
+ var callbacks;
+ if((callbacks = this._transactionCallbacks[this._frameTransactionID])) {
+ // Remove callback from list
+ if(this._frameTransactionID !== 0) {
+ delete this._transactionCallbacks[this._frameTransactionID];
+ }
+
+ // Parse JSON
+ var err, payload;
+ if(input.substr(0, 4) == "ERR:") {
+ err = input.substr(4);
+ } else {
+ try {
+ payload = JSON.parse(input);
+ } catch(e) {
+ err = e;
+ }
+ }
+
+ // Transmit to callback
+ Zotero.setTimeout(function() {
+ if(err) {
+ callbacks[1](err);
+ } else {
+ callbacks[0](payload);
+ }
+ }, 0);
+ }
+ },
+
+ /**
+ * Get a transaction ID and register a callback for it
+ */
+ "beginTransaction":function(successCallback, errorCallback) {
+ var transactionID = this._nextTransactionID++;
+ // Don't exceed MAX_INT
+ if(this._nextTransactionID === 2147483647) {
+ this._nextTransactionID = 1;
+ }
+ this._transactionCallbacks[transactionID] = [successCallback, errorCallback];
+ return transactionID;
+ },
+ }
+
+ /**
+ * Sends a command. This differs from _writeCommand in that it serializes its
+ * arguments and queues them if necessary.
+ */
+ this.sendCommand = function(cmd, args) {
+ var receivedData, error;
+ this.sendCommandAsync(cmd, args,
+ function(response) {
+ receivedData = response;
+ },
+ function(err) {
+ receivedData = true;
+ error = err;
+ }
+ );
+
+ while(receivedData === undefined) {
+ mainThread.processNextEvent(true);
+ }
+ if(error) throw error;
+
+ return receivedData;
+ }
+
+ /**
+ * Writes to the communication channel, waiting asynchronously for a response.
+ */
+ this.sendCommandAsync = function(cmd, args, successCallback, errorCallback) {
+ var payload = JSON.stringify([cmd, args]);
+ payload = _converter.ConvertFromUnicode(payload);
+
+ var receivedData;
+ var transactionID = _lastDataListener.beginTransaction(successCallback, errorCallback);
+
+ // Write to stream
+ Zotero.debug("ZoteroOpenOfficeIntegration: Sending "+transactionID+" "+payload);
+ _lastDataListener.boStream.write32(transactionID);
+ _lastDataListener.boStream.write32(payload.length);
+ _lastDataListener.boStream.writeBytes(payload, payload.length);
+ _lastDataListener.boStream.flush();
+ }
+
+ /**
+ * Displays a message warning the user that the LibreOffice extension is incompatible.
+ */
+ this.incompatibleVersion = function() {
+ var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
+ .getService(Components.interfaces.nsIPromptService);
+ var shouldReinstall = ps.confirm(null, "Zotero LibreOffice Integration Error",
+ 'The version of the Zotero LibreOffice Integration component installed within '+
+ 'LibreOffice does not appear to match '+
+ 'this Zotero Standalone version. '+
+ 'Would you like to attempt to reinstall it?\n\n'+
+ 'Please ensure your LibreOffice installation is properly detected. If you '+
+ 'continue to experience this error, click the "Manual Installation" button '+
+ 'within the wizard to show the directory containing the LibreOffice component. '+
+ 'Double-click this component or add it from within LibreOffice '+
+ 'to complete the installation procedure.');
+
+ if(shouldReinstall) {
+ var ZoteroOpenOfficeInstaller = Components.utils.import("resource://zotero-openoffice-integration/installer.jsm").Installer;
+ var zpi = new ZoteroOpenOfficeInstaller(false, true);
+ }
+
+ // We throw this error to avoid displaying another error dialog
+ Zotero.logError("Zotero and LibreOffice extension versions are incompatible");
+ throw Components.Exception("ExceptionAlreadyDisplayed");
+ }
+};
+
+/**
+ * A service to initialize the integration server on startup
+ */
+var Initializer = function() {
+ Comm.init();
+};
+Initializer.prototype = {
+ classDescription: "Zotero LibreOffice Integration Initializer",
+ "classID":Components.ID("{f43193a1-7060-41a3-8e82-481d58b71e6f}"),
+ "contractID":"@zotero.org/Zotero/integration/initializer?agent=OpenOffice;1",
+ "QueryInterface":XPCOMUtils.generateQI([Components.interfaces.nsISupports]),
+ "service":true
+};
+
+/**
+ * See integrationTests.js
+ */
+var Application = function() {
+ this.wrappedJSObject = this;
+};
+Application.prototype = {
+ classDescription: "Zotero LibreOffice Integration Application",
+ classID: Components.ID("{8478cd98-5ba0-4848-925a-75adffff2dbf}"),
+ contractID: "@zotero.org/Zotero/integration/application?agent=OpenOffice;1",
+ QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsISupports]),
+ _xpcom_categories: [{
+ category: "profile-after-change",
+ service: true
+ }],
+ "service": true,
+ "getActiveDocument":function() {
+ var retVal = Comm.sendCommand("Application_getActiveDocument", [API_VERSION]);
+ if(typeof retVal !== "object" || retVal[0] !== API_VERSION) Comm.incompatibleVersion();
+ return new Document(retVal[1]);
+ },
+ "primaryFieldType":"ReferenceMark",
+ "secondaryFieldType":"Bookmark"
+};
+
+/**
+ * See integrationTests.js
+ */
+var Document = function(documentID) {
+ this._documentID = documentID;
+};
+Document.prototype = {};
+for (let method of ["displayAlert", "activate", "canInsertField", "getDocumentData",
+ "setDocumentData", "setBibliographyStyle", "complete"]) {
+ let methodStable = method;
+ Document.prototype[method] = function() {
+ return Comm.sendCommand("Document_"+methodStable,
+ [this._documentID].concat(Array.prototype.slice.call(arguments)));
+ };
+}
+Document.prototype.cleanup = function() {};
+Document.prototype.cursorInField = function(fieldType) {
+ var retVal = Comm.sendCommand("Document_cursorInField", [this._documentID, fieldType]);
+ if(retVal === null) return null;
+ return new Field(this._documentID, retVal[0], retVal[1], retVal[2]);
+};
+Document.prototype.insertField = function(fieldType, noteType) {
+ var retVal = Comm.sendCommand("Document_insertField", [this._documentID, fieldType, parseInt(noteType) || 0]);
+ return new Field(this._documentID, retVal[0], retVal[1], retVal[2]);
+};
+Document.prototype.getFields = function(fieldType) {
+ var retVal = Comm.sendCommand("Document_getFields", [this._documentID, fieldType]);
+ return new FieldEnumerator(this._documentID, retVal[0], retVal[1], retVal[2]);
+};
+Document.prototype.getFieldsAsync = function(fieldType, observer) {
+ var documentID = this._documentID;
+ Comm.sendCommandAsync("Document_getFields", [this._documentID, fieldType],
+ function(retVal) {
+ observer.observe(new FieldEnumerator(documentID, retVal[0], retVal[1], retVal[2]), "fields-available", null);
+ },
+ function(err) {
+ observer.observe(err, "fields-error", null);
+ }
+ );
+};
+Document.prototype.convert = function(enumerator, fieldType, noteTypes) {
+ var i = 0;
+ while(enumerator.hasMoreElements()) {
+ Comm.sendCommand("Field_convert", [this._documentID, enumerator.getNext()._index, fieldType, noteTypes[i]]);
+ i++;
+ }
+};
+
+/**
+ * An enumerator implementation to handle passing off fields
+ */
+var FieldEnumerator = function(documentID, fieldIndices, fieldCodes, noteIndices) {
+ this._documentID = documentID;
+ this._fieldIndices = fieldIndices;
+ this._fieldCodes = fieldCodes;
+ this._noteIndices = noteIndices;
+ this._i = 0;
+};
+FieldEnumerator.prototype = {
+ "hasMoreElements":function() {
+ return this._i < this._fieldIndices.length;
+ },
+ "getNext":function() {
+ if(this._i >= this._fieldIndices.length) throw "No more fields!";
+ var field = new Field(this._documentID, this._fieldIndices[this._i], this._fieldCodes[this._i], this._noteIndices[this._i]);
+ this._i++;
+ return field;
+ },
+ QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsISupports, Components.interfaces.nsISimpleEnumerator])
+};
+
+/**
+ * See integrationTests.js
+ */
+var Field = function(documentID, index, code, noteIndex) {
+ this._documentID = documentID;
+ this._index = index;
+ this._code = code;
+ this._noteIndex = noteIndex;
+};
+Field.prototype = {};
+
+for (let method of ["delete", "select", "removeCode", "setText", "getText"]) {
+ let methodStable = method;
+ Field.prototype[method] = function() {
+ return Comm.sendCommand("Field_"+methodStable,
+ [this._documentID, this._index].concat(Array.prototype.slice.call(arguments)));
+ };
+}
+Field.prototype.getCode = function() {
+ return this._code;
+}
+Field.prototype.setCode = function(code) {
+ this._code = code;
+ Comm.sendCommand("Field_setCode", [this._documentID, this._index, code]);
+}
+Field.prototype.getNoteIndex = function() {
+ return this._noteIndex;
+}
+Field.prototype.equals = function(arg) {
+ return this._index === arg._index;
+}
+
+var classes = [
+ Initializer,
+ Application,
+];
+
+var NSGetFactory = XPCOMUtils.generateNSGetFactory(classes);
+
diff --git a/defaults/preferences/zoteroOpenOfficeIntegration.js b/defaults/preferences/zoteroOpenOfficeIntegration.js
new file mode 100644
index 0000000..6cb9992
--- /dev/null
+++ b/defaults/preferences/zoteroOpenOfficeIntegration.js
@@ -0,0 +1,4 @@
+pref("extensions.zoteroOpenOfficeIntegration.unopkgPaths", "{}");
+pref("extensions.zoteroOpenOfficeIntegration.version", "");
+pref("extensions.zoteroOpenOfficeIntegration.installed", false);
+pref("extensions.zoteroOpenOfficeIntegration.skipInstallation", false); \ No newline at end of file
diff --git a/install.rdf b/install.rdf
new file mode 100644
index 0000000..3a14b63
--- /dev/null
+++ b/install.rdf
@@ -0,0 +1,33 @@
+<?xml version="1.0"?>
+<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ xmlns:em="http://www.mozilla.org/2004/em-rdf#">
+<Description about="urn:mozilla:install-manifest">
+ <em:id>zoteroOpenOfficeIntegration@zotero.org</em:id>
+ <em:name>Zotero LibreOffice Integration</em:name>
+ <em:version>5.0.6.SOURCE</em:version>
+ <em:creator>Center for History and New Media<br/>George Mason University</em:creator>
+ <em:developer>Simon Kornblith</em:developer>
+ <em:homepageURL>https://www.zotero.org</em:homepageURL>
+ <em:updateURL>https://www.zotero.org/download/update-source.rdf</em:updateURL>
+ <em:iconURL>chrome://zotero/skin/zotero_z_32px.png</em:iconURL>
+ <em:optionsURL>chrome://zotero/content/preferences/preferences.xul#cite</em:optionsURL>
+ <em:description>Integrates Zotero with LibreOffice and OpenOffice.org 3.0 or later</em:description>
+ <em:type>2</em:type> <!-- type=extension -->
+ <em:unpack>true</em:unpack>
+
+ <em:targetApplication>
+ <Description>
+ <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id>
+ <em:minVersion>4.0</em:minVersion>
+ <em:maxVersion>53.*</em:maxVersion>
+ </Description>
+ </em:targetApplication>
+ <em:targetApplication>
+ <Description>
+ <em:id>zotero@chnm.gmu.edu</em:id>
+ <em:minVersion>4.0</em:minVersion>
+ <em:maxVersion>5.0.*</em:maxVersion>
+ </Description>
+ </em:targetApplication>
+</Description>
+</RDF>
diff --git a/resource/installer.jsm b/resource/installer.jsm
new file mode 100644
index 0000000..d0b78ec
--- /dev/null
+++ b/resource/installer.jsm
@@ -0,0 +1,399 @@
+/*
+ ***** BEGIN LICENSE BLOCK *****
+
+ Copyright (c) 2017 Zotero
+ Center for History and New Media
+ George Mason University, Fairfax, Virginia, USA
+ http://zotero.org
+
+ Zotero is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Zotero is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with Zotero. If not, see <http://www.gnu.org/licenses/>.
+
+ ***** END LICENSE BLOCK *****
+*/
+
+var EXPORTED_SYMBOLS = ["Installer"];
+var Zotero = Components.classes["@zotero.org/Zotero;1"].getService(Components.interfaces.nsISupports).wrappedJSObject;
+var ZoteroPluginInstaller = Components.utils.import("resource://zotero/word-processor-plugin-installer.js").ZoteroPluginInstaller;
+var Installer = function(failSilently=true, force) {
+ return new ZoteroPluginInstaller(Plugin, failSilently, force);
+}
+
+const UNOPKG_LOCATIONS = {
+ Mac:[
+ "/Applications/LibreOffice.app/Contents/MacOS/unopkg",
+ "/Applications/OpenOffice.org.app/Contents/MacOS/unopkg",
+ "/Applications/OpenOffice.app/Contents/MacOS/unopkg",
+ "/Applications/NeoOffice.app/Contents/MacOS/unopkg",
+ "/Applications/OpenOffice.org 2.4.app/Contents/MacOS/unopkg"
+ ],
+ Win:[
+ "C:\\Program Files\\LibreOffice 5\\program\\unopkg.exe",
+ "C:\\Program Files (x86)\\LibreOffice 5\\program\\unopkg.exe",
+ "C:\\Program Files\\LibreOffice 4\\program\\unopkg.exe",
+ "C:\\Program Files (x86)\\LibreOffice 4\\program\\unopkg.exe",
+ "C:\\Program Files\\LibreOffice 4.0\\program\\unopkg.exe",
+ "C:\\Program Files (x86)\\LibreOffice 4.0\\program\\unopkg.exe",
+ "C:\\Program Files\\LibreOffice 4.1\\program\\unopkg.exe",
+ "C:\\Program Files (x86)\\LibreOffice 4.1\\program\\unopkg.exe",
+ "C:\\Program Files\\LibreOffice 3\\program\\unopkg.exe",
+ "C:\\Program Files (x86)\\LibreOffice 3\\program\\unopkg.exe",
+ "C:\\Program Files\\LibreOffice 3.3\\program\\unopkg.exe",
+ "C:\\Program Files (x86)\\LibreOffice 3.3\\program\\unopkg.exe",
+ "C:\\Program Files\\LibreOffice 3.4\\program\\unopkg.exe",
+ "C:\\Program Files (x86)\\LibreOffice 3.4\\program\\unopkg.exe",
+ "C:\\Program Files\\LibreOffice 3.5\\program\\unopkg.exe",
+ "C:\\Program Files (x86)\\LibreOffice 3.5\\program\\unopkg.exe",
+ "C:\\Program Files\\LibreOffice 3.6\\program\\unopkg.exe",
+ "C:\\Program Files (x86)\\LibreOffice 3.6\\program\\unopkg.exe",
+ "C:\\Program Files\\LibreOffice 3.7\\program\\unopkg.exe",
+ "C:\\Program Files (x86)\\LibreOffice 3.7\\program\\unopkg.exe",
+ "C:\\Program Files\\OpenOffice 4\\program\\unopkg.exe",
+ "C:\\Program Files (x86)\\OpenOffice 4\\program\\unopkg.exe",
+ "C:\\Program Files\\OpenOffice.org 3.1\\program\\unopkg.exe",
+ "C:\\Program Files (x86)\\OpenOffice.org 3.1\\program\\unopkg.exe",
+ "C:\\Program Files\\OpenOffice.org 3.2\\program\\unopkg.exe",
+ "C:\\Program Files (x86)\\OpenOffice.org 3.2\\program\\unopkg.exe",
+ "C:\\Program Files\\OpenOffice.org 3.3\\program\\unopkg.exe",
+ "C:\\Program Files (x86)\\OpenOffice.org 3.3\\program\\unopkg.exe",
+ "C:\\Program Files\\OpenOffice.org 3.4\\program\\unopkg.exe",
+ "C:\\Program Files (x86)\\OpenOffice.org 3.4\\program\\unopkg.exe",
+ "C:\\Program Files\\OpenOffice.org 3\\program\\unopkg.exe",
+ "C:\\Program Files (x86)\\OpenOffice.org 3\\program\\unopkg.exe",
+ "C:\\Program Files\\OpenOffice.org 2.4\\program\\unopkg.exe",
+ "C:\\Program Files (x86)\\OpenOffice.org 2.4\\program\\unopkg.exe",
+ "C:\\Program Files\\OpenOffice.org 2\\program\\unopkg.exe",
+ "C:\\Program Files (x86)\\OpenOffice.org 2\\program\\unopkg.exe"
+ ],
+ Other:[
+ "/usr/bin/unopkg",
+
+ "/usr/lib/libreoffice/program/unopkg",
+ "/usr/lib64/libreoffice/program/unopkg",
+
+ "/usr/lib/openoffice/program/unopkg",
+ "/usr/lib64/openoffice/program/unopkg",
+
+ "/usr/lib/libreoffice4/program/unopkg",
+ "/usr/lib64/libreoffice4/program/unopkg",
+ "/usr/lib/libreoffice3/program/unopkg",
+ "/usr/lib64/libreoffice3/program/unopkg",
+
+ "/usr/lib/openoffice.org3/program/unopkg",
+ "/usr/lib64/openoffice.org3/program/unopkg",
+
+ "/usr/lib/ooo3/program/unopkg",
+ "/usr/lib64/ooo3/program/unopkg",
+
+ "/opt/openoffice4/program/unopkg",
+ "/opt/openoffice.org3.5/program/unopkg",
+ "/usr/local/opt/openoffice.org3.5/program/unopkg",
+ "/opt/openoffice.org3.4/program/unopkg",
+ "/usr/local/opt/openoffice.org3.4/program/unopkg",
+ "/opt/openoffice.org3.3/program/unopkg",
+ "/usr/local/opt/openoffice.org3.3/program/unopkg",
+ "/opt/openoffice.org3.2/program/unopkg",
+ "/usr/local/opt/openoffice.org3.2/program/unopkg",
+ "/opt/openoffice.org3.1/program/unopkg",
+ "/usr/local/opt/openoffice.org3.1/program/unopkg",
+ "/opt/openoffice.org3/program/unopkg",
+ "/usr/local/opt/openoffice.org3/program/unopkg",
+ "/opt/openoffice.org2.4/program/unopkg",
+ "/usr/local/opt/openoffice.org2.4/program/unopkg",
+ "/opt/openoffice.org2/program/unopkg",
+ "/usr/local/opt/openoffice.org2/program/unopkg",
+
+ "/opt/libreoffice/program/unopkg",
+ "/opt/libreoffice3/program/unopkg",
+ "/opt/libreoffice3.4/program/unopkg",
+ "/opt/libreoffice3.5/program/unopkg",
+ "/opt/libreoffice3.6/program/unopkg",
+ "/opt/libreoffice3.7/program/unopkg",
+ "/opt/libreoffice4.0/program/unopkg",
+ "/opt/libreoffice4.1/program/unopkg",
+ "/opt/libreoffice4.2/program/unopkg",
+ "/opt/libreoffice5.0/program/unopkg",
+ "/opt/libreoffice5.1/program/unopkg",
+ "/opt/libreoffice5.2/program/unopkg",
+ "/opt/libreoffice5.3/program/unopkg",
+ "/opt/libreoffice5.4/program/unopkg"
+ ]
+};
+
+const UNOPKG_RELPATHS = {
+ Mac:[
+ "Contents/MacOS/unopkg"
+ ],
+ Win:[
+ "program\\unopkg.exe"
+ ],
+ Other:[
+ "program/unopkg"
+ ]
+};
+
+var Plugin = new function() {
+ this.UNOPKG_PATHS_PREF = "unopkgPaths";
+
+ this.EXTENSION_STRING = "Zotero LibreOffice Integration";
+ this.EXTENSION_ID = "zoteroOpenOfficeIntegration@zotero.org";
+ this.EXTENSION_PREF_BRANCH = "extensions.zoteroOpenOfficeIntegration.";
+ this.EXTENSION_DIR = "zotero-openoffice-integration";
+ this.APP = 'LibreOffice';
+
+ this.REQUIRED_ADDONS = [{
+ name: "Zotero",
+ url: "zotero.org",
+ id: "zotero@chnm.gmu.edu",
+ minVersion: "2.1b7.SVN",
+ required: true
+ }, {
+ name: "Zotero Word for Mac Integration",
+ url: "zotero.org/support/word_processor_plugin_installation",
+ id: "zoteroMacWordIntegration@zotero.org",
+ minVersion: "3.1.6.SVN",
+ required: false
+ }, {
+ name: "Zotero Word for Windows Integration",
+ url: "zotero.org/support/word_processor_plugin_installation",
+ id: "zoteroWinWordIntegration@zotero.org",
+ minVersion: "3.1.2.SVN",
+ required: false
+ }];
+
+ // Bump if you want to trigger auto-update
+ this.LAST_INSTALLED_FILE_UPDATE = "5.0.6pre";
+ this.DISABLE_PROGRESS_WINDOW = true;
+
+ var zoteroPluginInstaller, pathToAddon, installing, prefBranch, wizardWindow;
+
+ this.verifyNotCorrupt = function() {}
+
+ this.__defineGetter__("platform", function() {
+ if(Zotero.isMac) {
+ return "Mac";
+ } if(Zotero.isWin) {
+ return "Win";
+ }
+ return "Other";
+ });
+
+ this.install = function(zpi) {
+ if(wizardWindow && !wizardWindow.closed) {
+ wizardWindow.focus();
+ return;
+ }
+ if(installing) return;
+
+ zoteroPluginInstaller = zpi;
+ this.pathToAddon = zoteroPluginInstaller.getAddonPath(this.EXTENSION_ID);
+
+ // look for installations
+ var installations = this.getInstallations(),
+ haveSelectedPaths = false,
+ havePaths = false;
+ for(var i in installations) {
+ haveSelectedPaths |= (installations[i] === true);
+ havePaths = true;
+ }
+
+ if(haveSelectedPaths && !zpi.force) {
+ // If there are installations already selected from a previous install and we are not
+ // being forced to show wizard, do silent install
+
+ // Automatically select new installations
+ for(var i in installations) {
+ if(installations[i] === null) installations[i] = true;
+ }
+
+ this.installComponents(installations, function(success) {
+ if(success) {
+ zpi.success();
+ } else {
+ openInstallationWizard();
+ }
+ });
+ } else if(!zpi.failSilently || havePaths) {
+ // Otherwise, if there are installations and we are not failing silently, open the
+ // wizard
+ openInstallationWizard();
+ }
+ }
+
+ /**
+ * Creates a new nsIFile corresponding to a given path
+ */
+ this.getFile = function(path) {
+ var file = Components.classes["@mozilla.org/file/local;1"].
+ createInstance(Components.interfaces.nsILocalFile);
+ file.followLinks = true;
+ file.initWithPath(path);
+ return file;
+ }
+
+ /**
+ * Gets a list of potential LibreOffice installations by
+ * checking paths and checking the preferences.
+ *
+ * @return {Object} An object whose keys are paths and whose values
+ * are either true, false, or null, representing installations that
+ * the user has selected in the past, installations that the user
+ * has not selected in the past, and installations that were not
+ * previously known, respectively.
+ */
+ this.getInstallations = function() {
+ // First try getting unopkg paths pref
+ var previousPaths, paths = {};
+ try {
+ previousPaths = JSON.parse(zoteroPluginInstaller.prefBranch.getCharPref(this.UNOPKG_PATHS_PREF));
+ } catch(e) {
+ previousPaths = {};
+ }
+
+ if(previousPaths instanceof Array) {
+ // Convert old-format unopkg path array to object
+ var convertPaths = previousPaths;
+ previousPaths = {};
+ for(var i=0; i<convertPaths.length; i++) {
+ previousPaths[convertPaths[i]] = true;
+ }
+ }
+
+ // Add previousPaths that exist to paths array
+ for(var path in previousPaths) {
+ try {
+ if(Plugin.getFile(path).exists()) {
+ paths[path] = previousPaths[path];
+ }
+ } catch(e) {};
+ }
+
+ // Start looking for paths from the list above, in case new
+ // copies/versions of LibreOffice/OpenOffice have been
+ // installed
+ var potentialLocations = UNOPKG_LOCATIONS[Plugin.platform];
+
+ if(Zotero.isWin) {
+ var wrk = Components.classes["@mozilla.org/windows-registry-key;1"]
+ .createInstance(Components.interfaces.nsIWindowsRegKey), path;
+ try {
+ wrk.open(Components.interfaces.nsIWindowsRegKey.ROOT_KEY_LOCAL_MACHINE,
+ "Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\unopkg.exe",
+ Components.interfaces.nsIWindowsRegKey.ACCESS_READ);
+ try {
+ path = wrk.readStringValue("");
+ } finally {
+ wrk.close();
+ }
+ } catch(e) {}
+ if(path) {
+ potentialLocations = potentialLocations.slice();
+ potentialLocations.push(path);
+ }
+ }
+
+ for (let potentialLocation of potentialLocations) {
+ try {
+ var file = Plugin.getFile(potentialLocation);
+ } catch(e) {
+ continue;
+ }
+
+ if(!paths.hasOwnProperty(file.path) && file.exists()) {
+ paths[file.path] = null;
+ }
+ }
+
+ return paths;
+ }
+
+ /**
+ * Gets the path to the LibreOffice oxt file
+ * @return {nsIFile}
+ */
+ this.getOxtPath = function() {
+ var oxt = this.pathToAddon.clone();
+ oxt.append("install");
+ oxt.append("Zotero_OpenOffice_Integration.oxt");
+ return oxt;
+ }
+
+ /**
+ * Installs LibreOffice components
+ * @param {String[]} unopkgPaths Paths to unopkg
+ * @param {Function} callback Function to call when installation is complete. Argument
+ * reflects whether installation was successful.
+ */
+ this.installComponents = function(unopkgPaths, callback) {
+ // set prefs in preferences
+ zoteroPluginInstaller.prefBranch.setCharPref(this.UNOPKG_PATHS_PREF, JSON.stringify(unopkgPaths));
+
+ // get path to oxt
+ var oxt = this.getOxtPath();
+
+ // start installing
+ var usePaths = [];
+ for(var i in unopkgPaths) {
+ if(unopkgPaths[i]) usePaths.push(i);
+ }
+ installComponent(oxt, usePaths, callback);
+ }
+
+ /**
+ * Opens the installation wizard dialog
+ */
+ function openInstallationWizard() {
+ var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
+ .getService(Components.interfaces.nsIWindowWatcher);
+ wizardWindow = ww.openWindow(null, "chrome://zotero-openoffice-integration/content/install.xul",
+ "openoffice-install-wizard", "chrome,centerscreen", {"wrappedJSObject":{
+ "ZoteroOpenOfficeIntegration":Plugin,
+ "ZoteroPluginInstaller":zoteroPluginInstaller
+ }});
+ }
+
+ /**
+ * Called recursively to install to different unopkgPaths
+ */
+ function installComponent(oxt, unopkgPaths, callback) {
+ installing = true;
+
+ // if all unopkgPaths have been exhausted, we were successful
+ if(!unopkgPaths.length) {
+ installing = false;
+ callback(true);
+ return;
+ }
+
+ // otherwise, install to next unopkg path
+ var proc = Components.classes["@mozilla.org/process/util;1"].
+ createInstance(Components.interfaces.nsIProcess);
+ var path = unopkgPaths.shift();
+ Zotero.debug("ZoteroOpenOfficeIntegration: Installing with unopkg at "+path);
+ proc.init(Plugin.getFile(path));
+
+ proc.runAsync(["remove", "org.Zotero.integration.openoffice"], 2, {"observe":function() {
+ proc.runAsync(["add", oxt.path], 2, {"observe":function(process, topic) {
+ if(topic === "process-finished" && !process.exitValue) {
+ // recursively continue installing until all unopkgPaths are exhausted
+ installComponent(oxt, unopkgPaths, callback);
+ } else {
+ // abort on error
+ installing = false;
+ callback(false);
+ throw "unopkg at "+path+" failed to install";
+ }
+ }});
+ }});
+ }
+}
diff --git a/scripts/symlink_sdk b/scripts/symlink_sdk
new file mode 100755
index 0000000..b5788d4
--- /dev/null
+++ b/scripts/symlink_sdk
@@ -0,0 +1,45 @@
+#!/bin/bash
+
+CWD="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
+SYMLINK_LOCATION="$CWD/../build/lib/libreoffice-sdk"
+
+if [[ -e $SYMLINK_LOCATION ]]; then
+ if [[ -L $SYMLINK_LOCATION ]]; then
+ rm $SYMLINK_LOCATION
+ else
+ echo "$SYMLINK_LOCATION already exists and is not a symlink."
+ exit 1
+ fi
+fi
+
+SDK_LOCATION=""
+if [[ "`uname`" = "Darwin" ]]; then
+ SDK_LOCATION="/Applications/LibreOffice.app/Contents/Resources/java"
+elif [[ "`uname`" = "Linux" ]]; then
+ SDK_LOCATION="$(echo /opt/libreoffice*/program/classes)"
+fi
+
+SEARCH=""
+if [[ ! -e "$SDK_LOCATION/java_uno.jar" ]]; then
+ read -e -p "LibreOffice SDK directory not found under default location. Perform search (might take a while) [Y/n]? " SEARCH
+
+ if [[ $SEARCH =~ ^[Yy]*$ ]]; then
+ JAVA_UNO="$(locate java_uno.jar | tail -n 1)"
+ if [[ ! -z $JAVA_UNO ]]; then
+ SDK_LOCATION=$(dirname "$JAVA_UNO")
+ fi
+ fi
+fi
+
+
+if [[ ! -e "$SDK_LOCATION/java_uno.jar" ]]; then
+ read -e -p "LibreOffice SDK files not found. Specify a directory that contains java_uno.jar: " SDK_LOCATION
+fi
+
+if [[ ! -e "$SDK_LOCATION/java_uno.jar" ]]; then
+ echo "LibreOffice SDK files not found. They should be located in your libreoffice installation directory under 'java' or 'classes'."
+ exit 1
+else
+
+ ln -s $SDK_LOCATION $SYMLINK_LOCATION && { echo "LibreOffice SDK ($SDK_LOCATION) symlinked for development with Eclipse."; }
+fi
diff --git a/update.rdf b/update.rdf
new file mode 100644
index 0000000..e2e6ea9
--- /dev/null
+++ b/update.rdf
@@ -0,0 +1,33 @@
+<?xml version="1.0"?>
+<RDF:RDF xmlns:RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ xmlns="http://www.mozilla.org/2004/em-rdf#">
+<RDF:Description about="urn:mozilla:extension:zoteroOpenOfficeIntegration@zotero.org">
+ <updates>
+ <RDF:Seq>
+ <RDF:li>
+ <RDF:Description>
+ <version>5.0.6.SOURCE</version>
+ <targetApplication>
+ <RDF:Description>
+ <id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</id>
+ <minVersion>4</minVersion>
+ <maxVersion>53.*</maxVersion>
+ <updateLink>http://download.zotero.org/integration/Zotero-LibreOffice-Plugin.xpi</updateLink>
+ <updateHash>sha1:</updateHash>
+ </RDF:Description>
+ </targetApplication>
+ <targetApplication>
+ <RDF:Description>
+ <id>zotero@chnm.gmu.edu</id>
+ <minVersion>4.0</minVersion>
+ <maxVersion>5.0.*</maxVersion>
+ <updateLink>http://download.zotero.org/integration/Zotero-LibreOffice-Plugin.xpi</updateLink>
+ <updateHash>sha1:</updateHash>
+ </RDF:Description>
+ </targetApplication>
+ </RDF:Description>
+ </RDF:li>
+ </RDF:Seq>
+ </updates>
+</RDF:Description>
+</RDF:RDF>