Этот перевод не завершён. Пожалуйста, помогите перевести эту статью с английского
Выбираем правильные инструменты
Есть три основных инструмента, которые на наш взгляд необходимы для эффективной разработки дополнения: редактор исходного кода, сиcтема управления версиями и система сборки.
Что касается редактирования кода, официальной интегрированной среды разработки от компании Mozilla нет. С другой стороны, расширения используют те же (или похожие) языки, используемые для веб-разработки, поэтому для этой задачи подойдут большинство текстовых редакторов или интегрированных сред разработки. Большинство XUL-инструментов и плагинов, которые вы найдете в сети Интернет, являются простыми шаблонами, которые создают структуру папок проекта, и это не очень помогает.
Мы рекомендуем текстовый редактор Komodo Edit. Он бесплатный, с открытым исходным кодом и кроссплатформенный. Он основан на платформе Mozilla XULRunner, поэтому поддерживает некоторые особенности при разработке расширений Firefox. Komodo Edit поддерживает автодополнение тегов и аттрибутов XUL, расширение Mozilla's CSS extensions (CSS значения и свойства, начинающиеся на "-moz"). У редактора есть система дополнений, схожая с той, что используется в браузере Firefox, и есть несколько Komodo расширений, которые предоставляют дополнительную помощь в разработке. Это приложение предоставляет больше возможностей, по сравнении с множеством других редакторов, поэтому мы рекомендуем вам попровать его. Все наши примеры исходных кодов разрабатываются на Komodo Edit, поэтому если в скачанных файлах с примерами вы увидете расширения .kpf или .komodoproject , то знайте, что это файлы проекта Komodo.
Что касается системы управления версиями, мы рекомендует лишь чтобы она у вас была. Самая распространенная система - это GitHub, но подойдет и любая другая.
Для упаковки XPI-файлов мы используем утилиту make. Мы выбрали этот способ, потому что он используется компанией Mozilla для сборки Firefox, и доступен для большинства операционных систем. Утилита make - это стандартный инструмент для Unix-совместимых операционных систем. Она может быть установлена на Mac OS X в составе пакета программ XCode Tools и на Windows с пакетом программ cygwin. При установке cygwin у вас будет возможность явно выбрать утилиты make и zip из длинного списка для скачивания и установки.
Также убедитесь в том, что утилита make корректно прописалась в системную директорию для запуска. Для этого после ее установки выполните команду "make -ver" в командной строке, и если все сделано правильно - на экран будет выведена версия утилиты make.
Мы рекомендуем установить утилиту make в вашей операционной системе, поскольку все наши примеры предоставляются со всеми необходимыми файлами для сборки и установки получившегося XPI-файла используя этот инструмент. Это сбережет вам время при упаковке. Или вы можете создать свою собственную систему, используя бат-файл, утилиту Ant или любую другую в зависимости от ваших предпочтений. В конечном счете, вы можете просто сжимать содержимое папки src используя любой zip-архиватор или любой другой, и получить аналогичный результат.
Let's start by downloading the project used to build the second version of Hello World, from the exercise in the last section.
Unzip the file anywhere you want. Inside the HelloWorld2 directory, you'll see two directories: bin and src. The bin directory should be empty. This is where all the resulting build files will be created, and where you'll find the extension XPI file once you get it to build.
Open the project file (HelloWorld2.komodoproject) from the src directory in Komodo Edit. In the Projects tab you should be able to see the directory structure inside the src directory. This structure should be familiar, as it is almost identical to the unpacked XPI from the previous section.
The only notable additions is a file named Makefile under src. This is the file that make uses to build the XPI. You should take some time to read it and understand it, or at least identify the parts that you should change to get a project of your own going. This GNU Make Manual is a very good reference to get to know make and Makefiles.
In most cases you'll only need to change the first lines in Makefile. These define the extension name, the extension id (as specified in install.rdf) and the name of the profile directory where the extension will be installed during development and testing. More about this further ahead.
Let's try and build the XPI from the command line first. Open the command line program in your system and navigate to the src directory in your project. Run the following command:
That's it. If everything went well, you should see an output similar to this:
If you inspect the bin directory, you should see the xulschoolhello2.xpi file.
If you run make again, you'll only see the last line of the build process. That is because make can tell that the file in the bin directory is up to date, and nothing needs to be done. Making changes on source files will make make run the necessary steps to build the XPI again.
You can clean up the bin directory by just running the following command (again, from the src directory):
You can also run these commands from Komodo. Click on Tools > Run Command.... In the "Run" textbox you should type this:
Or replace "make" with "make clean" for the clean command. The "bash -c" part forces Komodo to use bash, which for some reason can't be set properly as the default command shell. It isn't necessary to add this, but it's better so that it is consistent with the make command we'll see next.
In the "Start in" textbox you should choose %p (directory path of active project). If you don't see this textbox, click on the "More" button. You also have the option to save the command, by clicking on the "Add to Toolbox" checkbox. To see the Toolbox, click on View > Tabs > Toolbox, from the main menu. With that, you should now have a very easy way to build your XPI, by just double clicking on the created commands.
We can make it even better. Once you're testing and debugging your code, you'll find that constantly building and installing an XPI can be very tedious. This is the reason why we introduced "make install". This only works if your extension is already installed in a Firefox profile. Just like in the provided project, you need the add-on id and profile location set in the file Makefile. We use this information to locate the installation path of the extension and overwrite the installed files. If Firefox is open at the time you run "make install", you'll have to restart it in order to see the changes. It's still better than installing the XPI all over again.
In order to set the profile location to the right value, you should read the support article on profiles, at the Mozilla Support site. We'll also delve deeper in this topic later on in this section.
To make "make install" work on non-Windows systems, you need an extra step. The install process requires using an environment variable called OSTYPE, which is not exported. Long story short, if you want to run it from a command line, you need to run:
And in the command in Komodo, you should enter the following:
The export command won't work correctly unless you use "bash -c".
Building IDL files
Some extensions require developing XPCOM components to add certain advanced functions. There's a section dedicated to XPCOM in this tutorial, but we'll briefly discuss the impact it has on building the extension. You can skip this section and keep it present as a reference in case you do need to use XPCOM in your project.
XPCOM interfaces are defined using IDL files. These are text files that define the attributes and methods in one or more interfaces. These IDL files are compiled into binary form and included in the extension as XPT files.
To compile an IDL file to XPT, you need a command line tool called xpidl. This tool is included in the Mozilla Gecko SDK. If you need to compile IDLs, go to the SDK page and download a compiled version for your system. Also note any prerequisites you may need. If your system is not listed in the supported builds, you'll have to build the SDK yourself from the Mozilla source. Good luck with that.
You should also set up your environment so that xpidl.exe (or just xpidl on other systems) is in the default executable path, and also add a variable called GECKO_SDK, that points to your SDK build:
Our build system should pick it up from there. To make it work in Komodo in Unix-based systems, we add the command to the .bash_login file in the home directory, and we modify the commands to this:
An example project with XPCOM components is included in the XPCOM section. There is also a mention about building C++ XPCOM, which is something much more complicated.
In order to provide additional security for your users, you can choose to add a signature to your extension. The signature verifies that you are the author of this extension, and it can only be done if you have a valid certificate provided by a trusted Certificate Authority.
The only noticeable difference for the user is that the XPI installation dialog will say that the extension was created by you, making the dialog a little easier to trust. It's not common to sign extensions because most users will trust the official add-ons site (AMO) rather than rely on extension signatures. On the other hand, it is standard practice for big companies to sign their extensions.
You'll need to download some libraries in order to be able to sign your extension. Follow the instructions, and add something like the following to your Makefile:
Keep in mind that your password should not be in your Makefiles, and you must be very careful with the certificate information. Ideally this should be handled by a single person, and only done near the end of the release process. You should also have a different make command, such as make signed in order to distinguish the signed and unsigned development builds.
Firefox profile management
It is good development practice to keep your test environment separate from everything else. You don't want unstable extensions to break your everyday Firefox profile, risking data loss. It's much better to have a different "version" of Firefox for testing. This is what Firefox profiles are for.
You can learn about setting up multiple Firefox profiles in the Mozilla Support article Managing Profiles. You can have as many profiles as you like. You can also mix them with multiple Firefox installations. For instance, you may want to test your extension in Firefox 3.5 and Firefox 3.6, or test it in a localized version of Firefox. You can install as many Firefox versions as you want, and mix profiles and versions.
On Windows and Linux it's easy to create shortcuts for every profile you create, using the commands mentioned in the support article.
For Mac OS X developers, there is also a way to set up "shortcuts". You can do this by opening the Automator application, choosing Run Shell Script and then entering the profile-loading script in the textbox:
You can change "/dev/null" to a file location, in case you want to see dump output from Firefox, or other extensions. The last & prevents Automator from waiting for your Firefox session to finish. Save this as an Application, not a Workflow. And you probably want to have these on your Desktop or Dock, for easy access.
There's a wide variety of Firefox extensions that aid web development and add-on development. A good place to look for them is the Mozilla Add-ons site, and there's also a good development extension list here. You should also take some time to play around with the Web Developer tools that are included in Firefox. Some of them can be very useful for add-on development and overlap with the add-ons listed. In this section we'll cover a few that we have found to be very useful.
Tamper Data intercepts HTTP requests and their responses. It allows you to cancel them and even replace payload data before it is sent. There are several similar extensions, such as Live HTTP Headers, but Tamper Data is the one that we use the most. We'll cover more on HTTP debugging later on.
The Firebug extension includes pretty much all tools mentioned so far, but it's mostly focused on web development. The Chromebug extension helps in making Firebug more useful for extension development, but it may still not be powerful enough to replace all of the previously mentioned add-ons.
On the other hand, Firebug has a very friendly, integrated user interface, and sees much more development that its counterparts. It's definitely worth a try.
Memory leaks have always been a big criticism drawn against Firefox. Mozilla has proven with time that they take memory usage seriously, improving performance on several critical areas and removing all kinds of memory leaks.
To make sure your extension doesn't leak, you should use the Leak Monitor extension when testing it. Always test opening and closing windows. Leaks usually surface when doing this.
- Set up a new Firefox profile for XUL School. Make sure you can open and close your XUL School Firefox without having to close the instance of Firefox you use to browse normally (you use Firefox, don't you?). Make any modifications you want to the XUL School project, and use make and make install to see the extension work with your changes.
- Install DOM Inspector. Use it to locate the menu you created. Inspect the CSS rules Firefox applies to it by default. Look at the final, computed style for the menu items. Browse around the rest of the Firefox DOM, and try to figure out what the nodes correspond to in the Firefox UI.
- Install the Tamper Data extension. Open the Tamper Data window and go to a AJAX-heavy page such as Gmail or Facebook (don't click on the Start Tamper button, it's not necessary for this). Try to identify what is going on with some of the requests being sent.
Now that you know how to quickly monitor your project and test changes, we'll learn how to add new UI elements to Firefox, through overlays and new windows.
This tutorial was kindly donated to Mozilla by Appcoast._