Firefox. Увеличение ожидания загрузки (timeout) страницы.
+
+
+
+
+
При выполнении каких-либо ресурсоёмких операций на интернет ресурсах, когда время отклика может переваливать за минуты, а то и больше, браузеры прерывают соединение и сообщают, что сервер не доступен.
+
К таким операция, например, можно отнести выгрузку дампа базы данных в phpmyadmin, парсинг больших файлов и прочее.
+
Максимальное время ожидания (timeout) в браузерах по умолчанию обычно настроено на несколько минут. В браузере Firefox, если я не ошибаюсь, это значение равно 5 минут.
+
Нам, конечно, прерывать соединение не хочется, т.к. проводимая операция может прерваться, и, следовательно, возникнуть дальнейшие проблемы из-за неправильного выполнения операции.
+
Благо данную настройку в Firefox можно изменить. Для этого:
+
+
Открываем новую вкладку
+
В адресной строку пишем «about:config» и нажимаем Enter
+
Соглашаемся с сообщением о риске
+
В поле поиска вводим параметр «network.http.response.timeout»
+
Двойным нажатием открываем окно настройки данного параметра
+
Вводим необходимое время в секундах, например, 1800 (пол часа)
+
Нажимаем ОК и закрываем вкладку.
+
+
P.S. Иногда данная опция оказывается даже очень полезной. В небезызвестном браузере Chrome данный параметр для настройки отсутствует.
Геральд Нанн — разработчик Tilix (ранее называвшийся Terminix). Tilix— продвинутый тайлинговый эмулятор терминалов с открытым исходным кодом, который является самым «звёздным» проектом на основе D на GitHub, недавно даже обогнавший стандартный компилятор D, DMD. В этом году на DConf в Берлине он рассказывал о том, как использует D. Имеются слайды и видео. В своей повседневной работе, которая не имеет ничего общего с настольными графическими приложениями, он является старшим разработчиком промежуточных решений в Red Hat. [Подробнее об истории Джеральда в расширенном интервью — Ред.]
+
Йоаким: — Что такое тайлинговый эмулятор терминала?
+
Геральд: — Тайлинговый эмулятор терминала позволяет разделить терминал на несколько частей и распределить их в удобном порядке и месте, что наиболее удобно при работе над конкретной задачей. Люди, которые работают на нескольких терминалах одновременно, как правило, находят такие инструменты наиболее полезными, особенно с постоянно увеличивающимися размерами мониторов и разрешений.
+
Несмотря на то, что Tilix очень хорош, основной причиной, по которой я создал его, было то, что мне нужен был эмулятор терминала, который следовал бы концепции Gnome HIG (Human Interface Guidelines — рекомендации по созданию интуитивных, легко изучаемых и логичных интерфейсов взаимодействия с пользователем) и использовал CSD (Client-Side Decorations — отрисовку на стороне клиента). Tilix следует Gnome HIG, опубликованным здесь, что означает соблюдение интервалов, макетов и других рекомендаций. После HIG важно, чтобы приложение соответствовало всему рабочему столу в целом.
+
CSD ссылается на заголовок окна, где не диспетчер дисплея, а пользователь берёт на себя ответственность за него и может заполнять панель заголовка кнопками и другими элементами управления. Это часть концепции Gnome HIG, и большинство приложений Gnome (gedit, файлы, видео) по умолчанию используют этот подход. Единственное исключением является gnome-terminal, который вообще не использует CSD.
+
Й.: — Можете привести несколько примеров того, как вы используете концепцию Gnome HIG?
+
Г.: — Gnome HIG определяет конкретный язык дизайна в отношении того, как приложения, работающие в Gnome, должны выглядеть и показывать себя. Некоторые примеры Tilix, следующие концепции HIG, включают использование CSD и меню приложений по рекомендациям, таким как интервалы, макеты и т.д. Кроме того, разработчики Gnome собрали множество макетов, как они думают, как должны выглядеть различные приложения. Tilix использует макеты, разработанные дизайнерами Gnome для терминала, где это возможно. Например, в Tilix диалог предпочтений и профилей использовался отдельно, однако один из дизайнеров Gnome предложил этот макет для gnome-терминала. Я пошел вперед и реализовал его в Tilix, гораздо лучше, чем раньше.
+
В результате использования CSD и концепции Gnome HIG, надеюсь, что использование Tilix в Gnome более органичено для пользователей.
+
Интересная вещь — это напряженность между людьми, которые используют Tilix на Gnome и тех, кто использует его в других дистрибутивах. Хотя я не имею никаких сомнений в том, что разработка под Gnome является моей основной целью, я стараюсь сделать Tilix лучше и в других средах рабочего стола, разрешив пользователю отключить CSD в пользу обычного заголовка, если они того пожелают.
+
Й.: — Вы попали в D из среды Java. Вы все еще пишете код в стиле Java на D? Это было легко, т.е. сколько вам пришлось привыкать, чтобы писать на D?
+
Г.: — Да, чаще всего работаю с Java. Я нашёл это довольно интересным на DConf, когда я спросил, как много людей пришли не из среды C/C++ , только один человек поднял руку.
+
Если вы посмотрите на мой код в Tilix, то он очень похож на Java-код. Некоторое из этого связано с моей обычное средой, в которой я работаю, а некоторое из-за того, что GtkD является оболочкой классов.
+
Я считаю, что переключение между D и Java является довольно плавным по большей части; между ними гораздо меньше когнитивного трения, чем, скажем, между переключением между Java и Python.
+
Самая важная идиома D, которую мне пришлось изучить, — это диапазоны, поскольку они являются основополагающей особенностью D. Однако это не было сильно сложным. Выполнение функций времени компиляции (CTFE) по-прежнему остаются для меня неестественными. Когда я использую их, мне приходится каждый раз искать про них информацию, и мои текущие попытки использования CTFE с точки зрения кода довольны глупы. Я хотел бы больше использовать CTFE в Tilix, поскольку я получаю всё больший опыт использования D.
+
Наконец, мой недостаток опыта работы с C выявляет другую проблему, с которой я немного борюсь — это взаимодействие с кодом на C. Хотя по большей части это довольно просто, но, когда мне приходится расшифровывать что-то сложное, оно становится не таким простым. Поддержка FlatPak (система изолированных контейнеров для графических приложений) в настоящее время есть, так как мне не приходилось так сильно напрягаться по некоторым вопросам, с которыми я сталкивался на C.
+
Сказав это, у меня есть некоторый опыт разработки собственного кода, поскольку много лет назад я потратил много времени на разработку кода на Delphi и Object Pascal. Именно на это и приходится большая часть моего опыта работы с графическим интерфейсом.
+
Й.: — И из вашего выступления на DConf вы явное не беспокоились о сборщике мусора (GC). Вам приходилось думать о нём, когда вы разрабатывали Tilix? Имелись ли проблемы задержек с GUI, вызванные GC?
+
Г.: — Придя из Java, GC для меня довольно естественен, и я определенно не считаю его плохим для D. Я думаю, что GC в D получает много плохой прессы на основе опыта Java, но важно помнить, что GC в D сильно отличается от того, что в Java. Самое большое различие для меня в том, что в D есть больше возможностей для его управления, так как он хорошо понимает, когда он может начать цикл GC. Я был очень рад видеть, как больше людей поднимают различные темы на reddit и форумах, жалуются на использование GC.
+
У меня не было никаких проблем с GC с точки зрения пауз, и ни один пользователь Tilix не сообщал об этом. У меня было несколько проблем, связанных с GC, в основном связанных с утечкой памяти из-за хранения ссылок, но все они были ошибками программного кода, а не проблемой с реализацией GC в D. У меня есть другое приложение на GTK D, Visual Grep, где я столкнулся с ужасающей эффективностью при обработке большого количества совпадений в tight-цикле (цикл, который содержит несколько инструкций и повторяется много раз.). Тем не менее, просто отключив GC для этого раздела кода, ускорилось все.
+
Й.: — Репозиторий github для Tilix замечательно чист, нет открытых запросов «pull request» (PR) и низкий процент проблем, которые все еще открыты. Сколько времени вы еженедельно тратите на Tilix? Является ли Tilix только хобби или он стал чем-то большим?
+
Г.: — Tilix — это просто хобби. Я, вероятно, провожу от 5 до 10 часов в неделю. На данный момент — это зрелое приложение, следовательно, относительно небольшое количество проблем. Я также уделяю приоритетное внимание исправлению ошибок при добавлении новых функций, что помогает сохранить список управляемым.
+
Что касается запросов на «pull request» (PR), я твердо убежден в том, что я должен быть отзывчивым, поэтому я, как правило, отвечаю на PR в течение дня или двух. В качестве участника разработок я знаю, что ничего не убивает интерес, как видеть, что ваш PR томится в течение нескольких недель, месяцев или даже лет. Если вы хотите, чтобы люди вносили свой вклад, что я определенно делаю, то я чувствую, что вы обязаны участникам разработки своевременно реагировать на их PR.
+
На данный момент Tiltx — это относительно небольшой проект, поэтому мне легко принять этот подход. Я понимаю, почему более крупные проекты могут иметь больше проблем в этой области.
+
Й.: — D имеет много особенностей, насколько хорошо вы их знаете? Вы упомянули, что хотите использовать некоторые из возможностей времени компиляции. Как вы думаете за счёт каких особенностей D и что Tilix выиграет в будущем и как?
+
Г.: — Я не думаю, что знаю это, если честно, помимо основного набора особенностей, которые я использую в Tilix. Я всегда удивляюсь ребятам на форуме, которые могут утверждать достоинства/недостатки низкоуровневых деталей языка. Это определенно не я. Я бы хотел поправиться, но на самом деле я использую D только как хобби, поэтому я не могу тратить столько же времени, сколько и на Java. Кроме того, моя работа в Red Hat имеет больше компонентов инфраструктуры, чем мои предыдущие рабочие места, поэтому большая часть моего времени расходуется дома на обучение в этом направлении.
+
Что касается возможностей, от которых Tilix выиграет, я думаю, что использование CTFE и диапазонов было бы очень полезно для того, чтобы улучшить некоторые моменты в GtkD более идиоматичным способом. У меня есть достаточное количество кода, где он может быть намного более кратким при соответствующем использовании CTFE. В качестве простого примера можно использовать диапазоны для поддержки итераций по различным артефактам с использованием foreach, а не классическим циклом. Тем не менее, я думаю, что некоторые из более сложных вариантов использования, таких как поддержка D-Bus (система межпроцессного взаимодействия, которая позволяет приложениям в операционной системе сообщаться друг с другом) и GObject, будут очень полезны.
+
Для тех, кто не знаком с GObject — это объект базового уровня в GTK и является счётчиком ссылок. Возможность легко создавать GObjects в D, как можно и в Python, упростит взаимодействие с некоторыми из API; прямо сейчас это эквивалентно написанию его в сыром C, и это несколько трудоемко. Майк Вей, сопровождающий GtkD, начал делать некоторые работы над этим.
+
Й.: — Вы упомянули на DConf, что D имеет быстрый цикл компиляции: как вы используете это, то есть какие IDE, компиляторы, toolchain (набор программ, необходимых для создания других программ) вы используете как для разработки, так и для выпуска релизов?
+
Г.: — Я использую MS Visual Studio Code на Linux с отличным плагином code-d, написанным Jan «WebFreak» Jurzitza. Это дает мне все необходимые функции (автозаполнение кода, подсказки, рекомендации и т. Д.). Единственное, чего я не вижу, что есть в Java IDE, — это возможность рефакторинга. Для разработки я использую DMD, поскольку он имеет самое быстрое время компиляции. Сборку версий выполняю с использованием LDC, компилятора D с бэкэном LLVM, поскольку он генерирует меньшие и более быстрые двоичные файлы. Мне редко приходится запускать отладчик, но, когда я это делаю, я просто использую GDB из командной строки.
+
Й.: — Какие проблемы у вас были с D? Какие его особенности вам не нравятся?
+
Г.: — Никаких серьёзных проблем с моей точки зрения. Я в целом очень доволен этим языком и считаю, что он несёт правильный баланс между простотой использования и возможностями. Наибольшее неудобство мне доставляла стандартная библиотека Phobos, а не сам язык, и эти неудобства напрямую соотносятся с нехваткой времени.
+
Никаких серьёзных проблем с Phobos, а скорее кучей раздражителей. Например, нельзя легко использовать immutable для отправки в std.concurrency, std.experimental.logger являющиеся все ещё экспериментальными, парсер json имеет проблемы, если в локализации установлена запятая для отделения десятичных знаков чисел и т.д. и т.п. Ни один из данных недочётов по себе не является особо важным, и большинство из скорее всего связаны из-за нехватки трудовых ресурсов. Я на самом деле несколько неохотно жалуюсь на них, потому что я, наверное, мог исправить их сам и отправить PR.
+
Меня больше раздражает негативность на форумах в отношении GC. Я чувствую, что иногда люди так поворачиваются в сторону D, что хотят видеть его идеальным системным языком (т.е. без GC, без безопасности памяти и т.д.), упуская из виду, что он очень хороший язык для создания приложений на данный момент. Пока D сравнивают с Rust, в некотором смысле сравнение с Go для меня более интересно. Оба языка основаны на GC и оба начинали как системные языки, однако Go опирается на GC и «удваивается» (от переводчика: скорее всего имеется в виду рост популярности), добиваясь успеха. Один из продуктов Red Hat, который я поддерживаю, OpenShift, использует Kubernetes (проект Google) для управления кластером контейнеров Linux как единой системой, и он написан на Go.
+
Я думаю, что как язык D намного превосходит Go, и мне хотелось, что мы бы заявляли об этом громче вместо постоянного отрицательного обсуждения системного программирования. На данный момент надо сказать ради справедливости, что Go имеет крупного корпоративного спонсора, в отличие от D, однако контраст в позиционировании по-прежнему интересен мне.
+
Й.: — Каковы ваши будущие планы в отношении Tilix?
+
Г.: — Две самые большие функции, которые я хотел бы добавить, это поддержка режима управления tmux и добавление возможности отображения боковой панели popout.
+
Для тех, кто не знаком с tmux, это терминальный мультиплексор; это, по сути, терминальный разделитель, но внутри самого терминала. Он также поддерживает ряд других функций, но наиболее интересным является сохранение терминальных сеансов, находящихся вне терминала. Поскольку он работает в терминале, он немного ухудшает производительность, а с точки зрения графического интерфейса он не может использовать собственные виджеты, такие как полосы прокрутки. Чтобы смягчить это, он поддерживает так называемый режим управления, который позволяет ему интегрироваться с эмулятором тайлингово терминала для создания новых терминалов, т.е. подтерминалов внутри одного терминала, управляющихся за пределами tmux. Это значительно улучшает его производительность, позволяя пользователям использовать другие функции, поддерживаемые tmux. На данный момент поддерживается только iterm2 на OSX насколько мне известно.
+
Боковая панель в Tilix является одним из наиболее противоречивых элементов интерфейса. Я решил не реализовывать интерфейс с вкладками, потому что я счел их бесполезными с точки зрения поиска открытия необходимой вкладки; там просто недостаточно места для вкладок, чтобы отличить их, и переименовывать их вручную — это «боль». Боковая панель — это моя попытка альтернативы, она отображает миниатюру каждого сеанса (известную также как ярлык) на боковой панели, которая может быть убрана по мере необходимости для переключения между сеансами.
+
+Боковая панель Tilix в действии.
+
У некоторых людей есть сильное предпочтение к тому, что постоянно доступно, но, к сожалению, все, что видно на боковой панели, непросто, так как генерация эскизов занимает значительное количество времени из-за структуры GTK. Существуют потенциальные способы заставить это работать быстрее, но требуется время на то, чтобы попробовать разные варианты, чтобы увидеть, что как отображается, а затем, что наиболее эффективно.
+
В мечтах, я бы хотел переключиться на использование эмулятора терминала, написанного изначально в D, а не GTK VTE (Virtual Terminal Emulator), который написан на C, и который я использую сейчас. Для тех, кто не знаком с ним, VTE — это виджет эмуляции терминала, используемый терминалом Gnome и доступен в виде многоразового виджета. Многие эмуляторы терминала в Linux используют этот виджет (gnome-terminal, guake, terminator, tilix и т.д.), поскольку он обеспечивает полностью готовый к работке эмулятор, который прошел через огромное количество тестов.
+
Недостатком этого является то, что любые пользовательские функции, которые вы хотите реализовать, которые включают фактический уровень эмуляции терминала, требуют модификации VTE и получения этих изменений вверх по потоку (*upstream). У меня есть несколько патчей, которые Tilix поддерживает (для триггеров и значков), но, честно говоря, я провёл плохую работу по внедрению вверх по потоку (*upstream). Частично это связано с тем, что VTE написано на C и сделать быстрый и качественный патч на C занимает достаточно много времени.
+
Таким образом, наличие эмуляции терминала, написанного на D, сделало бы это намного проще, однако это огромные инвестиции времени, поскольку люди недооценивают объем работы. В эмуляции терминала много сложных случаев, плюс добавление всего материала, чтобы сделать его удобным для пользователей (поиск, клики по ссылкам и т.д.), это много, чтобы взять на себя. У меня просто нет времени, чтобы сделать это реальностью, если только я не выиграю в лотерею. Если кто-то захочет взять на себя это роль и создать виджет эмуляции терминала GTK, который имеет все необходимые функции и поддерживал бы его в течение длительного времени, я был бы рад работать с ним, чтобы интегрировать его с Tilix. Адам Рапп уже создал один, который работает достаточно хорошо по моим тестам; если кто-то хочет работать над преобразованием его в виджет GTK, добавит необходимые улучшения и согласится его поддерживать, то пусть не стесняется писать и надоедать сообщениями (*ping) мне. 🙂
+
Й.: — Пожалуйста, расскажите из своего опыта, как вы впервые обнаружили D и использовали его для написания Tilix?
+
Г.: — На протяжении всей моей карьеры я всегда имел хобби. Некоторые вещи, над которыми я работал, включали популярную надстройку для Delphi под названием Gexperts, замену проводника файлов Windows, Java IDE под названием Gel и популярное приложение для Android под названием OnTrack Diabetes, которое я продал несколько лет назад. Пару лет назад я искал что-то новое для работы в качестве моей программы в качества хобби и остановился на идее создания десктопного приложения для Linux. Я знал, что нужно использовать инструментарий GTK, так как Gnome — моя предпочтительная среда рабочего стола, и особенно с моим прошлым опытом Delphi в графических интерфейсах, которые я мог бы использовать. Я также знал, что меня не интересует разработка на C или C ++, поэтому я посмотрел, какие альтернативы были.
+
Я начал с Python, так как у него отличная поддержка GTK, и я немного поработал над программированием Jython в WebLogic, так как я использовал Weblogic Scripting Tool (WLST). Однако большая часть моей предыдущей работы была небольшими сценариями, и я быстро понял, что в больших масштабах Python не для меня. Я вообще предпочитаю статически типизированные языки, и динамический набор текста на Python приводил меня в замешательство, особенно в качестве хобби, где я постоянно нуждался в использование справочных материалов, так как я работал на нем нечасто.
+
Я также смотрел в сторону Rust и Go, но в то время ни у одного из них не было полнофункциональных GTK-привязок. Кроме того, в то время у Rust было много позитивной прессы, но у него был плохой материал для убеждения в правильности его подхода, и я был не так сильно убежден в том, что управление безопасностью памяти с помощью контролера заимствований было лучшим подходом, чем GC.
+
Я знал о D, поскольку я посматривал на D много лет назад и полюбил этот язык, но экосистема была настолько слабой, что это было не сильно полезно для практической работы. Я взглянул на него снова и обнаружил, что он значительно улучшился и даже удивительно: были доступны полные привязки GtkD. Это также помогло тому, чтобы D и Java были достаточно похожи, и чтобы собирать на D было невероятно легко. Как только я узнал, как работают диапазоны, было легко начать кодить.
+
Сначала я создал небольшое приложение под названием Visual Grep, которое переносит grep в графический интерфейс. Когда я консультировался, мне часто приходилось собирать большие базы кода, ищущие конкретные шаблоны, и графический интерфейс, который делал просмотр шаблонов, был абсолютной необходимостью. Это было отличное первое приложение, так как я узнал немало вещей о D. Производительность приложения была изначально плохой с большими наборами результатов, потому что GC постоянно был перегружен при загрузке результатов из-за постоянного распределения. Отключение GC во время этого tight-цикла улучшило производительность неизмеримо. Я также узнал об интеграции GTK с возможностями многопоточности D.
+
Я был вдохновлен пользовательским интерфейсом от Gnome Builder IDE, и подумал, что он хорошо подойдёт для эмулятора терминала. Таким образом, Tilix родился. Ну, на самом деле сначала он назывался Terminix, но как только он начал получать популярность, я получил вежливую просьбу на переименование из-за компании Terminix, американской компании по борьбе с вредителями. Будучи канадцем, я не слишком хорошо их знал, поэтому я не много думал об этом имени. Извлеченный урок: потратьте время на выбор хорошего имени, если ваше приложение станет более популярным, чем вы ожидаете.
+
Я наслаждаюсь временем, проведённым с D, и это отличный язык для создания настольных приложений в GTK. Во многих отношениях, я чувствую, что D является естественным преемником Vala, который был языком, созданным специально для создания приложений GTK, но постепенно умирающим, в основном из-за его узкой направленности. Если вы не создаёте приложения GTK, вы не используете Vala, что означает, что количество людей, использующих его и работающий над ним, по определению очень мало.
+
Я также считаю, что D является естественным преемником Delphi, по крайней мере с GtkD, как мощным инструментом для создания настольных приложений. Благодаря быстрому времени компиляции и легкому изучению языка, он приносит множество лучших атрибутов Delphi в современную эпоху. Плюс я могу ввести {и} вместо Begin и End и увеличить свою эффективность на 75% или около того. 🙂
Модель программирования псевдоблокировки на основе волокн
+
Основная идея vibe.d заключалась в том, чтобы использовать быструю и ресурсоемкую асинхронную модель ввода-вывода (AIO) и сделать ее удобной в использовании. Некоторые другие программные платформы, такие как node.js, напрямую отображают интерфейс AIO с использованием событий, используя функции обратного вызова. Хотя это приемлемый подход, он имеет ряд недостатков.
+
Прежде всего, в node.js часто становится утомительным и запутанным писать последовательности кода (например, выполнять несколько последовательных запросов к базе данных). На каждом шаге будет представлен новый callback-вызов (обратный) с новой областью, callback-вызовы ошибок часто приходится обрабатывать отдельно. Это часто является причиной того, что возникает соблазн выполнить слабую обработку ошибок.
+
Другим следствием асинхронных callback-вызовов является отсутствие значимого стека вызовов. Мало того, что это может усложнить отладку, но такие функции, как исключения, не могут эффективно использоваться в такой среде.
+
Подход vibe.d заключается в использовании асинхронного ввода-вывода под оболочкой, но в то же время кажется, что все операции были синхронными и блокирующими, как и обычные операции ввода-вывода.
+
Это делает возможным поддержку для так называемых волокон (также часто называемых совместными подпрограммами). Волокна ведут себя как потоки, просто они фактически работают в одном потоке. Как только бегущее волокно вызывает специальную функцию yield(), она возвращает управление функции, которая запустила волокно. Затем волокно может быть возобновлено в точно таком же положении и с тем же состоянием, которое было у него при вызове yield(). Таким образом, волокна могут мультиплексироваться вместе, выполняться квазипараллельно и максимально использовать каждую емкость нитей.
+
Все это обычно скрыто за функциями API vibe.d, так что все кажется простой работой с обычными потоками и блокировкой операций. Все блокирующие функции, такие как sleep() или read(), останавливают работу, когда им необходимо ждать, и возобновляют её при возникновении события.
+
Используя эти инструменты, основанные на событиях, характер AIO полностью скрыт от пользователя библиотеки. Он также прекрасно сочетается со встроенной поддержкой многопоточности. Все параллельные операции выполняются с использованием так называемых задач. Каждая задача выполняется внутри одного волокна и мультиплексируется вместе с другими задачами, которые выполняются одновременно. Пользователю инструментария обычно нет видимой разницы между задачей и потоком.
+
Сказав все это, vibe.d может также использоваться без волокон и без цикла обработки событий, если это необходимо, наподобие стандартной блокирующей модели ввода-вывода.
+
Компактное API
+
Акцент делается на короткий и простой API. Общие задачи выполняются как можно короче и на высоком уровне, но при этом, при необходимости, допускается низкоуровневый контроль. Используя некоторые из продвинутых функций D, типичные программы на основе vibe.d становятся лаконичными, что обычно могут предложить только скриптовые языки, такие как Ruby.
+
Нулевое время простоя при изменениях
+
Встроенный балансировщик нагрузки, способный динамически создавать, запускать и тестировать новые процессы после того, как код был изменен, прежде чем переключать их в главный поток. Это позволяет осуществлять «бесшовные» и с низким уровнем риска изменения в работающих системах.
+
Обработка ошибок на основе исключений
+
Обычно обработка исключений ограничивается локальными обработчиками ошибок в средах, основанных на событиях, так как невозможно поместить последовательность событий в блок try-catch, потому что каждая операция создает новую область, когда задействованы обратные вызовы. С другой стороны, vibe.d с его волоконно-ориентированным подходом обладает полной поддержкой обработки исключений.
+
Волокно ведет себя почти так же, как поток относительно стека: один согласованный стек вызовов существует во всех событиях, которые обрабатываются последовательно. Таким образом, становится возможно естественным образом использовать обработку исключений, и особенно в среде веб-служб, где исключения являются идеальной формой обработки ошибок.
+
Исключения имеют чрезвычайно полезную функцию, которую едва можно игнорировать. Таким образом, становится гораздо труднее создать трудноотлавливаемые ошибки и дыры в безопасности, непреднамеренно игнорируя условия ошибки. Любые неперехваченные исключения автоматически генерируют страницу ошибок и записывают всю полезную информацию в случае HTTP-сервисов.
+
Преимущества
+
Полностью интегрированный веб-фреймворк
+
Библиотека vibe.d содержит полный набор инструментов, необходимых для разработки веб-сайтов и веб-сервисов. В дополнение к HTTP 1.0/1.1 серверу уже интегрированы статические файлы, эффективная система шаблонов, веб-сокеты, сеансы и другие функции. К числу таких функций относятся фильтр markdown, драйверы MongoDB и Redis, криптография, поддержка JSON и BSON и простой SMTP-клиент.
+
Есть также средства для автоматической генерации JSON / REST или HTML-интерфейсов на основе форм из классов D, что устраняет много работы и потенциальных ошибок из-за избежания стандартного кода. Генератор интерфейса REST поддерживает генерацию как сервера, так и клиентской части, и как таковой может использоваться как удобный механизм RPC.
+
Встроенные драйверы баз данных
+
Основная библиотека содержит встроенную поддержку баз данных MongoDB и Redis. Эти драйверы по умолчанию обеспечивают быстрое и гибкое хранение данных. Дополнительные драйверы базы данных доступны в реестре пакетов DUB, например, совместимый с vibe.d драйвер MySQL.
+
Совместимость существующих драйверов легко сделать благодаря блокирующей природе API vibe.d. Единственное, что нужно сделать в большинстве случаев – заменить вызовы сокетов (send (), recv (), connect () и т. д.) соответствующими функциями vibe.d. В блоге дается обзор того, что нужно сделать, используя MySQL в качестве примера.
+
«Сырая» сеть и обработка файлов
+
Конечно, «сырые» (необработанные) TCP/UDP и доступ к файлам поддерживаются набором инструментальных средств для включения пользовательских протоколов и форматов файлов. I/O происходит через интерфейс блокирующего потока, который эффективно скрывает тот факт, что базовые операции фактически основаны на событиях.
+
Общие инструменты параллелизма
+
Помимо операций ввода-вывода поддерживаются все обычные инструменты для общих задач программирования:
+
+
Sleep() – приостанавливает выполнение текущих задач в течение определенного времени
+
Таймеры позволяют асинхронное планирование обратных вызовов
+
Мьютексы и условные переменные позволяют осуществлять совместный доступ к данным между несколькими потоками без вмешательства в цикл обработки событий
+
Поддержка передачи сообщений
+
Каналы данных для потоковой передачи данных между задачами и потоками
+
+
Интеграция графического интерфейса пользователя
+
В отличие от большинства других сред, поддерживающих асинхронный ввод-вывод, vibe.d полностью интегрируется с циклом событий пользовательского интерфейса, поэтому его можно использовать для реализации приложений с графическим интерфейсом пользователя.
+
Для Windows существует собственная реализация драйвера событий (включается с VibeWin32Driver), которая использует функцию MsgWaitForMultipleObjectsEx для обработки оконных сообщений вместе с событиями ввода/вывода или параллелизма. Для систем, работающих под управлением X11, можно использовать createFileDescriptorEvent для прослушивания связи дисплея вместо использования XNextEvent.
+
Производительность
+
Асинхронные операции ввода-вывода
+
Вместо использования классического блокирующего ввода-вывода и многопоточности для выполнения параллельных сетевых и файловых операций все операции используют асинхронные API-интерфейсы операционной системы. По умолчанию libevent используется для доступа к этому API операционной системы независимо.
+
Использование асинхронного ввода-вывода имеет ряд преимуществ, главным из которых является то, что накладные расходы памяти намного ниже. Это связано с тем, что для обработки произвольного количества одновременных операций необходим только один аппаратный поток. Поток обычно остается в ожидании событий и разбужен операционной системой сразу же после поступления новых данных, установления нового соединения или возникновения ошибки. После каждой инициированной операции блокировки (например, записи данных в сокет) поток вернется в спящий режим и позволит операционной системе выполнить операцию в фоновом режиме.
+
Другим важным аспектом для скорости является то, что, поскольку требуется только один или несколько потоков, часто можно сохранить много дорогих контекстных переключателей потока. Однако, если приложение должно выполнять много вычислений помимо операций ввода-вывода, vibe.d имеет полную поддержку многопоточности, чтобы полностью использовать многоядерный процессор системы.
+
Поскольку использование модели на основе асинхронных событий часто больше применяется для реализации приложений, волокна используются вместе с планировщиком на основе событий, чтобы создать впечатление классических вызовов блокировки и многопоточности, тем самым скрывая дополнительные сложности и сохраняя при этом эксплуатационные характеристики асинхронности ввода-выводы.
+
Поддержка многопоточности
+
Хотя производительность, как правило, очень высока в однопоточном приложении из-за использования асинхронных операций ввода-вывода и волокон, есть приложения, которые могут извлечь большую пользу из использования нескольких ядер. Vibe.d поддерживает несколько способов использования этой дополнительной вычислительной мощности, оставляя решение по архитектуре потоков программисту.
+
Помимо разрешения использовать потоков D низкого уровня, предоставляется пул потоков, который используется для любой задачи, запущенной с помощью runWorkerTask вместо runTask. Это в основном полезно для выполнения вычислительно дорогостоящих операций, таких как декодирование изображений, наряду с обычным потоком программ, но оно также может быть использовано для лучшей производительности тяжелых задач ввода-вывода в некоторых случаях.
+
Библиотека очень гибкая в том, что многопоточность может быть использована, и она гарантирует, что не могут возникнуть условия «низкоуровневых гонок», если не используются небезопасные операции, такие как cast () или __gshared переменные. В следующем списке показаны некоторые типичные архитектуры потоков:
+
+
Распределенная обработка входящих соединений
+
+
HTTP-серверу (а также любому другому серверу на базе TCP) можно поручить обработку входящих соединений по рабочим потокам пула потоков, а не по основному потоку. Для приложений, которым не требуется разделять состояние между различными соединениями в этом процессе, это может увеличить линейное число запросов в секунду по количеству ядер в системе. Эта функция активируется с использованием настроек HTTPServerOption.distribute или TCPListenOptions.distribute.
+
+
Использование рабочих задач для вычислений
+
+
Вычислительные дорогостоящие задачи могут быть выгружены из основного потока, выполнив их с помощью runWorkerTask. Любая такая задача будет выполнена в пуле потоков. Этот подход полезен в тех случаях, когда приложение требует выполнения таких дорогостоящих задач, поскольку оно позволяет чистому выполнению операций ввода-вывода оставаться без изменений при большой вычислительной нагрузке. Вероятно, наиболее распространенным примером такой задачи является обработка/декодирование/кодирование изображений.
+
+
Использование простых D-потоков
+
+
Нормальные потоки D также могут использоваться вместе с vibe.d. Это важно, когда используются потоковые примитивы стандартной библиотеки D. Помимо основных потоков D, это std.parallelism и std.concurrency. Обратите внимание, что части стандартной библиотеки D не следует смешивать с функциями ввода-вывода vibe.d, поскольку они блокируют цикл обработки событий. В частности, функции передачи сообщений в std.concurrency_* в настоящее время несовместимы с циклом событий vibe.d и должны быть заменены функциями vibe.core.concurrency.
+
Обратите внимание, что vibe.d также включает в себя экспериментальную библиотеку поддерживающую изолированные и ограниченные ссылки. Это позволяет передавать изменяемые данные между потоками без использования мьютексов или аналогичных средств для синхронизации доступа к данным. Это особенно полезно при передаче данных, используемых в рабочих задачах между рабочим потоком и основным потоком.
+
Встроенный компилятор кода
+
Vibe.d написан на языке программирования D. D – это C-подобный язык, который компилируется с использованием машинного кода с минимальными затратами времени выполнения. Помимо того, что D является быстрым, D предлагает ряд функций, которые позволяют повысить производительность и улучшить читаемость кода, безопасность и удобство использования по сравнению с другими языками, такими как C ++.
+
Некоторые заметные отличия перечислены здесь, но есть много дополнительных вещей, которые выходят за рамки этого текста. Смотрите страницу функций D или книгу Programming in D для более тщательного обзора.
+
+
Шаблоны, миксины иcompile-time функции
+
+
Метопрограммирование в D чрезвычайно эффективно. Шаблоны (сравнимые с шаблонами C ++) поддерживают параметры variadic, а также параметры строк и параметры-псевдонимы (alias) – это функции, которые обеспечивает очень удобные интерфейсы во время компиляции.
+
Мощность языка дает возможность выполненять обычные функций во время компиляции, а также возможность компилировать строку, заданную во время компиляции как код D. Эта возможность похожа на функцию eval () в JavaScript: результат статически компилируется в машинный код (и без последствий безопасности eval ()).
+
Эти функции вместе с возможностью чтения файлов во время компиляции позволили создать мощный синтаксический анализатор шаблонов Diet.
+
+
Сборщик мусора
+
+
Среда выполнения D предлагает встроенную сборку мусора, которая предоставляет некоторые интересные возможности, помимо очевидного преимущества отсутствия необходимости ручного управления памятью и связанного с этим риска утечек памяти и опасных потеряных ссылок.
+
В частности, он позволяет работать с неизменяемыми данными, такими как строки или объекты, на которые можно безопасно ссылаться и передавать между потоками без каких-либо издержек синхронизации. При передаче данных между потоками статически закрепляется, что данные безопасны для ссылок из нескольких потоков. Это позволяет избежать целого класса трудно воспроизводимых и отслеживаемых ошибок, часто встречающихся в многопоточном коде многих других языков.
+
+
Замыкания и лямбда-функции
+
+
Функции, также известные из некоторых скриптовых и функциональных языков, а также в C # и некоторых других – замыкания и лямбда-функции. Они позволяют указывать функции обратного вызова очень компактным и читаемым способом. В свою очередь, они, как правило, оказывают сильное влияние на архитектуру API, так как они могут сделать вычислительно эффективные или безопасные API-интерфейсы действительно переносимыми (или даже приятными) в использовании.
+
+
Свойства
+
+
Свойства – это функции, которые выглядят как поля класса или структуры. Они используются в API для получения логического и интуитивно понятного интерфейса без всякого рода ограничений и дополнительной типизации, необходимой для нормальных вызовов функций.
+
+
Модульная система
+Модульная система в D похожа на ту, что используется в Java. Среди прочего он семантически прозрачно кодирует зависимости между различными модулями (D-файлами). Используя эту информацию, становится возможным создавать целые приложения, просто указывая корневой файл (app.d) в командной строке. Зависимости можно найти рекурсивно. Инструмент rdmd build, включенный в компилятор D, поддерживаемый менеджером пакетов DUB, работает таким образом.
+
Массивы и срезы
+
+
Массивы поддерживают встроенный функциональные возможности выполнения срезов с очень естественным синтаксисом. Совместно со сборщиком мусора они обеспечивают чрезвычайно быструю реализацию синтаксического анализатора строк. Данные операции безопасны (проверяются границы) и легко читаются.
+
+
Краткий и читаемый синтаксис
+
+
Синтаксис в целом очень чистый и по смыслу – особенно в сравнение с его, возможно, самым близким родственником, C ++. Но в этом отношении также не нужно бояться современных скриптовых языков, таких как Ruby и Python. Помимо явной необходимости указывать явный типизации типы могут быть приведены автоматически при помощи оператора auto. Вы обнаружите, что использование auto работает предсказуемо, почти без промахов, и что разработка на D очень эффективна.
+
Компилируемый шаблонизатор “Diet”
+
Vibe.d имеет встроенную поддержку HTML-шаблонов Diet на основе синтаксиса шаблона Pug, известного из node.js, который, в свою очередь, основан на Haml. Эти шаблоны устраняют все синтаксические накладные расходы, которые присущи нотации HTML-тегов, а также позволяют вести встроенную спецификацию динамических элементов. Как правило, эти элементы написаны на языке динамических скриптов (JavaScript в случае Pug).
+Однако в vibe.d шаблоны могут содержать встроенный код D. Шаблоны читаются и анализируются, пока приложение компилируется и оптимизируется. Для них создается код на D. Это означает, что накладные расходы времени выполнения для этих шаблонов отсутствуют – не осуществляется доступ к диску, не выполняется синтаксический анализ, и нет необходимости в копировании строк, поскольку все это уже будет сделано до того, как приложение будет запущено.
+В то же время вы можете программировать на том же языке и остальную часть приложения, что обеспечивает очень последовательную разработку.
В течение последних 9 месяцев велась работа над проектом под названием NewCTFE, в котором переписываются методы выполнения функций времени компиляции (СTFE). СTFE считается одной из технологий способных изменить D.
+
Как следует из названия, CTFE позволяет компилятору выполнять некоторые функции, когда он компилирует исходный код, в котором реализованы функции. Пока все аргументы функции доступны во время компиляции, а функция чиста (не имеет побочных эффектов), тогда функция квалифицируется как CTFE, и компилятор заменяет вызов функции результатом.
+
+
Поскольку это неотъемлемая часть языка, чистые функции могут быть вычислены везде, где может находиться константа времени компиляции. Простой пример можно найти в стандартном модуле std.uri, где CTFE используется для вычисления таблицы поиска. Это выглядит так:
Вместо заполнения таблицы магическими значениями используется простой экспрессивный литерал функции. Это намного проще понять и отладить, чем некоторые непрозрачные статические массивы. ({ запускает функцию-литерал, а }) закрывает ее. () в конце говорит компилятору немедленно вызвать этот литерал, чтобы uri_flags стал результатом литерала.
+
Функции выполняются только во время компиляции, если они необходимы. Uri_flags в приведенном выше фрагменте объявляется в области видимости модуля. Когда переменная области видимости модуля инициализируется таким образом, инициализатор должен быть доступен во время компиляции. В этом случае, поскольку инициализатор является функциональным литералом, будет предпринята попытка выполнить CTFE. Этот конкретный литерал не имеет аргументов и является чистым, поэтому попытка выполнена успешно.
+
Более подробное обсуждение CTFE смотрите в статье H. S. Teoh D Wiki.
+
Конечно, подобный метод может быть применен и к более сложным проблемам. Например, std.regex можно использовать со специализированным автоматом для выполнения регулярного выражения во время компиляции с использованием CTFE. Однако, как только std.regex используется с CTFE для нетривиальных паттернов, то время компиляции может стать чрезвычайно длительным (в D все, что занимает больше секунды при компиляции — избыточность :)). В конце концов, по мере усложнения паттернов, у компилятора появится нехватка памяти, и, возможно, произойдёт крах всей системы.
+
Причина этого может крыться в текущей архитектуре интерпретатора CTFE. Это интерпретатор AST (абстрактного синтаксического дерева) — это означает, что он интерпретирует AST во время его обхода. Чтобы представить результат интерпретируемых выражений, он использует классы узлов DMD в AST. Это означает, что на каждое вновь встреченное выражение будет выделено один или несколько узлов AST. В ограниченном цикле интерпретатор может легко создать более 100.000.000 узлов и использовать несколько гигабайт оперативной памяти. Это может быстро израсходовать память.
+
В issue 12844 имеет место проблема, что std.regex занимает более 16 ГБ ОЗУ для одного шаблона. Также есть issue 6498 , которая показывает, что выполняется простой от 0 до 10.000.000 узлов во время выполнения CTFE и что приводит к критичной нехватки памяти.
+
Простое освобождение узлов не устраняет проблему, так мы точно не знаем, какие узлы необходимо освободить, и что cделает весь компилятор очень медленным из-за сборщика мусора. К счастью, есть еще один подход, который не выделяет память для каждого вновь встреченного выражения. Он включает в себя компиляцию функции в виртуальную ISA (архитектуру набора инструкций). Эта виртуальная ISA, также известная как байт-код, затем передается выделенному интерпретатору для этой ISA (в случае, когда виртуальный ISA совпадает с ISA хоста, мы называем его JIT (Just in Time) интерпретатором).
+
Проект NewCTFE занимается реализацией такого интерпретатора байт-кода. Написание фактического интерпретатора (эмулятора CPU для виртуального CPU/ISA) достаточно просто. Однако компиляция кода для виртуального ISA выполняется в точности так же, как и при компиляции его в реальном ISA (хотя виртуальная ISA имеет дополнительное преимущество, которое может быть расширено для индивидуальных потребностей, но это затруднит выполнение JIT позже). Вот почему потребовался всего месяц, чтобы пучить первые простые примеры, работающие на новом движке CTFE, и почему немного более сложные из них все еще не работают даже после 9 месяцев разработки. В конце статьи вы найдете примерный график выполненной к настоящему времени работы (см. оригинал).
+
Я буду выступать с презентацией на DConf 2017, где я расскажу о своем опыте внедрения движка и объясню некоторые технические детали, особенно относительно компромиссов и архитектурных решений, которые я применил. Текущая оценка состоит в том, что версия 1.0 не будет реализована к тому времени, но я буду заниматься разработкой, пока не закончу данный проект.
+
Те, кто хочет отслеживать разработку, могут сделать это на форуме D. В будущем я планирую написать еще одну статью о некоторых технических деталях реализации. К тому времени, я надеюсь, что следующий список поможет пролить свет на то, как много работы по реализации NewCTFE.
+
Данная статья является переводом статьи Штефана Коха, который является разработчиком sqlite-d, встроенного пакета в D для работы с sqlite, также он внес свой вклад в такие проекты, как SDC (Stupid D Compiler) и vibe.d. Он также был ответственен за 10% -ное повышение производительности в текущей реализации CTFE в D и в настоящее время пишет новый движок CTFE.
Я автор этого блога, именуемый в дальнейшем DarkRiDDeR. Мой блог посвящён тематики информационных технологий.
+Это моя первая запись, и я надеюсь, что буду писать полезные и интересные статьи.
+Спасибо за внимание!
Пишем аналог функции PHP preg_match_all на языке программирования D
+
+
+
+
+
В PHP есть очень удобная функция для глобального поиска шаблона регулярного выражения в строке preg_match_all. Давайте напишем аналогичный класс статических методов для реализации этой функции с разными флагами на языке программирования D.
+
Описание функции:
+
+
+
int preg_match_all( string $pattern, string $subject[,array&$matches[, int $flags= PREG_PATTERN_ORDER [, int $offset=0]]])
+
+
+
Функция ищет в строке subject все совпадения с шаблоном pattern и помещает результат в массив matches в порядке, определяемом комбинацией флагов flags.
+После нахождения первого соответствия последующие поиски будут осуществляться не с начала строки, а от конца последнего найденного вхождения.
+
Данная функцию очень удобна и чаще всего она применяется с третьим параметром, чтобы обработать полученный массив совпадений шаблона. В D подобной регулярной функции нет. Мне вообще не сильно нравятся, как реализованы регулярные выражения в D. Ну да ладно.
PREG_PATTERN_ORDER – упорядочивает результаты так, что элемент $matches[0] содержит массив полных вхождений шаблона, элемент $matches[1] содержит массив вхождений первой подмаски, и так далее;
+
PREG_SET_ORDER – упорядочивает результаты так, что элемент $matches[0] содержит первый набор вхождений, элемент $matches[1] содержит второй набор вхождений, и так далее;
+
PREG_OFFSET_CAPTURE – в случае, если этот флаг указан, для каждой найденной подстроки будет указана ее позиция в исходной строке. Необходимо помнить, что этот флаг меняет формат возвращаемого массива matches в массив, каждый элемент которого содержит массив, содержащий в индексе с номером 0 найденную подстроку, а смещение этой подстроки в параметре subject — в индексе 1.
+
+
Не будем заморачиваться с реализацией через передачу константы, как в PHP, или через шаблоны в D. Создадим для каждого флага PHP данной функции аналогичные статические методы. Параметр offset оставим за бортом. Класс давайте назовём PReg. Вырисовывается следующая структура:
Как параметры будем передавать строку для поиска (тип string), регулярное выражение (тип ???) и переменную для вывода количества совпадений шаблона регулярного выражения (тип out int). Тип регулярного выражения можно посмотреть, чтобы не капаться в модуле, применив такую хитрость:
+
writeln(typeof(regex(`\d+`)).stringof);
+
Также как аргумент вы без проблем сможете передавать compile-time регулярное выражение (ctRegex). Для данного типа создадим алиас типа, чтобы поудобнее было.
+Функция matchAllPatternOrder и matchAllSetOrder будет возвращать двумерный массив строк, для них тоже создадим алиас типов (мне так кажется, что путаницы меньше). MatchAllOffsetCapture пока оставим на закуску.
Функция matchAll осуществляет глобальный поиск шаблона регулярного выражения obRegex.
+
Цикл while файл перебирает найденные совпадения пока они не закончатся (проверка с помомощью stdMatches.empty);
+
stdMatches.front хранит строку и найденные подстроки;
+
stdMatches.front.hit возвращает всё строку входящую в найденный шаблон;
+
stdMatches.front[i] возвращает найденные части по позиции маски;
+
stdMatches.popFront() переход к следующей найденной строке.
+
+
Реализация функции matchAllSetOrder по сути ничем сильно не отличается кроме как позициями найденных строк в массиве (она даже проще). Приведу лишь реализованный вариант:
Реализация функции matchAllOffsetCapture имеет свои особенности. Найденные данные функции будем хранить в двумерном массиве картежа типов Tuple!(string, «text», int, «position»), по которому можно будет получить позицию и найденую строку. Реализация:
Позиция определяется через разность указателей позиций элементов массива. Также здесь выполняется приведение типа к int, так как многие процессоры уже использует 64-х битное представление, и указатели будут иметь тип long.
+
Полная реализация модуля с тестами представлена ниже:
Во время проходившего на конференции DConf-2017 хакатона, я самоуверенно возглавил группу из двух человек, хакающих Ди’шный сборщик мусора (GC). После нескольких часов я уже не мог избавиться от навязчивой мысли «эгей, парень, это надо бы переписать!». Так что я решил отправиться в квест в поисках лучшего мусорщика для Ди, где первым шагом стал бы более быстрый, клаcсический сборщик, отмечающий достижимые объекты (mark-sweep).
+
Для пояснения моих мотивов, я намерен описать внутренности современного сборщика, отмечая промахи архитектуры. В конце концов, надо же понять, «куды тыкать»!
+
Пулы, везде пулы!
+
Игнорируя излишние детали, мусорщик — это просто массив объектов пула. Каждый пул — это кусочек отображённой (mmap) памяти + немного метаданных в куче (таблиц маркирующих бит, освобождающих бит ну и так далее). Выделение памяти происходит внутри пула. Если одиночный пул не в состоянии обслужить выделение памяти, заводится новый пул. Размер пула определяется арифметической прогрессией от числа пулов (или 150% от размера выделения, смотря, что окажется больше).
+
Важно, что пулы бывают двух типов, для больших и маленьких объектов. В «маленьких» пулах выделяются объекты размером до 2 Кб, всё остальное обслуживается «большими» пулами. На самом деле, маленькие пулы более интересны, так что давайте на них первым делом и взглянем.
+
+
Прежде всего, размер памяти для любого маленького выделения округляется до подходящего (по степеням двойки) класса размера — 16, 32, 64, 128, 256, 512, 1024, 2048. Затем для данного размера проверяется глобальный список свободных блоков и, если такового найти не получается, продолжается поиск маленького пула.
+
Маленький пул выделит новую страницу памяти и внесёт её в список свободных блоков данного размера. Вот и «вылезла» первая большая ошибка существующей архитектуры: класс размера назначается на страничной основе, поэтому нам требуется таблица (чтобы жизнь мёдом не казалась, называемая таблицей страниц), ставящая в соответствие каждому классу размера соответствующую страницу. Теперь, чтобы найти начало объекта по внутреннему указателю, мы сперва ищем страницу, к которой он принадлежит, затем ищем класс размера и, наконец, накладываем битовую маску. Более того, метаданные представляют собой кучу простых битовых таблиц, которые теперь должны покрывать страницы разного размера, поэтому на каждые 16 байт требуется примерно 7 бит независимо от размера объекта.
+
Чем была обусловлена эта архитектура? У меня на этот счёт есть две гипотезы. Первая связана с нежеланием резервировать память для недоиспользуемых пулов (что, на самом деле, не является проблемой, так как для виртуальной памяти работает ленивая фиксация). Вторая — с опасениями получить слишком много пулов, замедлив выделение и полезную маркировку. Последнее больше похоже на причину, так как во время фазы маркировки, мусорщик действительно довольно часто производит линейное сканирование по пулам и бинарный поиск для каждого предполагаемого указателя (!).
+
Вот и вторая ошибка: поиск пула за log(P), где P — число пулов, и соответственно, отметка за N*log(P). Хэш–таблица могла бы малость сэкономить циклы.
+
Завершая наш обзор маленького пула, мы также должны взглянуть на выбор классов размеров. Это третья погрешность (не ошибка, скорее, спорный выбор): размеры, следующие степеням двойки, гарантируют нам внутреннюю фрагментацию, доходящую до 50 %. Современные выделители, подобные jemalloc’у, обычно предлагают ещё один класс, размер которого лежит между степеням двойки. Деление по модулю на константу, не являющуюся степенью двойки, несколько медленнее одиночного битового, но и вполне приемлемо.
+
+
Давайте взглянем на пулы больших объектов. Первое, что нужно заметить, так это гранулярность страницы памяти (4 КБ) как для метаданных, так и собственно выделений памяти. Наборы свободных страниц внесены в один список, который линейно сканируется при каждом запросе на выделение памяти. Это четвёртая ошибка, которая, впрочем, не оказывает влияния на производительность выделения больших объектов. Для поиска начала объекта организована отдельная таблица, в которой для каждой страницы хранится индекс начала объекта, к которой он принадлежит.
+
Схема разумна до тех пор, пока не коснётся больших (более 100 МБ) выделений памяти. В этом случае, скорее всего, не удастся перераспределить память «по месту», в результате чего будет выделен новый пул и огромный объём памяти метаданных будет истрачен на всего один объект.
+
Процесс сбора
+
До сих пор мы наблюдали конвейер выделения памяти, освобождение проходит примерно также. Более интересен автоматический возврат памяти, который и является смыслом сборщика мусора. Прежде всего позвольте мне отметить очевидное: во первых, сборщик мусора в Ди является консервативным, то есть, он не знает, является ли что-то указателем или нет. Во-вторых, он поддерживает финализаторы — действия, которые выполняются на объекте, прежде чем возвратить его память в общий пул. Эти два решения сильно ограничивают архитектуру сборщика.
+
С точки зрения высокого уровня, процесс сборки, как ни странно, представляет собой целостный 4-фазный процесс: подготовка — полная маркировка – подчистка — возврат памяти.
+
Стадия подготовки даёт наибольшие основания для сомнений. В сущности, для предотвращения сканирования свободной памяти, на этой стадии следовало бы скопировать биты–признаки свободных блоков в биты–признаки отметок. Однако всю малину портит то, что требуется вычислить полное свободное место, для чего перебрать списки свободных блоков. Это уже пятая(хм?) ошибка, потому что резкое распутывание бессчётного количества указателей — явно последнее, что нужно сделать во время «приостановки мира». Лучшей архитектурой было бы переворачивание битов–признаков свободных блоков во время выделения / освобождения памяти, тем более, что список свободных блоков поддерживает указатели на пул для каждого объекта, так что искать нужный пул не потребуется.
+
Фаза маркировки сводится, на самом деле, к вызову MarkAll, который просто передаёт подходящие участки памяти в маркировочную функцию, заслуживающую более пристального рассмотрения.
+
+
Прежде всего для каждого указателя в области памяти проверяется, попадает ли он в адресный диапазон кучи сборщика (от наименьшего до наибольшего адреса в пуле).
+
Затем для поиска правильного пула для данного указателя, применяется «кошмарный» бинарный поиск.
+
Независимо от типа пула, производится поиск в таблице страниц текущего пула для того, чтобы определить его класс размера, либо понять, что это большой объект или даже свободная память, которая вовсе не проверяется. Тут есть небольшая оптимизация: в итоге этого поиска становится ясно, с чем имеем дело: с началом большого объекта или продолжением. У нас есть 3 случая: маленький объект, начало большого объекта, либо продолжение большого объекта. Последние случаи идентичны, за исключением всего одного дополни- тельного поиска в таблице.
+
Определяется начало объекта, для этого накладывается правильная битовая маска, а также, в случае продолжения большого объекта, просматривается таблица смещений.
+
Заметим, что для случая большого объекта имеется специальный бит — признак «без внутреннего указателя», что позволяет игнорировать внутренние указатели на объект.
+
И наконец, проверяются и устанавливаются биты отметок, которые не были установлены раньше, или «noscan-биты» — биты-признаки «не сканировать» — добавляются в стек памяти сканирования.
+
+
Собственно, это всё, что нужно сказать о функции пометки, не считая забавных манипуляций с ограничением на стек (для того, чтобы избежать переполнения стека всё ещё пытаемся использовать выделение стека).
+
Упомянутый ранее поиск пула — далеко не единственный недостаток. Имеющее место смешение несканируемой памяти (без указателей) и нормальной памяти в одном и том же пуле, приводит к необходимости дополнительного просмотра битовой таблицы. А ведь если бы мы разделили пулы по классам размеров, можно было бы с лёгкостью избежать просмотра таблицы страниц. Не стоит даже упоминать сомнительную оптимизацию, касающуюся бита–признака «без внутреннего указателя», которая мало того, что делает код небезопасным (объект может быть сметён в мусор, хотя на него всё ещё ссылаются), но ещё и вводит несколько дополнительных проверок по критическому пути для всех больших объектов, включая возможный просмотр битовой таблицы.
+
Уф, весьма запутанно. Однако, стоит иметь в виду, что фаза отметки — это воистину сердце любого сборщика.
+
Перейдём теперь к третье фазе — очистки. Ирония в том, что вопреки ожиданиям, в текущем Ди’шном сборщике очиститель вовсе не очищает списки свободных блоков. Всё, что его волнует, так это вызвать финализаторы, если таковые имеются, и установить биты–признаки «свободен» и прочие таблицы. Заметьте, что это требует поиска битов–отметок и соответственно, линейного прохода по памяти каждого пула.
+
Последняя стадия — возврат освобождённой памяти. На самом деле, на этой стадии перестраиваются списки свободных блоков. и опять это линейный проход по (всем) пулам, но только по маленьким пулам. И опять нужен просмотр таблицы страниц для каждой страницы в пуле. И только для того, чтобы определить её размер. . . определённо, хочется плакать! Основной вопрос без ответа — зачем? Зачем лишний проход? Я долго пытался представить разумную причину, но так и не смог.
+
Возможно, слабое, но вполне возможное объяснение — «для простоты». По моему мнению, это последняя большая ошибка.
+
Чего же там нет?
+
До сих пор я критиковал то, что бросается в глаза. Пора перейти к тому, что попросту отсутствует.
+
Кэш нитей — одно из таких больших упущений. Правда, следует помнить, что Ди’шный мусорщик родом из 2000–ых, так что это не удивительно. В любом современном распределителе есть хоть какая-то форма кэша нитей, некоторые даже пытаются поддерживать кэш для каждого процессора. Кэш работает для каждого потока, выделяя память скопом и придерживая сделанные выделения памяти на будущее. Такой подход уменьшает стоимость просмотра разделяемых структур данных кучи. Точнее говоря, мелкозернистые блокировки имеются, но не на уровне всего пула.
+
Другой пример современного подхода, безусловно ожидаемого в любом мусорщике, это параллельная отметка. Весьма популярны параллельные (или квази–паралелльные) сборщики, в которых отметка и гораздо более редкая очистка и компактификация (операция, которая преобразует топологические пространства в компактные) производятся во время выполнения нитей приложения.
+
Заключительные размышления
+
Это сообщение получилось гораздо длиннее и более подробное, чем бы мне хотелось. Тем не менее, сохраняется его главный посыл: Ди’шный мусорщик медленный не из-за каких–то фундаментальных ограничений, а просто потому, что почти половина решений в его реализации откровенно плоха. Действуя в том же духе легко можно было бы построить медленный и точный «поколенческий» мусорщик, просто из-за отсутствия хороших методик реализации.
+
Подводя итог, что пытается изменить моя первая попытка:
+
+
Разделить маленькие пулы по классам размеров.
+
Использовать поиск в пуле с эффективностью O(1).
+
Чтобы избавиться от внутренней фрагментации, попробовать использовать больше классов размеров, в том числе, не кратных степеням двойки (а-ля jmalloc).
+
Упростить маркировку, разделив все пулы по атрибуту «не сканировать».
+
Ввести третий класс пулов для массивных выделений памяти (более 16 МБ), предназначенных исключительно для одиночных объектов.
+
Пулы больших объектов требуют более хитрой работы. Возможно, деревья с ключами на основе длины блока придутся кстати (jemalloc использует красно–чёрные деревья).
+
Надо бы убрать атрибут „без внутреннего указателя“. В текущей реализации он предназначен для борьбы с ложными указателями, что характерно для консервативного мусорщика. Однако это принципиально небезопасно и цена слишком высока. В конце концов, это полностью бессмысленно в 64-битных системах, где собственно и живут ваши серверы.
+
Не нужно «юродство» с многофазной сборкой в цикле „отметка – очистка“. Он должен отмечать и очищать, только и всего.
+
Добиться мелкогранулированной блокировки с самого начала. Я не вижу проблем с блокировками на уровне пула.
+
+
Вторая итерация моих усилий будет сосредоточена на более вкусных вещах: кэш потока, параллельная маркировка и одновременная маркировка, использующая трюк с разветвлением (fork).
+
На третьей итерации (если доживём), ожидаем совершенно новый дизайн, вдохновлённый коллегой immix1 — сборщик, основанный на отметки областей.
+
На этой оптимистичной ноте я завершаю озвучивание моих планов. Предупреждаю, что собираюсь начать реализацию в Линукс–специфике, медленно доводя её до совместимости с POSIX. Поддержка Windows — отдалённая возможность.
Вирус. Самопроизвольный запуск браузера и перенаправление на вредоносные сайты.
+
+
+
+
+
Недавно столкнулся с такой проблемой: браузер через приблизительно одинаковые промежутки времени сам запускался и открывал различные рекламные и вредоносные сайты.
+
+
«О! Нет! Это вирус!» – воскликнули с ужасом в сердцах.
+
Все мы напуганы зловредами, которые могут нанести ощутимый вред, особенно на фоне недавней атаки вируса шифровальщика WannaCry, который широко разгулялся и нанёс принёс ощутимые убытки большому числу компаний и организаций. Но в нашем случае всё не так страшно.
+
Данный вирус практически никакой угрозы не представляет, он даже вирус в кавычках. Основной его вред в том, что по большему счёту лишь надоедает и отвлекает. Сидишь ли делаешь работу, или может отдыхаешь, смотришь любимый сериал, и постоянно запускается браузер с каким-то левым сайтом, на котором находится нелицеприятный контент. Это начинает довольно сильно мешать.
+
После чего уже начинаешь задумываться. А какого фига данный вирус попал ко мне на компьютер? Как его удалить? Основная причина попадания таких вирусов – это установка какого-либо пиратского контента. Но бог с ним, как он к нам попал. Теперь его как-то надо удалять.
+
Мы сначала запускаем свой любимый установленный на нашем компьютере антивирус. У меня лично стоит ESET NOD32 Smart Security (рекомендую). Но сканирование ничего не даёт. Что же делать? Порывшись в закоулках ОС Windows я нашёл причину этой проблемы. Это планировщик заданий, в котором было указано задание на запуск браузера с последующим переходом на зловредный сайт.
+
Чтобы попасть в планировщик заданий Windows запустите командную строку набором клавишь Win+R и введите команду taskschd.msc, которая и запустит его.
+
+
Просмотрев команды планировщика можно легко найти ту, которая запускает наш браузер (у меня Firefox).
+
+
В задании видно, на какой сайт идёт перенаправление.
+
Это по сути своей и не вирус – это лишь задание на запуск браузера с последующим перенаправлением, поэтому и антивирус прошёл мимо, не обратив внимания. Хотя добавить в антивирус подобного рода проверку было бы неплохо.
+
Нещадно удаляем это задание. После чего проблема с самопроизвольным запуском браузера и последующим перенаправлением на вредоносные сайта решена.
+
В данной статье описан один из возможных способов решения данной проблемы. Возможно в вашем случае имеет место та же проблема, и я надеюсь, что помог вам.
В PHP есть очень удобная функция для глобального поиска шаблона регулярного выражения в строке preg_match_all. Давайте напишем аналогичный класс статических методов для реализации этой функции с разными флагами на языке программирования D.
В течение последних 9 месяцев велась работа над проектом под названием NewCTFE, в котором переписываются методы выполнения функций времени компиляции (СTFE). СTFE считается одной из технологий способных изменить D. Как следует из названия, CTFE позволяет компилятору выполнять некоторые функции, когда он компилирует исходный код, в котором реализованы функции. Пока все аргументы
Простота Модель программирования псевдоблокировки на основе волокн Основная идея vibe.d заключалась в том, чтобы использовать быструю и ресурсоемкую асинхронную модель ввода-вывода (AIO) и сделать ее удобной в использовании. Некоторые другие программные платформы, такие как node.js, напрямую отображают интерфейс AIO с использованием событий, используя функции обратного вызова. Хотя это приемлемый подход,
Недавно столкнулся с такой проблемой: браузер через приблизительно одинаковые промежутки времени сам запускался и открывал различные рекламные и вредоносные сайты.
Существуют проблемы совместимости с 32-x битными файлами DMD в Windows x64, так как они скомпилированы с использованием DMC фоновых программ, которые могут производить только OMF двоичные файлы. Поэтому для того, чтобы избежать проблем с подключением к внешним скомпилированным библиотекам, гораздо легче придерживаться использования 64-разрядных двоичных файлов. Это можно осуществить использованием
Я автор этого блога, именуемый в дальнейшем DarkRiDDeR. Мой блог посвящён тематики информационных технологий. Это моя первая запись, и я надеюсь, что буду писать полезные и интересные статьи. Спасибо за внимание!
Bitrix API. Функция для генерации кода элемента из имени через транслит
+
+
+
+
+
Часто в Bitrix необходимо сгенерировать код элемента из имени.
+Привожу пример реализации именно такой функции с помощью функции Bitrix API для транслита CUtil::translit:
Компиляция 64-x разрядных программ на DMD под Windows x64
+
+
+
+
+
Существуют проблемы совместимости с 32-x битными файлами DMD в Windows x64, так как они скомпилированы с использованием DMC фоновых программ, которые могут производить только OMF двоичные файлы. Поэтому для того, чтобы избежать проблем с подключением к внешним скомпилированным библиотекам, гораздо легче придерживаться использования 64-разрядных двоичных файлов. Это можно осуществить использованием Visual Studio компоновщика для DMD, который будет создавать совместимые COFF двоичный файлы. Еще одна проблема в том, что 32-битные DMD двоичные файлы связаны с устаревшими 32-битными библиотека WinAPI, в которых отсутствуют некоторые очень важные функции, в то время как 64-разрядные двоичные файлы должны быть связаны с 64-битными библиотеками, поставляемыми в SDK Windows. Решим эту проблему.
Директория установки Windows SDK в Windows 7 по умолчанию — C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\. Создадим системную переменную VCINSTALLDIR с данным адресом директории.
+
Далее нам будет предложено выбрать устанавливаемые средства разработки, нам важны только 64-x разрядные библиотеки и компилятор Visual Studio, выберем данные пункты.
+
Далее создадим ещё одну системную переменную DEV_DIR_WINSDK, в которой будет храниться путь к Windows SDK. В моё случае это C:\Program Files\Microsoft SDKs\Windows\v7.1\.
+
Теперь необходимо отредактировать файл конфигурации компилятора DMD, он находится по пути dmd2\windows\bin\sc.ini. Файл разбит на разделы, которые отмечены квадратными скобками, на потребуется изменить данные в разделе Environment64:
+
+
Изменим значение параметра LINKCMD на %VCINSTALLDIR%\bin\amd64\link.exe
+
Раскомментируем строку WindowsSdkDir= и приравняем к %DEV_DIR_WINSDK%
+
Далее необходимо закомментировать (символ «;») строки с параметром LIB, в которых прописаны пути к Wimdows SDK не для вашей платформы.
+
+
На этом настройка завершена, попробуем скомпилировать проект (запись блога ), открываем командную строку, пишем:
+
rdmd -m64 C:\D\projects\test\hello.d
+
Если всё прошло удачно, будет выведено «Hello, World!». Поздравляю, теперь вы можете компилировать 64-х разрядные приложения на D для Windows.
+ The site configured at this address does not
+ contain the requested file.
+
+
+
+ If this is your site, make sure that the filename case matches the URL
+ as well as any file permissions.
+ For root URLs (like http://example.com/) you must provide an
+ index.html file.
+
+
+
diff --git a/docs/rebuild-v2/raw/media/d165b88b6844e04a7ae1.bin b/docs/rebuild-v2/raw/media/d165b88b6844e04a7ae1.bin
new file mode 100644
index 0000000..5b10050
--- /dev/null
+++ b/docs/rebuild-v2/raw/media/d165b88b6844e04a7ae1.bin
@@ -0,0 +1,89 @@
+
+
+
+
+
+ Page not found · GitHub Pages
+
+
+
+
+
+
+
404
+
File not found
+
+
+ The site configured at this address does not
+ contain the requested file.
+
+
+
+ If this is your site, make sure that the filename case matches the URL
+ as well as any file permissions.
+ For root URLs (like http://example.com/) you must provide an
+ index.html file.
+
Duration: 50 minutes
+ Talk type: Presentation
+ Level: Beginner to Intermediate
+
+ Slides:PDF · PPTX
+ Video
+
+
+
+
Abstract:
+
D is an ideal language to use for building GTK applications. This talk will explore why it is a good fit in comparison to other languages based on the experience of the speaker writing Tilix, a popular terminal emulator for Gnome.
+
+
When writing GTK applications there is currently a gap between compiled languages, which are often low productivity and difficult to learn, and scripting languages which are easier to learn but lack performance, static typing and other features that developers often prefer.
+
+
Vala was intended by GNOME to fill this gap but it is not well maintained and it's future looks bleak. In my opinion D is a perfect replacement for Vala as it occupies a unique sweet spot for building GUI applications and, in particular, GTK Linux applications.
+
+
This talk will focus on the following topics:
+
Yes Matilda, desktop GUI applications are still relevant today
+
What is GTK in a single slide
+
Surveying the current options for building GTK applications (C, C++, Python, Javascript, Vala and Rust)
+
Why choose D over other options?
+
Summary of experience writing Tilix including:
+
How D makes Tilix better
+
Best practices for writing D GTK applications
+
Lessons learned
+
+
+
The future and a call to action
+
+
+
Speaker Bio:
+
Gerald Nunn is a Senior Middleware Solutions Architect with Red Hat. While his day job has nothing to do with the desktop, GTK or GNOME, he maintains a passion for building GUI applications. His current hobby project is Tilix, a popular tiling terminal emulator for GNOME.
If curl was built with Schannel support, then curl uses the Windows native CA store for verification. On Apple operating systems, it is possible to use Apple's "SecTrust" services for certain TLS backends, details below. All other TLS libraries use a file based CA store by default.
+
Verification
+
Every trusted server certificate is digitally signed by a Certificate Authority, a CA.
+
In your local CA store you have a collection of certificates from trusted certificate authorities that TLS clients like curl use to verify servers.
+
curl does certificate verification by default. This is done by verifying the signature and making sure the certificate was crafted for the server name provided in the URL.
+
If you communicate with HTTPS, FTPS or other TLS-using servers using certificates signed by a CA whose certificate is present in the store, you can be sure that the remote server really is the one it claims to be.
+
If the remote server uses a self-signed certificate, if you do not install a CA cert store, if the server uses a certificate signed by a CA that is not included in the store you use or if the remote host is an impostor impersonating your favorite site, the certificate check fails and reports an
+error.
+
If you think it wrongly failed the verification, consider one of the following sections.
+
Skip verification
+
Tell curl to not verify the peer with -k/--insecure.
+
We strongly recommend this is avoided and that even if you end up doing this for experimentation or development, never skip verification in production.
+
Use a custom CA store
+
Get a CA certificate that can verify the remote server and use the proper option to point out this CA cert for verification when connecting - for this specific transfer only.
+
With the curl command line tool: --cacert [file]
+
If you use the curl command line tool without a native CA store, then you can specify your own CA cert file by setting the environment variable CURL_CA_BUNDLE to the path of your choice. SSL_CERT_FILE and SSL_CERT_DIR are also supported.
+
If you are using the curl command line tool on Windows, curl searches for a CA cert file named curl-ca-bundle.crt in these directories and in this order:
+
+
application's directory
+
current working directory
+
Windows System directory (e.g. C:\Windows\System32)
+
Windows Directory (e.g. C:\Windows)
+
all directories along %PATH%
+
+
curl 8.11.0 added a build-time option to disable this search behavior, and another option to restrict search to the application's directory.
+
curl 8.19.0 added a build-time option to enable Native CA by default on Windows. This build-time option by default also disables searching for a curl-ca-bundle.crt on disk.
+
Use the native store
+
In several environments, in particular on Microsoft and Apple operating systems, you can ask curl to use the system's native CA store when verifying the certificate. Depending on how curl was built, this may already be the default.
+
With the curl command line tool: --ca-native.
+
Modify the CA store
+
Add the CA cert for your server to the existing default CA certificate store.
+
Usually you can figure out the path to the local CA store by looking at the verbose output that curl -v shows when you connect to an HTTPS site.
+
Change curl's default CA store
+
The default CA certificate store curl uses is set at build time. When you build curl you can point out your preferred path.
+
Extract CA cert from a server
+
curl -w %{certs} https://example.com > cacert.pem
+
The certificate has BEGIN CERTIFICATE and END CERTIFICATE markers.
+
Get the Mozilla CA store
+
Download a version of the Firefox CA store converted to PEM format on the CA Extract page. It always features the latest Firefox bundle.
+
Native CA store
+
Windows + Schannel
+
If curl was built with Schannel, then curl uses the certificates that are built into the OS. These are the same certificates that appear in the Internet Options control panel (under Windows). Any custom security rules for certificates are honored.
+
Schannel runs CRL checks on certificates unless peer verification is disabled.
+
Apple + OpenSSL/GnuTLS
+
When curl is built with Apple SecTrust enabled and uses an OpenSSL compatible TLS backend or GnuTLS, the default verification is handled by that Apple service. As in:
+
curl https://example.com
+
You may still provide your own certificates on the command line, such as:
+
curl --cacert mycerts.pem https://example.com
+
In this situation, Apple SecTrust is not used and verification is done only with the trust anchors found in mycerts.pem. If you want both Apple SecTrust and your own file to be considered, use:
How well the use of native CA stores work in all other combinations depends on the TLS backend and the OS. Many TLS backends offer functionality to access the native CA on a range of operating systems. Some provide this only on specific configurations.
+
Specific support in curl exists for Windows and OpenSSL compatible TLS backends. It tries to load the certificates from the Windows "CA" and "ROOT" stores for transfers requesting the native CA. Due to Window's delayed population of those stores, this might not always find all certificates.
+
HTTPS proxy
+
curl can do HTTPS to the proxy separately from the connection to the server. This TLS connection is handled and verified separately from the server connection so instead of --insecure and --cacert to control the certificate verification, you use
+--proxy-insecure and --proxy-cacert. With these options, you make sure that the TLS connection and the trust of the proxy can be kept totally separate from the TLS connection to the server.
The JSON.parse() static method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.
If a function, this prescribes how each value originally produced by parsing is transformed before being returned. Non-callable values are ignored. The function is called with the following arguments:
The original JSON string representing this value. This property is only present when reviving primitive values, but not when value is an object or array.
JSON.parse() parses a JSON string according to the JSON grammar, then evaluates the string as if it's a JavaScript expression. The only instance where a piece of JSON text represents a different value from the same JavaScript expression is when dealing with the "__proto__" key — see Object literal syntax vs. JSON.
If a reviver is specified, the value computed by parsing is transformed before being returned. Specifically, the computed value and all its properties (in a depth-first fashion, beginning with the most nested properties and proceeding to the original value itself) are individually run through the reviver.
+
The reviver is called with the object containing the property being processed as this (unless you define the reviver as an arrow function, in which case there's no separate this binding) and three arguments: key, value, and context. The key is a string even for arrays. For primitive values, the context argument has a field called source containing the source text of this value. If the reviver function returns undefined (or returns no value — for example, if execution falls off the end of the function), the property is deleted from the object. Otherwise, the property is redefined to be the return value. If the reviver only transforms some values and not others, be certain to return all untransformed values as-is — otherwise, they will be deleted from the resulting object.
+
Similar to the replacer parameter of JSON.stringify(), for arrays and objects, reviver will be last called on the root value with an empty string as the key and the root object as the value. For other valid JSON values, reviver works similarly and is called once with an empty string as the key and the value itself as the value.
+
If you return another value from reviver, that value will completely replace the originally parsed value. This even applies to the root value. For example:
There is no way to work around this generically. You cannot specially handle the case where key is an empty string, because JSON objects can also contain keys that are empty strings. You need to know very precisely what kind of transformation is needed for each key when implementing the reviver.
+
Note that reviver is run after the value is parsed. So, for example, numbers in JSON text will have already been converted to JavaScript numbers, and may lose precision in the process. One way to transfer large numbers without loss of precision is to serialize them as strings, and revive them to BigInts, or other appropriate arbitrary precision formats.
+
You can also use the context.source property to access the original JSON source text representing the value, as shown below:
+
js
const bigJSON = '{"gross_gdp": 12345678901234567890}';
+const bigObj = JSON.parse(bigJSON, (key, value, context) => {
+ if (key === "gross_gdp") {
+ // Ignore the value because it has already lost precision
+ return BigInt(context.source);
+ }
+ return value;
+});
+
In order for a value to properly round-trip (that is, it gets deserialized to the same original object), the serialization process must preserve the type information. For example, you can use the replacer parameter of JSON.stringify() for this purpose:
+
js
// Maps are normally serialized as objects with no properties.
+// We can use the replacer to specify the entries to be serialized.
+const map = new Map([
+ [1, "one"],
+ [2, "two"],
+ [3, "three"],
+]);
+
+const jsonText = JSON.stringify(map, (key, value) =>
+ value instanceof Map ? Array.from(value.entries()) : value,
+);
+
+console.log(jsonText);
+// [[1,"one"],[2,"two"],[3,"three"]]
+
+const map2 = JSON.parse(jsonText, (key, value) =>
+ Array.isArray(value) && value.every(Array.isArray) ? new Map(value) : value,
+);
+
+console.log(map2);
+// Map { 1 => "one", 2 => "two", 3 => "three" }
+
+
Because JSON has no syntax space for annotating type metadata, in order to revive values that are not plain objects, you have to consider one of the following:
+
+
Serialize the entire object to a string and prefix it with a type tag.
+
"Guess" based on the structure of the data (for example, an array of two-member arrays)
+
If the shape of the payload is fixed, based on the property name (for example, all properties called registry hold Map objects).
JSON.parse("[1, 2, 3, 4, ]");
+// SyntaxError: Unexpected token ] in JSON at position 13
+
+JSON.parse('{"foo": 1, }');
+// SyntaxError: Unexpected token } in JSON at position 12
+
+
JSON strings must be delimited by double (not single) quotes:
+
js
JSON.parse("{'foo': 1}");
+// SyntaxError: Unexpected token ' in JSON at position 1
+
+JSON.parse("'string'");
+// SyntaxError: Unexpected token ' in JSON at position 0
+
+
If you are writing JSON inside a JavaScript string literal, you should either use single quotes to delimit the JavaScript string literal, or escape the double quotes that delimit the JSON string:
+
js
JSON.parse('{"foo": 1}'); // OK
+JSON.parse("{\"foo\": 1}"); // OK
+
+
+
+
+ code_review
+
+
+
+ codeql_checker
+
+
+
+
+
+
+ $ cd /home/runner/work/solid-email/solid-email && npm run build
+
+
+
+
+
+
+
+
+
+
+ Describe your task, type `#` for adding context
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Refactor MailList component
+
+
+ Extract each row in MailList.tsx into a standalone MailListItem component. Preserve selection state, keyboard navigation, and the existing virtualization behavior.
+
+
+ Read MailList.tsx, useSelection.ts
+
+
+
+ Created MailListItem.tsx+62
+
+
+
+ Edited MailList.tsx+18−74
+
+
+ Mapped the MailList layout
+ Rows are rendered inline today and selection lives in useSelection. The react-window outer element wraps the list, so I'll keep its row renderer pointing at the new component to preserve virtualization.
+
+ Here's the plan I followed:
+
+
Create MailListItem.tsx with props for message, selected, and onSelect.
+
Wrap it in React.memo with a comparator on message.id + selected.
+
Lift useSelection into MailList and pass handlers down.
+
+
+ Make sure arrow‑key focus still works after the split.
+ Good call — I'll forward a ref to the row's root and call focus() when the active index changes, then re‑run the suite.
+
+
+ Ran npm test -- MailList
+
+ All 184 tests pass. Render time on the 10k‑message fixture dropped from 41ms to 12ms
+
+ Queued
+ Now extract the toolbar actions into a MailListToolbar component and add a Storybook story for it.
+
+
+
+ Describe what to build
+
+
+
+
+
+
+
+
+
+ Claude Opus 4.7
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Local
+
+
+
+
+ Autopilot (Preview)
+
+
+
+
+
+
+ Sessions
+
+ New Session
+
+
+
+
+
+
+
+ Refactor MailList component
+ Thinking…
+
+
+
+
+
+
+
+ Wire MCP server for telemetry pipeline
+ Editing mcp.config.ts
+
+
+
+
+
+
+
+ Add language server for .prisma files
+ Running tests in parser.test.ts
+
+
+
+
+
+
+ Refactor command palette to fluent API
+ +639-323 · 2 hrs ago
+
+
+
+
+
+ Scaffold extension for inline chat actions
+ 5 hrs ago
+
+ Generate typed SDK from OpenAPI 3.1 spec
+ +218-12 · 2 days ago
+
+
+
+
+
+
+
+
+ Diagnose flaky CI run on macOS arm64
+ 4 days ago
+
+
+
+
+
+
+ Optimize Live Share session bootstrap
+ +52-1 · 3 days ago
+
+
+
+
+
+
+ Add devcontainer for monorepo workspace
+ 6 days ago
+
+
+
+
+
+ Port debug adapter to DAP 1.65
+ 1 wk ago
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Agents that build for you
+
Hand off tasks to AI agents that autonomously plan, make code changes, run commands, and iterate until the job is done.
For example, assign a CLI-based agent to triage and fix bugs in the background, interact with another agent to implement a feature using live validation in the integrated browser, and delegate a homepage redesign to a cloud agent that opens a pull request for your team to review.
+
+
+ Add a POST /process/batch endpoint to the image service. Process up to 8 files in parallel with per-request budget, structured logging, and OpenTelemetry spans. Return per-item results.
+
+
+ Read server.go, processor.go, config.go
+
+
+
+ Created batch.go+128
+
+
+
+ Edited server.go+4−0
+
+
+
+ Created batch_test.go+96
+
+
+ Mapped the service layout
+ Existing handlers live in internal/http and the processor exposes a sync Extract. I'll add an ExtractCtx variant so the worker pool can honor cancellation, then fan out with errgroup + a weighted semaphore.
+
+
+
+ grep http.HandleFunc across internal/
+
+ Here's the plan I followed:
+
+
Add handleBatch in batch.go using a generic Result[Meta] type.
+
Cap concurrency with semaphore.NewWeighted(8) and wrap fan‑out in errgroup.
+
Wrap the request in an OTel span and a 30s context deadline.
+
Wire the route in server.go and add table tests.
+
+
+
+
+ Ran go test ./internal/http -run Batch -race
+
+ All 23 tests pass with -race clean. Throughput on a 64‑image batch (avg 1.2MB JPEG): 184ms to 31ms end‑to‑end
+ Nice. Stream results as NDJSON instead of buffering, and add a k6 script.
+
+ Queued
+ Then expose a p99_ms Prometheus histogram and wire it into the existing Grafana dashboard.
+
+
+
+ Describe what to build next
+
+
+
+
+
+
+
+
+
+ GPT 5.5
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Local
+
+
+
+
+ Autopilot (Preview)
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Any agent, any model
+
Use the agent harness that fits your workflow. Run agents locally or in the cloud,
+ with Copilot or third-party providers like Claude and OpenAI.
+
Choose from dozens of models across providers, from fast completion
+ models to advanced reasoning models. Or bring your own key to use any
+ model from any provider.
Stay productive while multiple agents work on tasks in parallel. Track
+ all your agent sessions from a single view, regardless of where they run.
+
Quickly filter and monitor sessions, or dive into an individual
+ agent interaction, without switching to a different tool or terminal.
+
+
+
+
+
+
+
Your rules, your agents
+
Ensure agents follow your practices and team workflows.
+ Define custom instructions, add agent skills, or
+ build custom agents tailored to your project.
+
Connect to external tools and services with MCP servers, or
+ install agent plugins or extensions to expand the agent's capabilities.
+
+
+
+
+
+
+
+
+
+
Start building with AI agents for free
+
+
+
No trial. No credit card required. Just your GitHub account.
VS Code has been the editor of choice for millions of developers for over a decade.
+ AI-powered inline suggestions, intelligent completions, and a rich editing experience
+ make it just as powerful when you're writing code yourself.
+
Seamlessly switch between working with agents and hands-on coding,
+ all within the same editor.
for species in np.sort(data["species"].unique()):
+for species in np.sort(iris_data["species"].unique()):
+try:
+stats = describe(species)
+except ValueError:
+print(f"{species}: no records")
+continue
+print(f"{species}: petal={stats['petal']:.2f} sepal={stats['sepal']:.2f}")
+
+if __name__ == "__main__":
+summary()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Code with extensions
+
Extend your agents with tools from extensions and Model Context Protocol servers.
+ Or, build your own
+ extension to power your team's unique scenarios.
+
VS Code supports almost every major programming language. Several ship in the box, like
+ JavaScript,
+ TypeScript, CSS, and HTML, but extensions for others can be found in the VS Code Marketplace.
+
+
+
+
+
JavaScript
+
TypeScript
+
Python
+
C#
+
C++
+
HTML
+
Java
+
JSON
+
PHP
+
Markdown
+
Powershell
+
YAML
+
+
+
+
+
+
+
+
+
Fully customizable
+
Customize your VS Code UI and layout so that it fits your coding style.
+
+
+
Color themes
+ let you modify the colors in VS Code's user interface to suit your preferences and work
+ environment.
+
+
+
Settings Sync enables you to share your user settings across
+ your VS Code instances with the Settings Sync feature.
+
+
+
Profiles let you create sets of customizations and quickly
+ switch between them or share them with others.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Code anywhere
+
Code wherever you're most productive, whether you're connected to the cloud, a remote repository,
+ or in the browser with VS Code for the Web (vscode.dev).
+
+
+
Built-in
+ Source Control empowers you with Git support out-of-the-box. Many other source control
+ providers are available through extensions.
+
+
+
GitHub Codespaces provides cloud-powered development
+ environments for any activity - whether it's a long-term project, or a short-term task like
+ reviewing a pull request.
+
+
+
+
+
+
+
+
+
+
+
+
Code with rich features
+
There's a lot more to an editor. Whether it's using built-in features or rich extensions, there's
+ something for everyone.
The key idea behind vibe.d was to take the fast and resource friendly asynchronous I/O model (AIO) and make it comfortable to use. Some other frameworks or toolkits such as node.js directly expose the event based interface of AIO using callback functions. While this is a workable approach, it has several drawbacks.
First and foremost, it often becomes tedious and confusing to write sequences of code (e.g. performing multiple consecutive database queries). Each step will introduce a new callback with a new scope, error callbacks often have to be handled separately. Especially the latter is a reason why it is tempting to just perform lax error handling.
Another consequence of asynchronous callbacks is that there is no meaningful call stack. Not only can this make debugging more difficult, but features such as exceptions cannot be used effectively in such an environment.
The approach of vibe.d is to use asynchronous I/O under the hood, but at the same time make it seem as if all operations were synchronous and blocking, just like ordinary I/O.
What makes this possible is D's support for so called fibers (also often called co-routines). Fibers behave a lot like threads, just that they are actually all running in the same thread. As soon as a running fiber calls a special yield() function, it returns control to the function that started the fiber. The fiber can then later be resumed at exactly the position and with the same state it had when it called yield(). This way fibers can be multiplexed together, running quasi-parallel and using each threads capacity as much as possible.
All of this usually happens behind the curtain of the vibe.d API, so that everything feels like just working with normal threads and blocking operations. All blocking functions, such as sleep() or read() will yield execution whenever they need to wait for an event and let themselves resume when the event occurs.
Using these tools, the event based nature of AIO is completely hidden from the user of the library. It also blends seamlessly with the built-in support for multi-threading. All concurrent operation are done using so called tasks. Every task runs inside of a single fiber and is multiplexed together with other tasks that run at the same time. To the user of the toolkit there is usually no visible difference between a task and a thread.
Having said all that, vibe.d can also be used without any fibers and no event loop if it has to, resembling the standard blocking I/O model.
+
+
+
+
Compact API
There is a strong focus on a short and simple API. Common tasks are kept as short and high level as possible, while still allowing fine grained control if needed. By using some of D's advanced features, typical vibe.d based programs reach a level of conciseness that usually only scripting languages such as Ruby can offer.
+
+
+
Zero-downtime changes
+
+ [work-in-progress] An integrated load balancer is able to dynamically compile, run and test new processes before switching them live after the code has been modified. This allows for seamless and low-risk changes on live-systems.
+
+
+
+
Exception based error handling
Usually, exception handling is restricted to local error handlers in event-based environments - it is impossible to wrap a sequence of events into a try-catch block, because every operation creates a new scope when callbacks are involved. vibe.d with its fiber based approach on the other hand has full support for exception handling.
A fiber behaves almost exactly like a thread regarding the stack; a single consistent call stack exists across all events that are handled in sequence. This way it becomes possible to naturally use exception handling, and especially in a web service environment exceptions are the ideal form of error handling.
Exceptions have the extremely useful feature that you can barely ignore them. As such, it is much more difficult to introduce subtle bugs and security holes by unintentionally ignoring error conditions. Any uncaught exceptions will automatically generate an error page and log all useful information in case of HTTP services.
+
+
+
+
Productivity
+
+
+
Full integrated web framework
The vibe.d library contains a complete set of tools needed for website and web service development. In addition to a HTTP 1.0/1.1 server, static file serving, an efficient template system, WebSockets, sessions and other features are already integrated. Surrounding features include a markdown filter, MongoDB and Redis drivers, cryptography, natural JSON and BSON support and a simple SMTP client.
There are also means to automatically generate JSON/REST or HTML form based interface from D classes, removing a lot of work and potential for bugs due to avoiding boilerplate code. The REST interface generator supports generation of both, the server and the client end, and as such can be used as a convenient RPC mechanism.
+
+
+
Native database drivers
+
+
The core library contains built-in support for MongoDB and Redis databases. These drivers provide a default for fast and flexible data storage. More database drivers are available in the DUB package registry, for example a vibe.d compatible MySQL driver.
Making existing drivers compatible is easy to do thanks to the blocking nature of vibe.d's API. The only thing that has to be done in most cases is to replace the socket calls (send(), recv(), connect() etc.) with the corresponding vibe.d functions. A blog post gives an overview of what needs to be done using the MySQL driver as an example.
+
+
+
Raw network and file handling
Of course, raw TCP/UDP and file access is supported by the toolkit to enable custom protocols and file formats. I/O happens through a blocking stream interface that effectively hides the fact that the underlying operations are actually event based.
+
+
+
Generic concurrency tools
Apart from I/O operations, all the usual tools for generic programming tasks are supported:
+
+
sleep() pauses execution of the current tasks for a specific amount of time
Timers enable asynchronous scheduling of callbacks
Mutexes and condition variables allow for sharing data access between multiple threads without interfering with the event loop
Data pipes for streaming data between tasks/threads
+
+
+
+
Graphical user interface integration
Contrary to most other frameworks supporting asynchronous I/O, vibe.d fully integrates with the UI event loop, so that it can be used to power applications with a graphical user interface.
For Windows, there is a native event driver implementation that makes use of the MsgWaitForMultipleObjectsEx function to process window messages together with I/O or concurrency events. For systems running X11, it's possible to use createFileDescriptorEvent to listen on the display connection instead of using XNextEvent. Finally, macOS has an event loop based on `CFRunLoop`, which processes CoreFramework events, as well as basic kqueue events.
+
+ An advanced example of this is Aspect, our photo management application that uses vibe.d for all of its I/O and concurrency needs. Tasks are a great fit for the asynchronous nature of the GUI system APIs, allowing to turn most event/callback based code into clear procedural code with a linear execution path. This results in both, more readable and more robust code. For Aspect, we are using direct Win32 API access on Windows and SDL2 on Linux and macOS.
+
+
+
+
+
Performance
+
+
Asynchronous I/O operations
+
+
+ Instead of using classic blocking I/O together with multi-threading for doing parallel network and file operations, all operations are using asynchronous operating system APIs. eventcore is used to access these APIs operating system independently.
+
+
Using asynchronous I/O has several advantages, the main point being that the memory overhead is much lower. This is because only a single hardware thread is needed to handle an arbitrary number of concurrent operations. The thread typically rests waiting for events and is woken up by the operating system as soon as new data arrives, a new connection is established, or an error occurs. After each initiated blocking operation (e.g. writing data to a socket), the thread will go back to sleep and let the operating system execute the operation in the background.
+
+ Another important aspect for speed is that, because there is only one or a few threads necessary, it is often possible to save a lot of expensive thread context switches. However, note that if the application has to do a lot of computations apart from the actual I/O operations, vibe.d has full support for multi-threading to fully exploit the system's multi-core CPU.
+
+
+ Because using the asynchronous event based model is often more involved regarding the application implementation, fibers are used together with an event based scheduler to give the impression of classic blocking calls and multi-threading, thus hiding the additional complexities, while retaining the performance characteristics of asynchronous I/O.
+
+
+
+
Multi-threading support
While the performance is usually very good in a single-threaded application due to the use of asynchronous I/O and fibers, there are applications that can greatly benefit from using multiple cores. vibe.d supports multiple ways to exploit this additional computational power, leaving the decision for the threading architecture to the application writer.
Apart from allowing the use of low-level D threads, a thread pool is provided, which is used for any task started with runWorkerTask instead of runTask. This is mainly useful for running computationally expensive operations, such as decoding images, alongside the normal program flow, but it can also be used for better performance of I/O heavy tasks in certain cases.
The library is very flexible in the way that multi-threading can be employed and makes sure that no low-level race-conditions can occur, as long as no unsafe operations, such as cast()s or __gshared variables, are used. The following list shows some typical threading architectures:
+
+
Distributed processing of incoming connections
The HTTP server (as well as any other TCP based server) can be instructed to process incoming connections across the worker threads of the thread pool instead of in the main thread. For applications that don't need to share state across different connections in the process, this can increase the maximum number of requests per second linearly with the number of cores in the system. This feature is enabled using the HTTPServerOption.distribute or TCPListenOptions.distribute settings.
Using worker tasks for computations
Computationally expensive tasks can be off-loaded from the main thread by performing them with runWorkerTask. Any such task will be executed in the thread pool. This approach is useful whenever an application has such computationally expensive tasks to do, because it allows pure I/O tasks to stay unaffected by heavy computational load. Probably the most common example of such a task is image processing/decoding/encoding.
Using plain D threads
Normal D threads can also be used together with vibe.d. This is important when the threading primitives of the D standard library are used. Apart from the D core threads, these are std.parallelism and std.concurrency. Note however, that parts of the D standard library shouldn't be mixed with vibe.d's I/O functions, because they block the event loop. Most notably, the message passing functions in std.concurrency are currently* not compatible with vibe.d's event loop and should be replaced with the ones in vibe.core.concurrency.
+
+
Note that vibe.d also includes experimental library based support of isolated and scoped references. These allow mutable data to be passed between threads without having to use mutexes or similar means to synchronize data access. This is especially useful when transferring the data used in worker tasks between the worker thread and the main thread.
+
+
+
Natively compiled code
+
+
Vibe.d is written in the D Programming Language. D is a C-style language that compiles down to native machine code with minimal runtime overhead. In addition to being fast, D offers a number of features that allow additional performance improvements and especially code readability, safety and usability improvements compared to other languages such as C++.
+
+ Some notable features are listed here, but there are a lot of additional things which would be beyond the scope of this text. See theD feature pageor the Programming in D online book for a more general overview.
+
+
+
Templates, mixins and compile-time functions
+
+
The meta-programming system in D is extremely powerful. Templates (comparable to C++ templates) support variadic parameters, as well as string and alias parameters - a feature which enables very comfortable compile-time interfaces.
The ultimate power is given by the possibility to execute ordinary functions at compile time, as well as the ability to compile a string given at compile time as D code. This functionality is similar to JavaScript's eval() function, just that the result is statically compiled to machine code (and without the runtime security implications of eval()).
These features together with the possibility to read files at compile time have enabled the powerful Diet template parser.
+
+
Garbage collection
+
+
The D runtime offers built-in garbage collection, which enables some interesting possibilities, apart from the obvious advantage of no need for manual memory management and the associated risk of memory leaks and dangerous dangling references.
Most notably, it allows to work with immutable data, such as strings or objects, which can be safely referenced and passed between threads without any synchronization overhead. When passing data between threads, it is statically enforced that the data is safe to be referenced from multiple threads. This avoids a whole class of difficult to reproduce and track down bugs common in multi-threaded code of many other languages.
+
+
Closures and lambdas
+
+
A feature also known from some scripting and functional languages, but also C# and a few others are closures and lambdas. They allow to specify callback functions in a very compact and readable way. In turn they tend to have a strong influence on the API design, as they can make computationally efficient or safe APIs actually bearable (or even pleasant) to use.
+
+
Properties
+
+
Properties are functions that look like they were a field of a class or struct. They are used throughout the API to get a logical and intuitive interface without all clamps and additional typing needed for normal function calls.
+
+
Module system
+
+
D's module system is similar to the one used in Java. Among other things it encodes the dependencies between different modules (D files) in a semantically clear way. Using this information, it becomes possible to build whole applications just by specifying the root file (app.d) on the command line. The dependencies can be found recursively. The rdmd build tool included with the D compiler, which is supported by the DUB package manager, works this way.
+
+
Arrays and slices
+
+
Arrays support native slicing with a very natural syntax. Together with the garbage collector they enable extremely fast string parser implementations which are safe (bounds checking) and easy to read at the same time.
+
+
Concise and readable syntax
+
+
The syntax in general is very clean and to the point - especially compared to its perhaps closest relative, C++. But it doesn't need to fear modern scripting languages such as Ruby and Python in this regard either. Apart from the occasional need to specify an explicit type (types can be inferred using auto), you will discover that there is not much to miss and that development using D is highly efficient.
+
+
+
+
+
Compile-time "Diet" templates
+
+
vibe.d has built-in support for Diet HTML templates based on the Pug template syntax known from node.js which in turn is based on Haml. These templates remove all the syntax overhead that is inherent to HTML's tag based notation and also allow the inline specification of dynamic elements. Typically, these elements are written in a dynamic scripting language (JavaScript in case of Pug).
In vibe.d, however, templates can contain embedded D code. The templates are read and parsed while the application is being compiled and optimized D code is generated for them. This means that the runtime overhead for those templates is non-existent - there are no disk accesses, no parsing and there is no string copying involved because all of this has already been done before the application has even started.
At the same time you can program in the same language as for the rest of the application, which makes for a very consistent development experience.
Метод добавляет (или обновляет) параметры товара к элементу каталога. Нестатический метод.
+
+
Параметры вызова
+
+
+
+
Параметр
Описание
С версии
+
+
+
arFields
+
Ассоциативный массив, ключами которого являются названия параметров товара, а значениями - новые значения параметров. Допустимые ключи:
+
+ключи, независящие от вида товаров:
+
+
ID - код товара (элемента каталога - обязательный);
+
AVAILABLE - доступность товара к покупке (Y/N, поле обновляется автоматически);
+
TYPE - тип товара (значения по умолчанию зависят от вида торгового каталога);
+
+
+ключи для обычных товаров и торговых предложений:
+
+
VAT_ID - код НДС;
+
VAT_INCLUDED - флаг (Y/N) включен ли НДС в цену;
+
QUANTITY - количество товара на складе;
+
QUANTITY_RESERVED - зарезервированное количество;
+
QUANTITY_TRACE - флаг (Y/N/D)* "включить количественный учет" (до версии 12.5.0 параметр назывался "уменьшать ли количество при заказе");
+
CAN_BUY_ZERO - флаг (Y/N/D)* "разрешить покупку при отсутствии товара";
+
SUBSCRIBE - флаг (Y/N/D)* "разрешить подписку при отсутствии товара";
+
BUNDLE - признак наличия набора (Y/N, поле обновляется автоматически);
+
+
+
PURCHASING_PRICE - закупочная цена. При указании в массиве этого ключа необходимо обязательно указать и валюту PURCHASING_CURRENCY, иначе метод возвратит false.
+
PURCHASING_CURRENCY - валюта закупочной цены;
+
+
WEIGHT - вес единицы товара;
+
+
WIDTH - ширина товара (в мм);
+
LENGTH - длина товара (в мм);
+
HEIGHT - высота товара (в мм);
+
MEASURE - ID единицы измерения;
+
+
BARCODE_MULTI - (Y/N) определяет каждый ли экземпляр товара имеет собственный штрихкод;
+
+
+ключи для продажи контента:
+
+
PRICE_TYPE - тип цены (S - одноразовый платеж, R - регулярные платежи, T - пробная подписка);
+
RECUR_SCHEME_TYPE - тип периода подписки ("H" - час, "D" - сутки, "W" - неделя, "M" - месяц, "Q" - квартал, "S" - полугодие, "Y" - год);
+
RECUR_SCHEME_LENGTH - длина периода подписки;
+
TRIAL_PRICE_ID - код товара, для которого данный товар является пробным;
+
WITHOUT_ORDER - флаг "Продление подписки без оформления заказа".
+
+
+
+
+
boolCheck
+
Параметр, указывающий, проверять ли наличие в базе информации о товаре или нет, перед добавлением. По умолчанию - проверять.
11.0.5
+
+
*D - значение берется из настроек модуля.
+
+
+
Возвращаемые значения
+
Возвращает true в случае успешного обновления параметров и false в противном случае.
+
+
+
+
+
+
+
+
+
+
Типы товаров
+
+
+
+
Основные
Описание
С версии
+
+
\Bitrix\Catalog\ProductTable::TYPE_PRODUCT
Простой товар
14.0.0
+
+
\Bitrix\Catalog\ProductTable::TYPE_SET
Комплект
14.0.0
+
+
\Bitrix\Catalog\ProductTable::TYPE_SKU
Товар с торговыми предложениями
16.0.3
+
+
\Bitrix\Catalog\ProductTable::TYPE_OFFER
Торговое предложение
16.0.3
+
+
+
+
+
+
+
+
Дополнительные
Описание
С версии
+
+
\Bitrix\Catalog\ProductTable::TYPE_FREE_OFFER
Торговое предложение, у которого нет товара (не указан или удален).
16.0.3
+
+
\Bitrix\Catalog\ProductTable::TYPE_EMPTY_SKU
Специфический тип, означает невалидный товар с торговыми предложениями.
16.0.3
+
+
+
+
+
+
+
+
Добавляемые в корзину
Описание
С версии
+
+
\Bitrix\Catalog\ProductTable::TYPE_PRODUCT
Простой товар
14.0.0
+
+
\Bitrix\Catalog\ProductTable::TYPE_SET
Комплект
14.0.0
+
+
\Bitrix\Catalog\ProductTable::TYPE_OFFER
Торговое предложение
16.0.3
+
+
+
+
+
+
+
+
+
+
+
+
+
Примеры использования
+
+
$arFields = array(
+ "ID" => $PRODUCT_ID,
+ "VAT_ID" => 1, //выставляем тип ндс (задается в админке)
+ "VAT_INCLUDED" => "Y" //НДС входит в стоимость
+);
+if(CCatalogProduct::Add($arFields))
+ echo "Добавили параметры товара к элементу каталога ".$PRODUCT_ID.'<br>';
+else
+ echo 'Ошибка добавления параметров<br>';
+
+
+
+
+
+
+
+
+
+
+ Новинки документации в соцсетях:
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Была ли эта страница полезна?
+
+
+
+
+
+
+
+
Что можно улучшить?
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Пользовательские комментарии
Помните, что Пользовательские комментарии, несмотря на модерацию, не являются официальной документацией. Ответственность за их использование несет сам пользователь.
Также Пользовательские комментарии не являются местом для обсуждения функционала. По подобным вопросам обращайтесь на форумы.
+
+
+
+
+
+
+ 3
+
+
+ Алексей Попович
+ 23.12.2019 13:21:23
+
+
+
+
+
Для обновления остатков лучше воспользоваться конструкцией:
Quickly fork, edit online, and submit a pull request for this page.
+ Requires a signed-in GitHub account. This works well for small changes.
+ If you'd like to make larger changes you may want to consider using
+ a local clone.
+
+
+
+
Phobos Runtime Library
+
+
+
+
Phobos is the standard runtime library that comes with the D language
+compiler.
+
+
The std namespace is used for the main modules in the
+ Phobos standard library.
+
The etc namespace is used for external C/C++ library bindings.
+
The core namespace is mainly used for low-level D runtime functions.
core.stdcpp wraps some of the C++ standard library.
+
core.sys wraps OS headers.
+
+
+
The following table is a quick reference guide for which Phobos modules to
+use for a given category of functionality. Note that some modules may appear in
+more than one category, as some Phobos modules are quite generic and can be
+applied in a variety of situations.
Generic algorithms that work with ranges
+ of any type, including strings, arrays, and other kinds of
+ sequentially-accessed data. Algorithms include searching,
+ comparison, iteration, sorting, set operations, and mutation.
+
Convenient operations commonly used with built-in arrays.
+ Note that many common array operations are subsets of more generic
+ algorithms that work with arbitrary ranges, so they are found in
+ std.algorithm.
+
The LDC project aims to provide a portable D programming language compiler with modern optimization and code generation capabilities. The compiler uses the official DMD frontend to support the latest D2 version and relies on the LLVM Core libraries for code generation.
+
LDC is fully Open Source; the parts of the code not taken/adapted from other projects are BSD-licensed (see the LICENSE file for details).
+
D1 is no longer supported in the current development tree; the last version supporting it can be found at the d1 Git branch.
+
NOTE: As Wiki pages usually don't keep up with development, the changelog might be of use to check for recent developments and newly conquered targets.
+
+
Architectures
+
+
+
+
x86 / x86_64
+
+
Fine, CI-tested.
+
+
+
64-bit ARM
+
+
Basically fine, a few testsuite failures remain (for non-Apple OS). See tracker issue for ~current status.
+
Should work fine; currently limited to -betterC (lacking druntime/Phobos support). See Generating WebAssembly with LDC for a quick how-to.
+
+
+
PowerPC
+
+
Incomplete; has been worked on (32-bit, 64-bit big & little endian) but not touched/tested in years. E.g., see tracker issue.
+
+
+
MIPS
+
+
Incomplete; has been worked on but not really touched/tested in years. E.g., see tracker issue.
+
+
+
Others
+
+
Basic code generation should work as long as there's an LLVM backend, and simple -betterC code might just work. druntime/Phobos support is most likely lacking (and probably requires a new version predefined by the compiler). Proper C(++) interop most likely requires a new TargetABI implementation in the compiler.
+
+
+
Operating Systems
+
+
+
+
Linux
+
+
glibc and musl environments are working fine & CI-tested (on i686 / x86_64 / AArch64 for glibc, x86_64 for musl). uClibc should be usable but isn't tested.
+
+
+
macOS
+
+
Fine, CI-tested on arm64 and x86_64. Requires macOS v10.7+ for native TLS. 32-bit i686 support was dropped with LDC v1.15.
+
+
+
Windows
+
+
Fine for 'native' MSVC (Microsoft Visual C++) environments, CI-tested on Win32 & Win64. NOTE: LDC uses 64-bit double precision for real, unlike DMD, for MSVC long double compatibility. 32-bit MinGW support was almost complete at one stage but got neglected; a manageable number of adaptations (mainly in druntime) would probably suffice to support it again.
+
+
+
Android
+
+
Should be usable for ARMv7-A / AArch64 / i686 / x86_64, only rudimentarily CI-tested though (cross-compilability). Check out the Build D for Android article for how to get started.
+
+
+
iOS / tvOS / watchOS
+
+
Should be usable with 64-bit ARM (all druntime/Phobos unittests pass on iOS with LDC v1.21), only rudimentarily CI-tested though. The official prebuilt macOS package supports cross-compilation out-of-the-box, just use -mtriple=arm64-apple-ios12.0.
+
+
+
FreeBSD
+
+
Fine, CI-tested on x86_64. Requires LLD 9+ to pull in libexecinfo automatically when linking static druntime.
+
+
+
Other BSDs
+
+
Should be usable, not CI-tested though.
+
+
+
Solaris
+
+
Ditto.
+
+
+
Contributing
+
LDC is an entirely community-driven effort, so all contributions are warmly welcomed. The easiest way to help with development is to write high-quality bug reports for any issues you run into. For a quick guide on what a useful report should contain, please see Reporting LDC issues.
+
If you are interested in getting into compiler development, anecdotal evidence suggests that hacking on LDC might be a nice first step, particularly because the LLVM backend is very comfortable to work with. To get started, just browse through the issue list, find a ticket that tickles your fancy (some of them are specifically marked as "junior jobs"), and work on a fix – and of course don't hesitate to ask for advice at the mailing list or on IRC. An LDC contributor's guide is in the works. Have a look at LDC project ideas for a list of features/improvements to add to LDC.
+
We would also be excited to see LDC packages in more OS distributions, particular Debian and its derivatives. So, if you think you might be able to help, please just drop us a line at the development mailing list. We will actively try to make packaging as smooth as possible, but besides the fact that upstream-maintained packages are sometimes discouraged, it is hard to build good packages for a system you don't know well, so we need to rely on external contributors here.
+
+
Presentations
+
LDC is an active project and the team promotes the use of D and LDC.
+
cURL error 60: SSL certificate problem: unable to get local issuer certificate
+
+This problem can occur when developing locally on windows. I am using windows 10 (x64)
+
+In order to fix the error, I downloaded cacert.pem from https://curl.haxx.se/docs/caextract.html
+
+Set the following value for in php.ini
+
+curl.cainfo = "C: \ php-8.0.7 \ extras \ ssl \ cacert.pem"
cURL error 60: SSL certificate problem: unable to get local issuer certificate
+
+This local development error comes when curl.cainfo variable is not set correctly.
+
+I faced this issue in PHP Version 7.3.1
+
+In order to fix the error, I downloaded cacert.pem from https://curl.haxx.se/docs/caextract.html
+
+Set the following paths in php.ini
+
+curl.cainfo="D:\wamp64\bin\php\php7.3.1\extras\ssl\cacert.pem"
+openssl.cafile="D:\wamp64\bin\php\php7.3.1\extras\ssl\cacert.pem"
+
+Even after adding the paths and restart Apache, Inside phpinfo(), both the paths were showing blank.
+
+The error will go only if we set via php code of the project.
+
+Example code worked for me :-
+
+$guzzle = new \GuzzleHttp\Client(['verify' => 'D:\wamp64\bin\php\php7.3.1\extras\ssl\cacert.pem']);
I was editing wrong php.ini file in last comment.
+
+Even though loaded configuration path was showing as "D:\wamp64\bin\apache\apache2.4.37\bin\php.ini" inside phpinfo() of WAMP Server, It was actually loading "D:\wamp64\bin\apache\apache2.4.37\bin\phpForApache.ini"
+
+Once I set both the variables inside phpForApache.ini, details are displayed in phpinfo() and error has gone without extra coding line.
Quickly fork, edit online, and submit a pull request for this page.
+ Requires a signed-in GitHub account. This works well for small changes.
+ If you'd like to make larger changes you may want to consider using
+ a local clone.
+
+
+
+
std.json
+
+
Implements functionality to read and write JavaScript Object Notation values.
+
JavaScript Object Notation is a lightweight data interchange format commonly used in web services and configuration files.
+It's easy for humans to read and write, and it's easy for machines to parse and generate.
+
+
+Warning: While JSONValue is fine for small-scale use, at the range of hundreds of megabytes it is
+known to cause and exacerbate GC problems. If you encounter problems, try replacing it with a stream parser. See
+also https://forum.dlang.org/post/[email protected].
+
+
Constructor for JSONValue. If arg is a JSONValue
+ its value and type will be copied to the new JSONValue.
+ Note that this is a shallow copy: if type is JSONType.object
+ or JSONType.array then only the reference to the data will
+ be copied.
+ Otherwise, arg must be implicitly convertible to one of the
+ following types: typeof(null), string, ulong,
+ long, double, an associative array V[K] for any V
+ and K i.e. a JSON object, any array or bool. The type will
+ be set accordingly.
An enum value that can be used to obtain a JSONValue representing
+ an empty JSON object.
+ Unlike emptyObject, the order of inserted keys is preserved.
JSON arrays and objects are compared deeply. The order of object keys does not matter.
+
+
+ Floating point numbers are compared for exact equality, not approximal equality.
+
+
+ Different number types (unsigned, signed, and floating) will be compared by converting
+ them to a common type, in the same way that comparison of built-in D int, uint and
+ float works.
+
+
+ Other than that, types must match exactly.
+ Empty arrays are not equal to empty objects, and booleans are never equal to integers.
+
+
+
Returns:
whether this JSONValue is equal to rhs
+
+
+
pure nothrow @nogc @trusted hash_t toHash() const;
+
+
Calculate a numerical hash value for this value,
+allowing JSONValue to be used in associative arrays.
Implicitly calls toJSON on this JSONValue, like toString, but
+ also passes true as pretty argument.
+
options can be used to tweak the conversion behavior
+
+
+
void toPrettyString(Out)(Out sink, in JSONOptions options = JSONOptions.none) const;
+
+
+
+
+
+
JSONValue parseJSON(T)(T json, int maxDepth = -1, JSONOptions options = JSONOptions.none) if (isSomeFiniteCharInputRange!T);
+
+
Parses a serialized string and returns a tree of JSON values.
+
Throws:
JSONException if string does not follow the JSON grammar or the depth exceeds the max depth,
+ ConvException if a number in the input cannot be represented by a native D type.
+
+
Parameters:
T json
+
json-formatted string to parse
+
int maxDepth
+
maximum depth of nesting allowed, -1 disables depth checking
+
JSONOptions options
+
enable decoding string representations of NaN/Inf as float values
+
+
+
+
JSONValue parseJSON(T)(T json, JSONOptions options) if (isSomeFiniteCharInputRange!T);
+
+
Parses a serialized string and returns a tree of JSON values.
+
enable decoding string representations of NaN/Inf as float values
+
+
+
+
@safe string toJSON(ref const JSONValue root, in bool pretty = false, in JSONOptions options = JSONOptions.none);
+
+
Takes a tree of JSON values and returns the serialized string.
+
Any Object types will be serialized in a key-sorted order.
+
+
+If pretty is false no whitespaces are generated.
+If pretty is true serialized string is formatted to be human-readable.
+Set the JSONOptions.specialFloatLiterals flag is set in options to encode NaN/Infinity as strings.
+
+
+
void toJSON(Out)(auto ref Out json, ref const JSONValue root, in bool pretty = false, in JSONOptions options = JSONOptions.none) if (isOutputRange!(Out, char));
+
Quickly fork, edit online, and submit a pull request for this page.
+ Requires a signed-in GitHub account. This works well for small changes.
+ If you'd like to make larger changes you may want to consider using
+ a local clone.
+
+
+
+
Table of Contents
+
+
+
+
This is the specification for the D Programming Language.
+ For more information see dlang.org.
Quickly fork, edit online, and submit a pull request for this page.
+ Requires a signed-in GitHub account. This works well for small changes.
+ If you'd like to make larger changes you may want to consider using
+ a local clone.
+
+
+
+
std.regex
+
+
Regular expressions
+ are a commonly used method of pattern matching
+ on strings, with regex being a catchy word for a pattern in this domain
+ specific language. Typical problems usually solved by regular expressions
+ include validation of user input and the ubiquitous find & replace
+ in text processing utilities.
+
+ They met on 24/01/1970.
+7/8/99 wasn't as hot as 7/8/2022.
+
+
import std.regex;
+import std.stdio;
+// Print out all possible dd/mm/yy(yy) dates found in user input.
+auto r = regex(r"\b[0-9][0-9]?/[0-9][0-9]?/[0-9][0-9](?:[0-9][0-9])?\b");
+foreach (line; stdin.byLine)
+{
+ // matchAll() returns a range that can be iterated
+// to get all subsequent matches.
+foreach (c; matchAll(line, r))
+ writeln(c.hit);
+}
+
+
+
+ Create a static regex at compile-time, which contains fast native code:
+
+
import std.regex;
+auto ctr = ctRegex!(`^.*/([^/]+)/?$`);
+
+// It works just like a normal regex:
+auto c2 = matchFirst("foo/bar", ctr); // First match found here, if any
+assert(!c2.empty); // Be sure to check if there is a match before examining contents!
+assert(c2[1] == "bar"); // Captures is a range of submatches: 0 = full match.
+
import std.regex;
+// The result of `matchAll/matchFirst` is directly testable with `if/assert/while`,
+// e.g. test if a string consists of letters only:
+assert(matchFirst("LettersOnly", `^\p{L}+$`));
+
+// And we can take advantage of the ability to define a variable in the IfCondition:
+if (const captures = matchFirst("At l34st one digit, but maybe more...", `((\d)(\d*))`))
+{
+ assert(captures[2] == "3");
+ assert(captures[3] == "4");
+ assert(captures[1] == "34");
+}
+
+ The general usage guideline is to keep regex complexity on the side of simplicity,
+ as its capabilities reside in purely character-level manipulation.
+ As such it's ill-suited for tasks involving higher level invariants
+ like matching an integer number bounded in an [a,b] interval.
+ Checks of this sort of are better addressed by additional post-processing.
+
+
+ The basic syntax shouldn't surprise experienced users of regular expressions.
+ For an introduction to std.regex see a
+ short tour of the module API
+ and its abilities.
+
+
+ There are other web resources on regular expressions to help newcomers,
+ and a good reference with tutorial
+ can easily be found.
+
+
+ This library uses a remarkably common ECMAScript syntax flavor
+ with the following extensions:
+
Named subexpressions, with Python syntax.
+
Unicode properties such as Scripts, Blocks and common binary properties e.g Alphabetic, White_Space, Hex_Digit etc.
+
Arbitrary length and complexity lookbehind, including lookahead in lookbehind and vise-versa.
+
+
+
+
Pattern syntax
+ std.regex operates on codepoint level,
+ 'character' in this table denotes a single Unicode codepoint.
+
Pattern element
Semantics
+
Atoms
Match single characters
+
any character except [{|*+?()^$
Matches the character itself.
+
.
In single line mode matches any character.
+ Otherwise it matches any character except '\n' and '\r'.
+
[class]
Matches a single character
+ that belongs to this character class.
+
[^class]
Matches a single character that
+ does not belong to this character class.
+
\cC
Matches the control character corresponding to letter C
+
\xXX
Matches a character with hexadecimal value of XX.
+
\uXXXX
Matches a character with hexadecimal value of XXXX.
+
\U00YYYYYY
Matches a character with hexadecimal value of YYYYYY.
+
\f
Matches a formfeed character.
+
\n
Matches a linefeed character.
+
\r
Matches a carriage return character.
+
\t
Matches a tab character.
+
\v
Matches a vertical tab character.
+
\d
Matches any Unicode digit.
+
\D
Matches any character except Unicode digits.
+
\w
Matches any word character (note: this includes numbers).
+
\W
Matches any non-word character.
+
\s
Matches whitespace, same as \p{White_Space}.
+
\S
Matches any character except those recognized as \s .
+
\\
Matches \ character.
+
\c where c is one of [|*+?()
Matches the character c itself.
+
\p{PropertyName}
Matches a character that belongs
+ to the Unicode PropertyName set.
+ Single letter abbreviations can be used without surrounding {,}.
+
\P{PropertyName}
Matches a character that does not belong
+ to the Unicode PropertyName set.
+ Single letter abbreviations can be used without surrounding {,}.
+
\p{InBasicLatin}
Matches any character that is part of
+ the BasicLatin Unicode block.
+
\P{InBasicLatin}
Matches any character except ones in
+ the BasicLatin Unicode block.
+
\p{Cyrillic}
Matches any character that is part of
+ Cyrillic script.
+
\P{Cyrillic}
Matches any character except ones in
+ Cyrillic script.
+
Quantifiers
Specify repetition of other elements
+
*
Matches previous character/subexpression 0 or more times.
+ Greedy version - tries as many times as possible.
+
*?
Matches previous character/subexpression 0 or more times.
+ Lazy version - stops as early as possible.
+
+
Matches previous character/subexpression 1 or more times.
+ Greedy version - tries as many times as possible.
+
+?
Matches previous character/subexpression 1 or more times.
+ Lazy version - stops as early as possible.
+
?
Matches previous character/subexpression 0 or 1 time.
+ Greedy version - tries as many times as possible.
+
??
Matches previous character/subexpression 0 or 1 time.
+ Lazy version - stops as early as possible.
+
{n}
Matches previous character/subexpression exactly n times.
+
{n,}
Matches previous character/subexpression n times or more.
+ Greedy version - tries as many times as possible.
+
{n,}?
Matches previous character/subexpression n times or more.
+ Lazy version - stops as early as possible.
+
{n,m}
Matches previous character/subexpression n to m times.
+ Greedy version - tries as many times as possible, but no more than m times.
+
{n,m}?
Matches previous character/subexpression n to m times.
+ Lazy version - stops as early as possible, but no less then n times.
+
Other
Subexpressions & alternations
+
(regex)
Matches subexpression regex,
+ saving matched portion of text for later retrieval.
+
(?#comment)
An inline comment that is ignored while matching.
+
(?:regex)
Matches subexpression regex,
+ not saving matched portion of text. Useful to speed up matching.
+
A|B
Matches subexpression A, or failing that, matches B.
+
(?P<name>regex)
Matches named subexpression
+ regex labeling it with name 'name'.
+ When referring to a matched portion of text,
+ names work like aliases in addition to direct numbers.
+
+
Assertions
Match position rather than character
+
^
Matches at the beginning of input or line (in multiline mode).
+
$
Matches at the end of input or line (in multiline mode).
+
\b
Matches at word boundary.
+
\B
Matches when not at word boundary.
+
(?=regex)
Zero-width lookahead assertion.
+ Matches at a point where the subexpression
+ regex could be matched starting from the current position.
+
+
(?!regex)
Zero-width negative lookahead assertion.
+ Matches at a point where the subexpression
+ regex could not be matched starting from the current position.
+
+
(?<=regex)
Zero-width lookbehind assertion. Matches at a point
+ where the subexpression regex could be matched ending
+ at the current position (matching goes backwards).
+
+
(?<!regex)
Zero-width negative lookbehind assertion.
+ Matches at a point where the subexpression regex could not
+ be matched ending at the current position (matching goes backwards).
+
+
+
+
+
Character classes
+
Pattern element
Semantics
+
Any atom
Has the same meaning as outside of a character class,
+ except for ] which must be written as \]
+
a-z
Includes characters a, b, c, ..., z.
+
[a||b], [a--b], [a~~b], [a&&b]
Where a, b are arbitrary classes, means union, set difference,
+ symmetric set difference, and intersection respectively.
+ Any sequence of character class elements implicitly forms a union.
+
+
+
+
Regex flags
+
Flag
Semantics
+
g
Global regex, repeat over the whole input.
+
i
Case insensitive matching.
+
m
Multi-line mode, match ^, $ on start and end line separators
+ as well as start and end of input.
+
s
Single-line mode, makes . match '\n' and '\r' as well.
+
x
Free-form syntax, ignores whitespace in pattern,
+ useful for formatting complex regular expressions.
+
+
+ A set of functions in this module that do the substitution rely
+ on a simple format to guide the process. In particular the table below
+ applies to the format argument of
+ replaceFirst and replaceAll.
+
+
+ The format string can reference parts of match using the following notation.
+
+
+
+ All matches returned by pattern matching functionality in this library
+ are slices of the original input. The notable exception is the replace
+ family of functions that generate a new string from the input.
+
+
+ In cases where producing the replacement is the ultimate goal
+ replaceFirstInto and replaceAllInto could come in handy
+ as functions that avoid allocations even for replacement.
+
+
Regex object holds regular expression pattern in compiled form.
+
Instances of this object are constructed via calls to regex.
+ This is an intended form for caching and storage of frequently
+ used regular expressions.
+
+
+
Example
+ Test if this object doesn't contain any compiled pattern.
+
Regex!char r;
+assert(r.empty);
+r = regex(""); // Note: "" is a valid regex pattern.
+assert(!r.empty);
+
+
+
+ Getting a range of all the named captures in the regex.
+
Same as !(x.empty), provided for its convenience in conditional statements.
+
+
@property inout(Captures!R) captures() inout;
+
+
Same as .front, provided for compatibility with original std.regex.
+
+
+
+
auto match(R, RegEx)(R input, RegEx re) if (isSomeString!R && isRegexFor!(RegEx, R));
+
auto match(R, String)(R input, String re) if (isSomeString!R && isSomeString!String);
+
+
Start matching input to regex pattern re,
+ using Thompson NFA matching scheme.
+
The use of this function is discouraged - use either of
+ matchAll or matchFirst.
+
+
+ Delegating the kind of operation
+ to "g" flag is soon to be phased out along with the
+ ability to choose the exact matching scheme. The choice of
+ matching scheme to use depends highly on the pattern kind and
+ can done automatically on case by case basis.
+
+
+
Returns:
a RegexMatch object holding engine state after first match.
+
+
+
auto matchFirst(R, RegEx)(R input, RegEx re) if (isSomeString!R && isRegexFor!(RegEx, R));
+
auto matchFirst(R, String)(R input, String re) if (isSomeString!R && isSomeString!String);
+
auto matchFirst(R, String)(R input, String[] re...) if (isSomeString!R && isSomeString!String);
+
+
Find the first (leftmost) slice of the input that
+ matches the pattern re. This function picks the most suitable
+ regular expression engine depending on the pattern properties.
+
re parameter can be one of three types:
+
Plain string(s), in which case it's compiled to bytecode before matching.
+
Regex!char (wchar/dchar) that contains a pattern in the form of
+ compiled bytecode.
+
StaticRegex!char (wchar/dchar) that contains a pattern in the form of
+ compiled native machine code.
+
+
+
+
Returns:
Captures containing the extent of a match together with all submatches
+ if there was a match, otherwise an empty Captures object.
+
+
+
auto matchAll(R, RegEx)(R input, RegEx re) if (isSomeString!R && isRegexFor!(RegEx, R));
+
auto matchAll(R, String)(R input, String re) if (isSomeString!R && isSomeString!String);
+
auto matchAll(R, String)(R input, String[] re...) if (isSomeString!R && isSomeString!String);
+
+
Initiate a search for all non-overlapping matches to the pattern re
+ in the given input. The result is a lazy range of matches generated
+ as they are encountered in the input going left to right.
+
This function picks the most suitable regular expression engine
+ depending on the pattern properties.
+
+
+ re parameter can be one of three types:
+
Plain string(s), in which case it's compiled to bytecode before matching.
+
Regex!char (wchar/dchar) that contains a pattern in the form of
+ compiled bytecode.
+
StaticRegex!char (wchar/dchar) that contains a pattern in the form of
+ compiled native machine code.
+
+
+
+
Returns:
RegexMatch object that represents matcher state
+ after the first match was found or an empty one if not present.
+
+
+
auto bmatch(R, RegEx)(R input, RegEx re) if (isSomeString!R && isRegexFor!(RegEx, R));
+
auto bmatch(R, String)(R input, String re) if (isSomeString!R && isSomeString!String);
+
+
Start matching of input to regex pattern re,
+ using traditional backtracking matching scheme.
+
The use of this function is discouraged - use either of
+ matchAll or matchFirst.
+
+
+ Delegating the kind of operation
+ to "g" flag is soon to be phased out along with the
+ ability to choose the exact matching scheme. The choice of
+ matching scheme to use depends highly on the pattern kind and
+ can done automatically on case by case basis.
+
+
+
Returns:
a RegexMatch object holding engine
+ state after first match.
+
+
+
R replaceFirst(R, C, RegEx)(R input, RegEx re, const(C)[] format) if (isSomeString!R && is(C : dchar) && isRegexFor!(RegEx, R));
+
+
Construct a new string from input by replacing the first match with
+ a string generated from it according to the format specifier.
+
R replaceFirst(alias fun, R, RegEx)(R input, RegEx re) if (isSomeString!R && isRegexFor!(RegEx, R));
+
+
This is a general replacement tool that construct a new string by replacing
+ matches of pattern re in the input. Unlike the other overload
+ there is no format string instead captures are passed to
+ to a user-defined functor fun that returns a new string
+ to use as replacement.
+
This version replaces the first match in input,
+ see replaceAll to replace the all of the matches.
+
+
+
Returns:
A new string of the same type as input with all matches
+ replaced by return values of fun. If no matches found
+ returns the input itself.
+
Examples:
import std.conv : to;
+string list = "#21 out of 46";
+string newList = replaceFirst!(cap => to!string(to!int(cap.hit)+1))
+ (list, regex(`[0-9]+`));
+writeln(newList); // "#22 out of 46"
+
+
+
+
+
@trusted void replaceFirstInto(Sink, R, C, RegEx)(ref Sink sink, R input, RegEx re, const(C)[] format) if (isOutputRange!(Sink, dchar) && isSomeString!R && is(C : dchar) && isRegexFor!(RegEx, R));
+
A variation on replaceFirst that instead of allocating a new string
+ on each call outputs the result piece-wise to the sink. In particular
+ this enables efficient construction of a final output incrementally.
+
Like in replaceFirst family of functions there is an overload
+ for the substitution guided by the format string
+ and the one with the user defined callback.
+
Examples:
import std.array;
+string m1 = "first message\n";
+string m2 = "second message\n";
+auto result = appender!string();
+replaceFirstInto(result, m1, regex(`([a-z]+) message`), "$1");
+//equivalent of the above with user-defined callback
+replaceFirstInto!(cap=>cap[1])(result, m2, regex(`([a-z]+) message`));
+writeln(result.data); // "first\nsecond\n"
+
+
+
+
+
@trusted R replaceAll(R, C, RegEx)(R input, RegEx re, const(C)[] format) if (isSomeString!R && is(C : dchar) && isRegexFor!(RegEx, R));
+
+
Construct a new string from input by replacing all of the
+ fragments that match a pattern re with a string generated
+ from the match according to the format specifier.
+
To replace only the first match use replaceFirst.
+
+
+
Parameters:
R input
+
string to search
+
RegEx re
+
compiled regular expression to use
+
const(C)[] format
+
format string to generate replacements from,
+ see the format string.
+
+
Returns:
A string of the same type as input with the all
+ of the matches (if any) replaced.
+ If no match is found returns the input string itself.
@trusted R replaceAll(alias fun, R, RegEx)(R input, RegEx re) if (isSomeString!R && isRegexFor!(RegEx, R));
+
+
This is a general replacement tool that construct a new string by replacing
+ matches of pattern re in the input. Unlike the other overload
+ there is no format string instead captures are passed to
+ to a user-defined functor fun that returns a new string
+ to use as replacement.
+
This version replaces all of the matches found in input,
+ see replaceFirst to replace the first match only.
+
+
+
Returns:
A new string of the same type as input with all matches
+ replaced by return values of fun. If no matches found
+ returns the input itself.
+
+
+
Parameters:
R input
+
string to search
+
RegEx re
+
compiled regular expression
+
fun
+
delegate to use
+
+
Examples:
string baz(Captures!(string) m)
+{
+ import std.string : toUpper;
+ return toUpper(m.hit);
+}
+// Capitalize the letters 'a' and 'r':
+auto s = replaceAll!(baz)("Strap a rocket engine on a chicken.",
+ regex("[ar]"));
+writeln(s); // "StRAp A Rocket engine on A chicken."
+
+
+
+
+
@trusted void replaceAllInto(Sink, R, C, RegEx)(Sink sink, R input, RegEx re, const(C)[] format) if (isOutputRange!(Sink, dchar) && isSomeString!R && is(C : dchar) && isRegexFor!(RegEx, R));
+
A variation on replaceAll that instead of allocating a new string
+ on each call outputs the result piece-wise to the sink. In particular
+ this enables efficient construction of a final output incrementally.
+
As with replaceAll there are 2 overloads - one with a format string,
+ the other one with a user defined functor.
+
Examples:
// insert comma as thousands delimiter in fifty randomly produced big numbers
+import std.array, std.conv, std.random, std.range;
+staticre = regex(`(?<=\d)(?=(\d\d\d)+\b)`, "g");
+autosink = appender!(char [])();
+enumulong min = 10UL ^^ 10, max = 10UL ^^ 19;
+foreach (i; 0 .. 50)
+{
+ sink.clear();
+ replaceAllInto(sink, text(uniform(min, max)), re, ",");
+ foreach (pos; iota(sink.data.length - 4, 0, -4))
+ writeln(sink.data[pos]); // ','
+}
+
+
+
+
+
R replace(alias scheme = match, R, C, RegEx)(R input, RegEx re, const(C)[] format) if (isSomeString!R && isRegexFor!(RegEx, R));
+
R replace(alias fun, R, RegEx)(R input, RegEx re) if (isSomeString!R && isRegexFor!(RegEx, R));
+
+
Old API for replacement, operation depends on flags of pattern re.
+ With "g" flag it performs the equivalent of replaceAll otherwise it
+ works the same as replaceFirst.
+
The use of this function is discouraged, please use replaceAll
+ or replaceFirst explicitly.
+
+
+
struct Splitter(Flag!"keepSeparators" keepSeparators = No.keepSeparators, Range, alias RegEx = Regex) if (isSomeString!Range && isRegexFor!(RegEx, Range));
+
An eager version of splitter that creates an array with splitted slices of input.
+
+
alias RegexException = std.regex.internal.ir.RegexException;
+
+
Exception object thrown in case of errors during regex compilation.
+
+
auto escaper(Range)(Range r);
+
+
A range that lazily produces a string output escaped
+ to be used inside of a regular expression.
Examples:
import std.algorithm.comparison;
+import std.regex;
+string s = `This is {unfriendly} to *regex*`;
+assert(s.escaper.equal(`This is \{unfriendly\} to \*regex\*`));
+
Bitrix Framework - технологическое ядро (платформа) для создания и управления проектами (веб-сайтами и корпоративными порталами). Платформа позволяет создавать неограниченное количество проектов с применением одной копии (лицензии) продукта, размещая ядро и базу данных системы в единственном экземпляре на сервере.
+
+
На данный момент не все возможности старого ядра продублированы в D7. Но новое ядро D7 в Bitrix Framework постепенно замещает старое. Если использование старого ядра привело к предупреждению от IDE: Method/class is deprecated, значит нужно использовать методы D7.
+
+
В силу ряда причин API документация может не охватывать все методы. Для понимания работы иногда лучше просмотреть собственно программный код. Для этого можно использовать бесплатный модуль из Маркетплейса: Живое описание АПИ.
+
+
Данная документация носит только справочный характер. Детальное описание принципов работы с системой описаны в учебном курсе Разработчик Bitrix Framework. Следить за изменениями в документации можно с помощью страницы Что нового?, либо подпиской на канал в Телеграмме, а также в блоге Отдела документации.
+
+
Примечание: добавив к адресу любой страницы #examples можно быстро перейти к примеру, если он на ней есть. (В файлах документации формата CHM это не работает.)
+
+
+
Документация также доступна в виде файла в формате chm: bsm_api.chm. Рекомендуется пользоваться онлайн версией, как более актуальной. Файлы формата chm обновляются периодически, в них может отсутствовать информация по последним изменениям в справочной системе. При возникновении проблем с просмотром скачанного файла chm откройте свойства файла и во вкладке "Общие" нажмите кнопку
+
+ Разблокировать
+
+
+
+
+
+
+
+
+
+ .
+
+
+
Версии сущностей
+
+
Bitrix Framework постоянно развивается. Появляются новые функции, некоторые устаревают, в функциях появляются новые параметры. Однако достаточно большое число проектов не обновляются. Для облегчения программистского труда в документации проставлено с какой и по какую версию продукта класс, метод, параметр, событие существовали (существуют).
+
+
Версии проставляются в двух местах: в названии и в таблицах. Если метод действующий, то в заголовке будет стоять только номер версии с которой он появился в продукте. Если метод устарел, то там же будет указан диапазон версий, где он был действующий.
+
+
В таблицах указывается версия, с которой сущность появилась в продукте, только в том случае, если её появление не совпадает с моментом появления самого класса, метода и так далее.
+На иллюстрации ниже: параметр COURSE_ID появился вместе с методом (то есть с 5.1.0), а параметр CHAPTER_ID только с версии 9.5.4.
+
+
Если с развитием продукта параметр (обычно это относится к параметрам) изменялся, то будет соответствующее примечание в его описании. (Например: до версии х.х.х параметр назывался *****).
+
+
Пример
+
+
+
+
Примечания:
+
+
Отметка Устарел у метода, параметра, ключа означает, что его не рекомендуется использовать так как расширений и исправлений не будет.
+
Простановка версий выполнена не полностью, работы в этом направлении ведутся в данный момент.
Quickly fork, edit online, and submit a pull request for this page.
+ Requires a signed-in GitHub account. This works well for small changes.
+ If you'd like to make larger changes you may want to consider using
+ a local clone.
+
+
+
+
std.experimental.logger
+
+
This module is now deprecated, use std.logger
+ instead.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/docs/rebuild-v2/raw/outbound/7c3728c1412f6888.txt b/docs/rebuild-v2/raw/outbound/7c3728c1412f6888.txt
new file mode 100644
index 0000000..70e03af
--- /dev/null
+++ b/docs/rebuild-v2/raw/outbound/7c3728c1412f6888.txt
@@ -0,0 +1,21897 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+# This file defines static prefs, i.e. those that are defined at startup and
+# used entirely or mostly from C++ and/or Rust code.
+#
+# The file is separated into sections, where each section contains a group of
+# prefs that all share the same first segment of their name -- all the "gfx.*"
+# prefs are together, all the "network.*" prefs are together, etc. Sections
+# must be kept in alphabetical order, but prefs within sections need not be.
+#
+# Basics
+# ------
+# Any pref defined in one of the files included here should *not* be defined
+# in a data file such as all.js; that would just be useless duplication.
+#
+# (Except under unusual circumstances where the value defined here must be
+# overridden, e.g. for some Thunderbird prefs. In those cases the default
+# value from the data file will override the static default value defined
+# here.)
+#
+# Please follow the existing prefs naming convention when considering adding a
+# new pref, and don't create a new pref group unless it's appropriate and there
+# are likely to be multiple prefs within that group. (If you do, you'll need to
+# update the `pref_groups` variable in modules/libpref/moz.build.)
+#
+# Definitions
+# -----------
+# A pref definition looks like this:
+#
+# - name: # mandatory
+# type: # mandatory
+# value: # mandatory
+# mirror: # mandatory
+# do_not_use_directly: # optional
+# include: # optional
+# rust: # optional
+# set_spidermonkey_pref: # optional
+#
+# - `name` is the name of the pref, without double-quotes, as it appears
+# in about:config. It is used in most libpref API functions (from both C++
+# and JS code).
+#
+# - `type` is one of `bool`, `int32_t`, `uint32_t`, `float`, an atomic version
+# of one of those, `String` or `DataMutexString`. Note that float prefs are
+# stored internally as strings. The C++ preprocessor doesn't like template
+# syntax in a macro argument, so use the typedefs defined in
+# StaticPrefsBase.h; for example, use `RelaxedAtomicBool` instead of
+# `Atomic`.
+#
+# - `value` is the default value. Its type should be appropriate for
+# , otherwise the generated code will fail to compile. A complex
+# C++ numeric expressions like `60 * 60` (which the YAML parser cannot treat
+# as an integer or float) is treated as a string and passed through without
+# change, which is useful.
+#
+# - `mirror` indicates how the pref value is mirrored into a C++ variable.
+#
+# * `never`: There is no C++ mirror variable. The pref value can only be
+# accessed via the standard libpref API functions.
+#
+# * `once`: The pref value is mirrored into a variable at startup; the
+# mirror variable is left unchanged after that. (The exact point at which
+# all `once` mirror variables are set is when the first `once` mirror
+# variable is accessed, via its getter function.) This is mostly useful for
+# graphics prefs where we often don't want a new pref value to apply until
+# restart. Otherwise, this update policy is best avoided because its
+# behaviour can cause confusion and bugs.
+#
+# * `always`: The mirror variable is always kept in sync with the pref value.
+# This is the most common choice.
+#
+# When a mirror variable is present, a getter will be created that can access
+# it. Using the getter function to read the pref's value has the two
+# following advantages over the normal API functions.
+#
+# * A direct variable access is faster than a hash table lookup.
+#
+# * A mirror variable can be accessed off the main thread. If a pref *is*
+# accessed off the main thread, it should have an atomic type. Assertions
+# enforce this.
+#
+# Note that Rust code must access the mirror variable directly, rather than
+# via the getter function.
+#
+# - `do_not_use_directly` indicates if `_DoNotUseDirectly` should be appended to
+# the name of the getter function. This is simply a naming convention
+# indicating that there is some other wrapper getter function that should be
+# used in preference to the normal static pref getter. Defaults to `false` if
+# not present. Cannot be used with a `never` mirror value, because there is
+# no getter function in that case.
+#
+# - `include` names a header file that must be included for the pref value to
+# compile correctly, e.g. because it refers to a code constant. System
+# headers should be surrounded with angle brackets, e.g. ``.
+#
+# - `rust` indicates if the mirror variable is used by Rust code. If so, it
+# will be usable via the `static_prefs::pref!` macro, e.g.
+# `static_prefs::pref!("layout.css.cross-fade.enabled")`.
+#
+# - `set_spidermonkey_pref` indicates whether SpiderMonkey boilerplate code
+# should be generated for this pref. If this is set to 'startup', the
+# pref on the SpiderMonkey side is only set during process startup. If set to
+# 'always', the SpiderMonkey pref value is also updated when this pref is
+# changed at runtime.
+# This option is only valid for javascript.options.* prefs.
+#
+# - `fuzzing_safe` indicates whether the SpiderMonkey pref is safe to toggle
+# while fuzzing. Defaults to `true`. When set to `false`, the JS shell ignores
+# attempts to change the pref while running with --fuzzing-safe.
+# This option is only valid for prefs with `set_spidermonkey_pref`.
+#
+# The getter function's base name is the same as the pref's name, but with
+# '.' or '-' chars converted to '_', to make a valid identifier. For example,
+# the getter for `foo.bar_baz` is `foo_bar_baz()`. This is ugly but clear,
+# and you can search for both the pref name and the getter using the regexp
+# /foo.bar.baz/. Suffixes are added as follows:
+#
+# - If the `mirror` value is `once`, `_AtStartup` is appended, to indicate the
+# value was obtained at startup.
+#
+# - If the `do_not_use_directly` value is true, `_DoNotUseDirectly` is
+# appended.
+#
+# Preprocessor
+# ------------
+# Note finally that this file is preprocessed by preprocessor.py, not the C++
+# preprocessor. As a result, the following things may be surprising.
+#
+# - YAML comments start with a '#', so putting a comment on the same line as a
+# preprocessor directive is dubious. E.g. avoid lines like `#define X 3 #
+# three` because the ` # three` will be part of `X`.
+#
+# - '@' use is required for substitutions to occur. E.g. with `#define FOO 1`,
+# `FOO` won't be replaced with `1` unless it has '@' chars around it.
+#
+# - Spaces aren't permitted between the leading '#' and the name of a
+# directive, e.g. `#ifdef XYZ` works but `# ifdef XYZ` does not.
+#
+# Please indent all prefs defined within #ifdef/#ifndef conditions. This
+# improves readability, particular for conditional blocks that exceed a single
+# screen. But note that the leading '-' in a definition must remain in the
+# first column for it to be valid YAML.
+
+#ifdef RELEASE_OR_BETA
+#define IS_NOT_RELEASE_OR_BETA false
+#else
+#define IS_NOT_RELEASE_OR_BETA true
+#endif
+
+#ifdef NIGHTLY_BUILD
+#define IS_NIGHTLY_BUILD true
+#define IS_NOT_NIGHTLY_BUILD false
+#else
+#define IS_NIGHTLY_BUILD false
+#define IS_NOT_NIGHTLY_BUILD true
+#endif
+
+#if defined(NIGHTLY_BUILD) || defined(MOZ_DEV_EDITION)
+#define IS_NIGHTLY_OR_DEV_EDITION true
+#else
+#define IS_NIGHTLY_OR_DEV_EDITION false
+#endif
+
+#ifdef MOZILLA_OFFICIAL
+#define IS_NOT_MOZILLA_OFFICIAL false
+#else
+#define IS_NOT_MOZILLA_OFFICIAL true
+#endif
+
+#ifdef EARLY_BETA_OR_EARLIER
+#define IS_EARLY_BETA_OR_EARLIER true
+#define IS_NOT_EARLY_BETA_OR_EARLIER false
+#else
+#define IS_EARLY_BETA_OR_EARLIER false
+#define IS_NOT_EARLY_BETA_OR_EARLIER true
+#endif
+
+#if defined(MOZ_DEV_EDITION) || defined(EARLY_BETA_OR_EARLIER)
+#define IS_DEV_EDITION_OR_EARLY_BETA_OR_EARLIER true
+#else
+#define IS_DEV_EDITION_OR_EARLY_BETA_OR_EARLIER false
+#endif
+
+#ifdef ANDROID
+#define IS_ANDROID true
+#define IS_NOT_ANDROID false
+#else
+#define IS_ANDROID false
+#define IS_NOT_ANDROID true
+#endif
+
+#ifdef XP_WIN
+#define IS_XP_WIN true
+#define IS_NOT_XP_WIN false
+#else
+#define IS_XP_WIN false
+#define IS_NOT_XP_WIN true
+#endif
+
+#ifdef XP_MACOSX
+#define IS_XP_MACOSX true
+#define IS_NOT_XP_MACOSX false
+#else
+#define IS_XP_MACOSX false
+#define IS_NOT_XP_MACOSX true
+#endif
+
+#ifdef XP_IOS
+#define IS_IOS true
+#define IS_NOT_IOS false
+#else
+#define IS_IOS false
+#define IS_NOT_IOS true
+#endif
+
+#if defined(ANDROID) || defined(XP_IOS)
+#define IS_MOBILE true
+#define IS_NOT_MOBILE false
+#else
+#define IS_MOBILE false
+#define IS_NOT_MOBILE true
+#endif
+
+#---------------------------------------------------------------------------
+# Prefs starting with "accessibility."
+#---------------------------------------------------------------------------
+
+# Tab focus model bit field:
+# 1 focuses text controls, 2 focuses other form elements, 4 adds links.
+# Most users will want 1, 3, or 7. On macOS we expose a checkbox to alter
+# between 7 and 3.
+- name: accessibility.tabfocus
+ type: int32_t
+ value: 7
+ mirror: always
+
+# Only on mac tabfocus is expected to handle UI widgets as well as web content.
+# FIXME(emilio): This is weird now that we have a lot of HTML in our pages.
+- name: accessibility.tabfocus_applies_to_xul
+ type: bool
+ value: @IS_XP_MACOSX@
+ mirror: always
+
+- name: accessibility.accesskeycausesactivation
+ type: bool
+ value: true
+ mirror: always
+
+- name: accessibility.monoaudio.enable
+ type: RelaxedAtomicBool
+ value: false
+ mirror: always
+
+- name: accessibility.browsewithcaret
+ type: RelaxedAtomicBool
+ value: false
+ mirror: always
+
+- name: accessibility.AOM.enabled
+ type: bool
+ value: false
+ mirror: always
+
+# Whether to enable automatic details relationships for
+# anchor positioned content.
+- name: accessibility.anchorPositionedAsDetails.enabled
+ type: bool
+ value: false
+ mirror: always
+
+- name: accessibility.ariaNotify.enabled
+ type: bool
+ value: true
+ mirror: always
+
+# Whether to enable all accessibility cache domains on startup.
+# * false: enable domains as needed
+# * true: enable all domains regardless of need (cache everything)
+- name: accessibility.enable_all_cache_domains
+ type: bool
+ value: false
+ mirror: once
+
+# Whether form controls and images should be focusable with mouse, in content
+# documents.
+#
+# This matches historical macOS / Safari behavior.
+#
+# * 0: never
+# * 1: always
+# * 2: on content documents
+- name: accessibility.mouse_focuses_formcontrol
+ type: int32_t
+#ifdef XP_MACOSX
+ value: 2
+#else
+ value: 1
+#endif
+ mirror: always
+
+- name: accessibility.tagged_pdf_output.enabled
+ type: bool
+ value: true
+ mirror: always
+
+# Whether to enable support for the UI Automation API on Windows. Values:
+# * 0: Never.
+# * 1: Always.
+# * 2: Enable unless incompatible accessibility clients are detected.
+- name: accessibility.uia.enable
+ type: uint32_t
+ value: 2
+ mirror: always
+ do_not_use_directly: true
+
+#ifdef XP_WIN
+# Whether to avoid accessibility activation on Windows shortly after clipboard
+# copy.
+#
+# Possible values are:
+# * 0: never
+# * 1: always
+# * 2 (or others): when needed
+- name: accessibility.windows.suppress-after-clipboard-copy
+ type: uint32_t
+ value: 2
+ mirror: always
+
+# Whether to avoid accessibility activation on Windows shortly after max button
+# hit-test for the "snap layout" feature.
+#
+# Possible values are:
+# * 0: never
+# * 1: always
+# * 2 (or others): when needed
+- name: accessibility.windows.suppress-for-snap-layout
+ type: uint32_t
+ value: 2
+ mirror: always
+#endif
+
+#---------------------------------------------------------------------------
+# Prefs starting with "alerts."
+#---------------------------------------------------------------------------
+
+# Whether to use platform-specific backends for showing desktop notifications.
+# If no such backend is available, or if the pref is false, then XUL
+# notifications are used.
+- name: alerts.useSystemBackend
+ type: bool
+ value: true
+ mirror: always
+
+#if defined(XP_WIN)
+ # On Windows, a COM Surrogate notification server receives notification events
+ # and can relaunch the application after it has been closed.
+- name: alerts.useSystemBackend.windows.notificationserver.enabled
+ type: bool
+ value: true
+ mirror: never
+#endif
+
+#ifdef ANDROID
+ #---------------------------------------------------------------------------
+ # Prefs starting with "android."
+ #---------------------------------------------------------------------------
+
+ # On Android, we want an opaque background to be visible under the page,
+ # so layout should not force a default background.
+- name: android.widget_paints_background
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+
+- name: android.touch_resampling.enabled
+ type: RelaxedAtomicBool
+ value: false
+ mirror: always
+
+#endif
+
+#---------------------------------------------------------------------------
+# Prefs starting with "apz."
+# The apz prefs are explained in AsyncPanZoomController.cpp
+#---------------------------------------------------------------------------
+
+# amount we zoom in for a double tap gesture if we couldn't find any content
+# based rect to zoom to
+- name: apz.doubletapzoom.defaultzoomin
+ type: AtomicFloat
+ value: 1.2f
+ mirror: always
+
+# After a user has executed a pan gesture, we may receive momentum phase pan
+# gestures from the OS. This specifies how long we should wait following the
+# pan end gesture for possible momentum phase pan gestures before sending the
+# TransformEnd notification.
+- name: apz.scrollend-event.content.delay_ms
+ type: RelaxedAtomicInt32
+ value: 100
+ mirror: always
+
+- name: apz.wr.activate_all_scroll_frames
+ type: RelaxedAtomicBool
+ value: false
+ mirror: always
+
+- name: apz.wr.activate_all_scroll_frames_when_fission
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+
+- name: apz.prefer_jank_minimal_displayports
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+
+- name: apz.allow_double_tap_zooming
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+
+#ifdef XP_MACOSX
+- name: apz.mac.enable_double_tap_zoom_touchpad_gesture
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+#endif
+
+- name: apz.allow_immediate_handoff
+ type: RelaxedAtomicBool
+ value: false
+ mirror: always
+
+- name: apz.allow_zooming
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+
+- name: apz.max_zoom
+ type: AtomicFloat
+ value: 10.0f
+ mirror: always
+
+- name: apz.min_zoom
+ type: AtomicFloat
+ value: 0.25f
+ mirror: always
+
+- name: apz.allow_zooming_out
+ type: RelaxedAtomicBool
+ value: false
+ mirror: always
+
+#ifdef ANDROID
+- name: apz.android.chrome_fling_physics.friction
+ type: AtomicFloat
+ value: 0.015f
+ mirror: always
+
+- name: apz.android.chrome_fling_physics.inflexion
+ type: AtomicFloat
+ value: 0.35f
+ mirror: always
+
+- name: apz.android.chrome_fling_physics.stop_threshold
+ type: AtomicFloat
+ value: 0.1f
+ mirror: always
+#endif
+
+- name: apz.autoscroll.enabled
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+
+- name: apz.autoscroll.scroll_wheel_cooldown
+ type: RelaxedAtomicInt32
+ value: 500
+ mirror: always
+
+- name: apz.axis_lock.breakout_angle
+ type: AtomicFloat
+ value: float(M_PI / 8.0) # 22.5 degrees
+ mirror: always
+ include:
+
+- name: apz.axis_lock.breakout_threshold
+ type: AtomicFloat
+ value: 1.0f / 32.0f
+ mirror: always
+
+- name: apz.axis_lock.direct_pan_angle
+ type: AtomicFloat
+ value: float(M_PI / 3.0) # 60 degrees
+ mirror: always
+ include:
+
+- name: apz.axis_lock.lock_angle
+ type: AtomicFloat
+ value: float(M_PI / 6.0) # 30 degrees
+ mirror: always
+ include:
+
+# Whether to lock touch scrolling to one axis at a time. When a new
+# axis lock mode is added, the APZCAxisLockCompatTester GTest shoud
+# be updated to include the lock mode value.
+# 0 = FREE (No locking at all)
+# 1 = STANDARD (Once locked, remain locked until scrolling ends)
+# 2 = STICKY (Allow lock to be broken, with hysteresis)
+# 3 = DOMINANT_AXIS (Only allow movement on one axis at a time, only
+# applies to touchpad scrolling)
+- name: apz.axis_lock.mode
+ type: RelaxedAtomicInt32
+ value: 2
+ mirror: always
+
+- name: apz.content_response_timeout
+ type: RelaxedAtomicInt32
+ value: 400
+ mirror: always
+
+- name: apz.danger_zone_x
+ type: RelaxedAtomicInt32
+ value: 50
+ mirror: always
+
+- name: apz.danger_zone_y
+ type: RelaxedAtomicInt32
+ value: 100
+ mirror: always
+
+- name: apz.disable_for_scroll_linked_effects
+ type: RelaxedAtomicBool
+ value: false
+ mirror: always
+
+- name: apz.displayport_expiry_ms
+ type: RelaxedAtomicUint32
+ value: 15000
+ mirror: always
+
+- name: apz.drag.enabled
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+
+- name: apz.drag.touch.enabled
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+
+- name: apz.enlarge_displayport_when_clipped
+ type: RelaxedAtomicBool
+ value: @IS_ANDROID@
+ mirror: always
+
+# Fast-path notify APZ on non-passive APZ-aware listener registration,
+# without waiting for the next paint.
+- name: apz.fastpath_apz_aware_listener.enabled
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+
+# Test only.
+- name: apz.fixed-margin-override.enabled
+ type: RelaxedAtomicBool
+ value: false
+ mirror: always
+
+# Test only.
+- name: apz.fixed-margin-override.bottom
+ type: RelaxedAtomicInt32
+ value: 0
+ mirror: always
+
+# Test only.
+- name: apz.fixed-margin-override.top
+ type: RelaxedAtomicInt32
+ value: 0
+ mirror: always
+
+- name: apz.fling_accel_base_mult
+ type: AtomicFloat
+ value: 1.0f
+ mirror: always
+
+- name: apz.fling_accel_supplemental_mult
+ type: AtomicFloat
+ value: 1.0f
+ mirror: always
+
+- name: apz.fling_accel_min_fling_velocity
+ type: AtomicFloat
+ value: 1.5f
+ mirror: always
+
+- name: apz.fling_accel_min_pan_velocity
+ type: AtomicFloat
+ value: 0.8f
+ mirror: always
+
+- name: apz.fling_accel_max_pause_interval_ms
+ type: RelaxedAtomicInt32
+ value: 50
+ mirror: always
+
+- name: apz.fling_curve_function_x1
+ type: float
+ value: 0.0f
+ mirror: once
+
+- name: apz.fling_curve_function_x2
+ type: float
+ value: 1.0f
+ mirror: once
+
+- name: apz.fling_curve_function_y1
+ type: float
+ value: 0.0f
+ mirror: once
+
+- name: apz.fling_curve_function_y2
+ type: float
+ value: 1.0f
+ mirror: once
+
+- name: apz.fling_curve_threshold_inches_per_ms
+ type: AtomicFloat
+ value: -1.0f
+ mirror: always
+
+- name: apz.fling_friction
+ type: AtomicFloat
+ value: 0.002f
+ mirror: always
+
+- name: apz.fling_min_velocity_threshold
+ type: AtomicFloat
+ value: 0.5f
+ mirror: always
+
+- name: apz.fling_stop_on_tap_threshold
+ type: AtomicFloat
+ value: 0.05f
+ mirror: always
+
+- name: apz.fling_stopped_threshold
+ type: AtomicFloat
+ value: 0.01f
+ mirror: always
+
+- name: apz.touch_acceleration_factor_x
+ type: float
+ value: 1.0f
+ mirror: always
+
+- name: apz.touch_acceleration_factor_y
+ type: float
+ value: 1.0f
+ mirror: always
+
+#ifdef MOZ_WIDGET_GTK
+- name: apz.gtk.kinetic_scroll.enabled
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+
+- name: apz.gtk.pangesture.enabled
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+
+# Mode to use when receiving pan gesture input.
+#
+# * 0: Auto mode (uses the default behavior, subject to change).
+# * 1: Page mode: Uses gtk deltas as a percentage of the page size to scroll. This mode matches:
+#
+# https://gitlab.gnome.org/GNOME/gtk/blob/c734c7e9188b56f56c3a504abee05fa40c5475ac/gtk/gtkrange.c#L3063-3074
+#
+# * 2: Pixel mode: Uses gtk deltas as a fixed pixel multiplier. This mode matches e.g. GNOME web.
+#
+# https://webkit-search.igalia.com/webkit/rev/215039ef09d6bfd6e088175bfe30788d95b9705d/Source/WebKit/Shared/gtk/WebEventFactory.cpp#265-296
+# (multiplied then by pixelsPerLineStep which in GNOME-web is 40).
+- name: apz.gtk.pangesture.delta_mode
+ type: uint32_t
+ value: 0
+ mirror: always
+
+- name: apz.gtk.pangesture.page_delta_mode_multiplier
+ type: float
+ value: 1.0f
+ mirror: always
+
+- name: apz.gtk.pangesture.pixel_delta_mode_multiplier
+ type: float
+ value: 40.0f
+ mirror: always
+
+- name: apz.gtk.touchpad_pinch.enabled
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+
+- name: apz.gtk.touchpad_pinch.three_fingers.enabled
+ type: RelaxedAtomicBool
+ value: false
+ mirror: always
+
+- name: apz.gtk.touchpad_hold.enabled
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+#endif
+
+- name: apz.keyboard.enabled
+ type: bool
+ value: @IS_NOT_MOBILE@
+ mirror: once
+
+- name: apz.keyboard.passive-listeners
+ type: RelaxedAtomicBool
+ value: @IS_NOT_MOBILE@
+ mirror: always
+
+- name: apz.keyboard.focus-optimization
+ type: bool
+ value: false
+ mirror: always
+
+- name: apz.max_tap_time
+ type: RelaxedAtomicInt32
+ value: 300
+ mirror: always
+
+- name: apz.max_velocity_inches_per_ms
+ type: AtomicFloat
+ value: -1.0f
+ mirror: always
+
+- name: apz.max_velocity_queue_size
+ type: uint32_t
+ value: 5
+ mirror: once
+
+- name: apz.min_skate_speed
+ type: AtomicFloat
+ value: 1.0f
+ mirror: always
+
+- name: apz.minimap.enabled
+ type: RelaxedAtomicBool
+ value: false
+ mirror: always
+
+- name: apz.mousemove_hittest_optimization.enabled
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+
+- name: apz.one_touch_pinch.enabled
+ type: RelaxedAtomicBool
+ value: @IS_ANDROID@
+ mirror: always
+
+- name: apz.overscroll.enabled
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+
+# The "test async scroll offset" (used via reftest-async-scroll
+# or nsIDOMWindowUtils.setAsyncScrollOffset()) can be used to
+# trigger overscroll. Used for tests only.
+- name: apz.overscroll.test_async_scroll_offset.enabled
+ type: RelaxedAtomicBool
+ value: false
+ mirror: always
+
+- name: apz.overscroll.min_pan_distance_ratio
+ type: AtomicFloat
+ value: 1.0f
+ mirror: always
+
+- name: apz.overscroll.stop_distance_threshold
+ type: AtomicFloat
+ value: 5.0f
+ mirror: always
+
+- name: apz.overscroll.spring_stiffness
+ type: AtomicFloat
+ value: 200
+ mirror: always
+
+- name: apz.overscroll.damping
+ type: AtomicFloat
+ value: 1.1
+ mirror: always
+
+- name: apz.overscroll.max_velocity
+ type: AtomicFloat
+ value: 10
+ mirror: always
+
+- name: apz.paint_skipping.enabled
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+
+# Fetch displayport updates early from the message queue.
+- name: apz.pinch_lock.mode
+ type: RelaxedAtomicInt32
+ value: 2
+ mirror: always
+
+- name: apz.pinch_lock.scroll_lock_threshold
+ type: AtomicFloat
+ value: 1.0f / 16.0f # 1/16 inches
+ mirror: always
+
+- name: apz.pinch_lock.span_breakout_threshold
+ type: AtomicFloat
+ value: 1.0f / 32.0f # 1/32 inches
+ mirror: always
+
+- name: apz.pinch_lock.span_lock_threshold
+ type: AtomicFloat
+ value: 1.0f / 32.0f # 1/32 inches
+ mirror: always
+
+- name: apz.pinch_lock.buffer_max_age
+ type: uint32_t
+ value: 80 # milliseconds
+ mirror: once
+
+- name: apz.popups.enabled
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+
+- name: apz.popups_without_remote.enabled
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+
+# Whether to print the APZC tree for debugging.
+- name: apz.printtree
+ type: RelaxedAtomicBool
+ value: false
+ mirror: always
+
+- name: apz.record_checkerboarding
+ type: RelaxedAtomicBool
+ value: @IS_NIGHTLY_BUILD@
+ mirror: always
+
+- name: apz.second_tap_tolerance
+ type: AtomicFloat
+ value: 0.5f
+ mirror: always
+
+# If this is true, APZ fully recalculates the scroll thumb size and
+# position in the compositor. This leads to the size and position
+# being more accurate in scenarios such as async zooming.
+- name: apz.scrollthumb.recalc
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+
+- name: apz.test.fails_with_native_injection
+ type: RelaxedAtomicBool
+ value: false
+ mirror: always
+
+- name: apz.test.logging_enabled
+ type: RelaxedAtomicBool
+ value: false
+ mirror: always
+
+- name: apz.touch_move_tolerance
+ type: AtomicFloat
+ value: 0.1f
+ mirror: always
+
+- name: apz.touch_scroll.buffer_max_age
+ type: uint32_t
+ value: 200 # milliseconds
+ mirror: once
+
+- name: apz.touch_start_tolerance
+ type: AtomicFloat
+ value: 0.1f
+ mirror: always
+
+- name: apz.velocity_bias
+ type: AtomicFloat
+ value: 0.0f
+ mirror: always
+
+- name: apz.velocity_relevance_time_ms
+ type: RelaxedAtomicUint32
+ value: 100
+ mirror: always
+
+#ifdef XP_WIN
+- name: apz.windows.force_disable_direct_manipulation
+ type: RelaxedAtomicBool
+ value: false
+ mirror: always
+
+- name: apz.windows.check_for_pan_gesture_conversion
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+#endif
+
+- name: apz.x_skate_highmem_adjust
+ type: AtomicFloat
+ value: 0.0f
+ mirror: always
+
+- name: apz.x_skate_size_multiplier
+ type: AtomicFloat
+ value: 1.25f
+ mirror: always
+
+- name: apz.x_stationary_size_multiplier
+ type: AtomicFloat
+ value: 1.5f
+ mirror: always
+
+- name: apz.y_skate_highmem_adjust
+ type: AtomicFloat
+ value: 0.0f
+ mirror: always
+
+- name: apz.y_skate_size_multiplier
+ type: AtomicFloat
+#if defined(MOZ_WIDGET_ANDROID)
+ value: 1.5f
+#else
+ value: 3.5f
+#endif
+ mirror: always
+
+- name: apz.y_stationary_size_multiplier
+ type: AtomicFloat
+#if defined(MOZ_WIDGET_ANDROID)
+ value: 1.5f
+#else
+ value: 3.5f
+#endif
+ mirror: always
+
+- name: apz.zoom_animation_duration_ms
+ type: RelaxedAtomicInt32
+#if defined(MOZ_WIDGET_ANDROID)
+ value: 250
+#else
+ value: 350
+#endif
+ mirror: always
+
+- name: apz.scale_repaint_delay_ms
+ type: RelaxedAtomicInt32
+ value: 500
+ mirror: always
+
+# Whether to async scroll CSS anchor pos.
+- name: apz.async_scroll_css_anchor_pos
+ type: bool
+ value: true
+ mirror: once
+
+#---------------------------------------------------------------------------
+# Prefs starting with "beacon."
+#---------------------------------------------------------------------------
+
+# Should navigator.sendBeacon() actually send requests?
+# When false, sendBeacon() is still exposed and still reports success, but
+# no request is sent.
+- name: beacon.enabled
+ type: bool
+ value: true
+ mirror: always
+
+#---------------------------------------------------------------------------
+# Prefs starting with "bidi."
+#---------------------------------------------------------------------------
+
+# Whether delete and backspace should immediately delete characters not
+# visually adjacent to the caret, or adjust the visual position of the caret
+# on the first keypress and delete the character on a second keypress
+- name: bidi.edit.delete_immediately
+ type: bool
+ value: true
+ mirror: always
+
+# Bidi caret movement style:
+# 0 = logical
+# 1 = visual
+# 2 = visual, but logical during selection
+- name: bidi.edit.caret_movement_style
+ type: int32_t
+#if !defined(XP_LINUX) && defined(NIGHTLY_BUILD)
+ value: 1
+#else
+ value: 2 # See Bug 1638240
+#endif
+ mirror: always
+
+# Bidi numeral style:
+# 0 = nominalnumeralBidi *
+# 1 = regularcontextnumeralBidi
+# 2 = hindicontextnumeralBidi
+# 3 = arabicnumeralBidi
+# 4 = hindinumeralBidi
+# 5 = persiancontextnumeralBidi
+# 6 = persiannumeralBidi
+- name: bidi.numeral
+ type: RelaxedAtomicUint32
+ value: 0
+ mirror: always
+
+# Bidi text type
+# 1 = charsettexttypeBidi *
+# 2 = logicaltexttypeBidi
+# 3 = visualtexttypeBidi
+- name: bidi.texttype
+ type: RelaxedAtomicUint32
+ value: 1
+ mirror: always
+
+# Bidi direction
+# 1 = directionLTRBidi *
+# 2 = directionRTLBidi
+- name: bidi.direction
+ type: RelaxedAtomicUint32
+ value: 1
+ mirror: always
+
+# Setting this pref to |true| forces Bidi UI menu items and keyboard shortcuts
+# to be exposed, and enables the directional caret hook. By default, only
+# expose it for bidi-associated system locales.
+- name: bidi.browser.ui
+ type: bool
+ value: false
+ mirror: always
+
+#---------------------------------------------------------------------------
+# Prefs starting with "browser."
+#---------------------------------------------------------------------------
+
+- name: browser.active_color
+ type: String
+ value: "#EE0000"
+ mirror: never
+
+- name: browser.active_color.dark
+ type: String
+ value: "#FF6666"
+ mirror: never
+
+# When set, every alert with an actionable (content) principal that is shown or
+# closed is reported to the parent-process observer service, on the topics
+# "web-notification-shown" and "web-notification-closed", with the
+# nsIAlertNotification as the subject. Private-browsing alerts are never
+# reported. Reporting is inert unless something registers for the topics; this
+# is a kill switch for that capability, not a feature gate, and no consumer
+# should write it. Consumers gate themselves.
+- name: browser.alerts.capture.enabled
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+
+- name: browser.anchor_color
+ type: String
+ value: "#0000EE"
+ mirror: never
+
+# If you change this, you probably also want to change
+# nsXPLookAndFeel::GenericDarkColor for Linktext.
+- name: browser.anchor_color.dark
+ type: String
+ value: "#00CADB"
+ mirror: never
+
+# See http://dev.w3.org/html5/spec/forms.html#attr-fe-autofocus
+- name: browser.autofocus
+ type: bool
+ value: true
+ mirror: always
+
+- name: browser.cache.disk.enable
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+
+# Whether to encrypt HTTP disk cache data at rest. The key is a data encryption
+# key held by the profile keystore (security/lockstore); the decrypted cache
+# content only ever lives in memory. Off by default; takes effect on restart.
+# Read via CacheCrypto::IsEnabled(), which caches the value on first use so it
+# is stable for the session.
+- name: browser.cache.disk.encryption.enabled
+ type: RelaxedAtomicBool
+ value: false
+ mirror: always
+
+# Minimum number of unwritten changes before the disk cache index is written
+# back to disk. Lowering it (e.g. to 1) forces the index to be persisted
+# eagerly; intended for tests.
+- name: browser.cache.disk.index.min_unwritten_changes
+ type: RelaxedAtomicUint32
+ value: 300
+ mirror: always
+
+# Minimum delay in milliseconds between two disk cache index writes. Lowering it
+# (e.g. to 0) forces the index to be persisted eagerly; intended for tests.
+- name: browser.cache.disk.index.min_dump_interval_ms
+ type: RelaxedAtomicUint32
+ value: 20000
+ mirror: always
+
+# Maximum delay in milliseconds before the disk cache index is written back when
+# there is at least one dirty entry, regardless of min_unwritten_changes. This
+# bounds how much recently-updated frecency can be lost on a crash or Android
+# process kill under light browsing. Must be >= min_dump_interval_ms.
+- name: browser.cache.disk.index.max_dump_interval_ms
+ type: RelaxedAtomicUint32
+ value: 60000
+ mirror: always
+
+# Delay in milliseconds after startup before the disk cache index build/update
+# process is started. Lowering it (e.g. to 0) makes the index reach the ready
+# state sooner; intended for tests.
+- name: browser.cache.disk.index.update_start_delay_ms
+ type: RelaxedAtomicUint32
+ value: 50000
+ mirror: always
+
+- name: browser.cache.memory.enable
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+
+# Limit of recent metadata we keep in memory for faster access, in KB.
+- name: browser.cache.disk.metadata_memory_limit
+ type: RelaxedAtomicUint32
+ value: 1024 # 1 MB
+ mirror: always
+
+# Does the user want smart-sizing?
+- name: browser.cache.disk.smart_size.enabled
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+
+# Disk cache capacity in kilobytes. It's used only when
+# browser.cache.disk.smart_size.enabled == false
+- name: browser.cache.disk.capacity
+ type: RelaxedAtomicUint32
+ value: 256000
+ mirror: always
+
+# -1 = determine dynamically, 0 = none, n = memory capacity in kilobytes.
+- name: browser.cache.memory.capacity
+ type: RelaxedAtomicInt32
+ value: -1
+ mirror: always
+
+# When smartsizing is disabled we could potentially fill all disk space by
+# cache data when the disk capacity is not set correctly. To avoid that we
+# check the free space every time we write some data to the cache. The free
+# space is checked against two limits. Once the soft limit is reached we start
+# evicting the least useful entries, when we reach the hard limit writing to
+# the entry fails.
+- name: browser.cache.disk.free_space_soft_limit
+ type: RelaxedAtomicUint32
+ value: 5 * 1024 # 5MB
+ mirror: always
+
+- name: browser.cache.disk.free_space_hard_limit
+ type: RelaxedAtomicUint32
+ value: 1024 # 1MB
+ mirror: always
+
+# The number of chunks we preload ahead of read. One chunk currently has
+# 256kB.
+- name: browser.cache.disk.preload_chunk_count
+ type: RelaxedAtomicUint32
+ value: 4 # 1 MB of read ahead
+ mirror: always
+
+# Max-size (in KB) for entries in disk cache. Set to -1 for no limit.
+# (Note: entries bigger than 1/8 of disk-cache are never cached)
+- name: browser.cache.disk.max_entry_size
+ type: RelaxedAtomicUint32
+ value: 50 * 1024 # 50 MB
+ mirror: always
+
+# Max-size (in KB) for entries in memory cache. Set to -1 for no limit.
+# (Note: entries bigger than than 90% of the mem-cache are never cached.)
+- name: browser.cache.memory.max_entry_size
+ type: RelaxedAtomicInt32
+ value: 5 * 1024
+ mirror: always
+
+# Memory limit (in kB) for new cache data not yet written to disk. Writes to
+# the cache are buffered and written to disk on background with low priority.
+# With a slow persistent storage these buffers may grow when data is coming
+# fast from the network. When the amount of unwritten data is exceeded, new
+# writes will simply fail. We have two buckets, one for important data
+# (priority) like html, css, fonts and js, and one for other data like images,
+# video, etc.
+# Note: 0 means no limit.
+- name: browser.cache.disk.max_chunks_memory_usage
+ type: RelaxedAtomicUint32
+ value: 40 * 1024
+ mirror: always
+- name: browser.cache.disk.max_priority_chunks_memory_usage
+ type: RelaxedAtomicUint32
+ value: 40 * 1024
+ mirror: always
+
+
+# Number of seconds the cache spends writing pending data and closing files
+# after shutdown has been signalled. Past that time data is not written and
+# files are left open for the OS to clean up.
+- name: browser.cache.max_shutdown_io_lag
+ type: RelaxedAtomicUint32
+ value: 2
+ mirror: always
+
+# After the max_shutdown_io_lag has passed, we will attempt to cancel
+# blocking IO (on windows). The CacheIOThread may pick up more blocking
+# tasks so we want to cancel those too. The main thread will be woken
+# up every shutdown_io_time_between_cancellations_ms to cancel the IO
+# on the other thread.
+- name: browser.cache.shutdown_io_time_between_cancellations_ms
+ type: RelaxedAtomicUint32
+ value: 5
+ mirror: always
+
+# A percentage limit for media content type in the disk cache. When some entries
+# need to be evicted and media is over the limit, it's evicted first.
+- name: browser.cache.disk.content_type_media_limit
+ type: RelaxedAtomicInt32
+ value: 50
+ mirror: always
+
+# How often to validate document in cache
+# 0 = once-per-session,
+# 1 = each-time,
+# 2 = never,
+# 3 = when-appropriate/automatically
+- name: browser.cache.check_doc_frequency
+ type: RelaxedAtomicUint32
+ value: 3
+ mirror: always
+
+# Compression level for cached JavaScript bytecode
+# 0 = do not compress,
+# 1 = minimal compression,
+# 9 = maximal compression
+- name: browser.cache.jsbc_compression_level
+ type: RelaxedAtomicUint32
+ value: 0
+ mirror: always
+
+# Whether tooltips are enabled.
+- name: browser.chrome.toolbar_tips
+ type: bool
+ value: true
+ mirror: always
+
+# Whether tooltips are hidden on keydown.
+# 0: never
+# 1: always
+# 2: only on non-modifier keys
+- name: browser.chrome.toolbar_tips.hide_on_keydown
+ type: uint32_t
+#if defined(XP_WIN)
+ value: 0
+#else
+ value: 2
+#endif
+ mirror: always
+
+# DLP agent name, for display in the browser
+- name: browser.contentanalysis.agent_name
+ type: String
+ value: "A DLP agent"
+ mirror: never
+
+# (optional) The organization name that the DLP agent should have. If this is
+# non-empty and the DLP agent is not signed with this organization name,
+# Firefox will fail the connection.
+- name: browser.contentanalysis.client_signature
+ type: String
+ value: ""
+ mirror: never
+
+# Content analysis by external applications, e.g. data-loss prevention apps
+- name: browser.contentanalysis.enabled
+ type: bool
+ value: false
+ mirror: always
+
+# If true, content analysis uses an in-process WebAssembly DLP module
+# instead of an external agent.
+- name: browser.contentanalysis.use_wasm_backend
+ type: bool
+ value: false
+ mirror: always
+
+# If true, the content analysis extension must be signed before Firefox will
+# read and run its DLP module. Should only be set to false for testing.
+- name: browser.contentanalysis.wasm_module_extension_require_signature
+ type: bool
+ value: true
+ mirror: never
+
+# On Windows, whether to bring the foreground window to the front when printing
+# to avoid a DLP agent stealing focus and cancelling the print (bug 1980225)
+- name: browser.contentanalysis.print_set_foreground_window
+ type: bool
+ value: true
+ mirror: always
+
+# What content analysis should return if there is a problem communicating
+# with the agent. (see DefaultResponse enum in ContentAnalysis.h)
+# Make sure these stay in sync with the out-of-range check in Policies.sys.mjs.
+#
+# 0: Block all requests
+# 1: Warn on all requests (which lets the user decide)
+# 2: Allow all requests
+- name: browser.contentanalysis.default_result
+ type: uint32_t
+ value: 0
+ mirror: always
+
+# What content analysis should return if the agent takes too long to respond
+# to a request. (see DefaultResponse enum in ContentAnalysis.h)
+# Make sure these stay in sync with the out-of-range check in Policies.sys.mjs.
+#
+# 0: Block all requests
+# 1: Warn on all requests (which lets the user decide)
+# 2: Allow all requests
+- name: browser.contentanalysis.timeout_result
+ type: uint32_t
+ value: 0
+ mirror: always
+
+# Is the IPC pipe to the DLP tool specific to the user or to the system?
+- name: browser.contentanalysis.is_per_user
+ type: bool
+ value: true
+ mirror: always
+
+# Path name of pipe used to connect to a configured DLP agent.
+- name: browser.contentanalysis.pipe_path_name
+ type: String
+ value: "path_user"
+ mirror: never
+
+# Space-separated list of regexs that are compared to URLs of resources
+# being checked by content-analysis. Resources that match are not checked
+# and are always permitted.
+# By default this does not check any about: page except for about:blank
+# and about:srcdoc.
+- name: browser.contentanalysis.allow_url_regex_list
+ type: String
+ value: "^about:(?!blank|srcdoc).*"
+ mirror: never
+
+# Space-separated list of regexs that are compared to URLs of resources
+# being checked by content-analysis. Resources that match are not checked
+# and are always denied.
+- name: browser.contentanalysis.deny_url_regex_list
+ type: String
+ value: ""
+ mirror: never
+
+# Should CA ignore the system setting and use silent notifications?
+- name: browser.contentanalysis.silent_notifications
+ type: bool
+ value: false
+ mirror: always
+
+# Time (secs) after which content analysis operations are considered timed-out
+# A non-positive value indicates a timeout of 25ms, which is used for testing.
+- name: browser.contentanalysis.agent_timeout
+ type: int32_t
+ value: 300
+ mirror: always
+
+# Should Firefox show a notification or dialog when content analysis blocks
+# access?
+- name: browser.contentanalysis.show_blocked_result
+ type: bool
+ value: true
+ mirror: always
+
+# Should Firefox bypass content analysis for pastes and drags whose source
+# is the same tab?
+- name: browser.contentanalysis.bypass_for_same_tab_operations
+ type: bool
+ value: false
+ mirror: always
+
+# Max number of concurrent connections to the DLP agent. For stability
+# reasons, values exceeding 256 will be ignored.
+- name: browser.contentanalysis.max_connections
+ type: uint32_t
+ value: 32
+ mirror: always
+
+# Should Firefox use content analysis for clipboard operations?
+# Note that this has no effect unless browser.contentanalysis.enabled
+# is true.
+- name: browser.contentanalysis.interception_point.clipboard.enabled
+ type: bool
+ value: true
+ mirror: always
+
+# Should Firefox only analyze plain text contents of the clipboard?
+# If this is false, all formats on the clipboard will be analyzed.
+# Note that regardless of this setting, files on the clipboard
+# will be analyzed.
+- name: browser.contentanalysis.interception_point.clipboard.plain_text_only
+ type: bool
+ value: true
+ mirror: always
+
+# Should Firefox use content analysis when web content copies data to the
+# clipboard?
+# Note that this has no effect unless browser.contentanalysis.enabled
+# is true.
+# This defaults to false so as to not break existing content analysis
+# configurations.
+- name: browser.contentanalysis.interception_point.clipboard_copy.enabled
+ type: bool
+ value: false
+ mirror: always
+
+# Should Firefox only analyze plain text contents when web content copies
+# data to the clipboard?
+# If this is false, all formats being copied will be analyzed.
+# Note that regardless of this setting, files being copied
+# will be analyzed.
+- name: browser.contentanalysis.interception_point.clipboard_copy.plain_text_only
+ type: bool
+ value: true
+ mirror: always
+
+# Should Firefox use content analysis for download operations?
+# Note that this has no effect unless browser.contentanalysis.enabled
+# is true.
+# This defaults to false so as to not break existing content analysis
+# configurations.
+- name: browser.contentanalysis.interception_point.download.enabled
+ type: bool
+ value: false
+ mirror: always
+
+# Should Firefox use content analysis for drag and drop operations?
+# Note that this has no effect unless browser.contentanalysis.enabled
+# is true.
+- name: browser.contentanalysis.interception_point.drag_and_drop.enabled
+ type: bool
+ value: true
+ mirror: always
+
+# Should Firefox only analyze plain text contents for drag and drop
+# operations?
+# If this is false, all formats that are part of the drag and drop
+# operation will be analyzed.
+# Note that regardless of this setting, files that are dragged and dropped
+# will be analyzed.
+- name: browser.contentanalysis.interception_point.drag_and_drop.plain_text_only
+ type: bool
+ value: true
+ mirror: always
+
+# Should Firefox use content analysis for file upload operations through
+# a file dialog?
+# Note that this has no effect unless browser.contentanalysis.enabled
+# is true.
+- name: browser.contentanalysis.interception_point.file_upload.enabled
+ type: bool
+ value: true
+ mirror: always
+
+# Should Firefox use content analysis for print operations?
+# Note that this has no effect unless browser.contentanalysis.enabled
+# is true.
+- name: browser.contentanalysis.interception_point.print.enabled
+ type: bool
+ value: true
+ mirror: always
+
+# Content blocking for Enhanced Tracking Protection
+- name: browser.contentblocking.database.enabled
+ type: bool
+ value: false
+ mirror: always
+
+# If true, TrackingDBService read methods broadcast a flush request before
+# querying, so live ContentBlockingLogs for long-lived top-level documents
+# write their pending events to the database first. Has no effect unless
+# browser.contentblocking.database.enabled is also true.
+- name: browser.contentblocking.database.flushOnQuery.enabled
+ type: bool
+ value: true
+ mirror: always
+
+# How many recent block/unblock actions per origins we remember in the
+# Content Blocking log for each top-level window.
+- name: browser.contentblocking.originlog.length
+ type: uint32_t
+ value: 32
+ mirror: always
+
+# Whether memorytesting is enabled when crash reporter client is launched
+- name: browser.crashReporter.memtest
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+
+# Space-separated list of prioritized memory test kinds
+- name: browser.crashReporter.memtestKinds
+ type: DataMutexString
+ value: ""
+ mirror: always
+
+# Control whether we enable the feature of crash reports on demand at all
+- name: browser.crashReports.onDemand
+ type: bool
+ value: true
+ mirror: always
+
+# Should we prompt the user to send targeted crash report requested by devs?
+- name: browser.crashReports.requestedNeverShowAgain
+ type: bool
+ value: false
+ mirror: always
+
+# Do not show crash pull prompt before this unix epoch time to avoid spamming user
+- name: browser.crashReports.dontShowBefore
+ type: uint32_t
+ value: 0
+ mirror: always
+
+# Min font device pixel size at which to turn on high quality.
+- name: browser.display.auto_quality_min_font_size
+ type: RelaxedAtomicUint32
+ value: 20
+ mirror: always
+
+- name: browser.display.background_color
+ type: String
+ value: "#FFFFFF"
+ mirror: never
+
+- name: browser.display.background_color.dark
+ type: String
+ value: "#1C1B22"
+ mirror: never
+
+# This preference is a bit confusing because we use the opposite
+# string value in the colors dialog to indicate to users how FF HCM
+# will behave.
+# With resect to document colors, these values mean:
+# 0 = "default" = always, except in high contrast mode
+# 1 = "always"
+# 2 = "never"
+#
+# On windows, we set this to 0, which means FF HCM will mirror OS HCM.
+# Everywhere else, we set this to 1, disabling FF HCM.
+- name: browser.display.document_color_use
+ type: RelaxedAtomicUint32
+#if defined(XP_WIN)
+ value: 0
+#else
+ value: 1
+#endif
+ mirror: always
+ rust: true
+
+# This pref dictates whether or not backplates and background images
+# are to be drawn, when in high-contrast mode:
+# false: do not draw backplates or render background images
+# true: render background images and draw backplates
+# This condition is only considered when high-contrast mode is enabled
+# in Firefox, ie. when the user has:
+# (1) mUseAccessibilityMode set to true (Widows high-contrast mode is on)
+# AND browser.display.document_color_use set to 0
+# (only with high-contrast themes) OR
+# (2) browser.display.document_color_use set to 2 (always)
+- name: browser.display.permit_backplate
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+ rust: true
+
+# Whether we should suppress the background-image of the canvas (the root
+# frame) if we're in forced colors mode.
+#
+# This is important because some sites use background-image with a plain color
+# and it causes undesirable results in high-contrast mode.
+#
+# See bug 1614921 for example.
+- name: browser.display.suppress_canvas_background_image_on_forced_colors
+ type: bool
+ value: true
+ mirror: always
+
+- name: browser.display.foreground_color
+ type: String
+ value: "#000000"
+ mirror: never
+
+- name: browser.display.foreground_color.dark
+ type: String
+ value: "#FBFBFE"
+ mirror: never
+
+# Determines the behavior of OS zoom settings.
+#
+# 0: doesn't affect rendering at all
+# 1: affects full zoom (dpi, effectively).
+# 2: affects text zoom.
+#
+# Default is (1): Historical behavior on Linux, matches other browsers on
+# Windows, and generally creates more consistent rendering.
+- name: browser.display.os-zoom-behavior
+ type: RelaxedAtomicInt32
+ value: 1
+ mirror: always
+ rust: true
+
+# Whether focus rings are always shown by default.
+#
+# This is the initial value of nsWindowRoot::mShowFocusRings, but it can be
+# overridden by system preferences.
+- name: browser.display.show_focus_rings
+ type: bool
+ value: false
+ mirror: always
+
+# Enable showing image placeholders while image is loading or when image is broken.
+- name: browser.display.show_image_placeholders
+ type: bool
+ value: true
+ mirror: always
+
+# Whether we should always enable focus rings after focus was moved by keyboard.
+#
+# This behavior matches both historical and GTK / Windows focus behavior.
+#
+# :focus-visible is intended to provide better heuristics than this.
+- name: browser.display.always_show_rings_after_key_focus
+ type: bool
+ value: false
+ mirror: always
+
+# In theory: 0 = never, 1 = quick, 2 = always, though we always just use it as
+# a bool!
+- name: browser.display.use_document_fonts
+ type: RelaxedAtomicInt32
+ value: 1
+ mirror: always
+ rust: true
+
+# font-family names for which we'll override use_document_fonts=0, and always
+# use the specified font.
+# This is to support ligature-icon fonts, which render literal strings like
+# "arrow_drop_down" with an icon, even when use_document_fonts is disabled.
+# If an author provides & uses such a font, and we decline to use it, we'll end
+# up rendering these literal strings where the author intended an icon, which
+# can cause all sorts of overlapping/unreadable content.
+- name: browser.display.use_document_fonts.icon_font_allowlist
+ type: String
+ value: >-
+ Material Icons,
+ Material Icons Extended,
+ Material Icons Outlined,
+ Material Icons Round,
+ Material Icons Sharp,
+ Material Icons Two Tone,
+ Google Material Icons,
+ Google Material Icons Filled,
+ Material Symbols Outlined,
+ Material Symbols Round,
+ Material Symbols Rounded,
+ Material Symbols Sharp,
+ Google Symbols,
+ FontAwesome
+ mirror: never
+
+- name: browser.dom.window.dump.enabled
+ type: RelaxedAtomicBool
+ value: @IS_NOT_MOZILLA_OFFICIAL@
+ mirror: always
+
+# See bug 1738574
+- name: browser.download.start_downloads_in_tmp_dir
+ type: bool
+ value: false
+ mirror: always
+
+# See bug 1747343
+- name: browser.download.always_ask_before_handling_new_types
+ type: bool
+ value: false
+ mirror: always
+
+# See bug 1790641
+- name: browser.download.enableDeletePrivate
+ type: bool
+ value: true
+ mirror: always
+
+- name: browser.download.deletePrivate
+ type: bool
+ value: false
+ mirror: always
+
+# See bug 1731668
+- name: browser.download.enable_spam_prevention
+ type: bool
+ value: false
+ mirror: always
+
+# See bug 1772569
+- name: browser.download.open_pdf_attachments_inline
+ type: bool
+ value: false
+ mirror: always
+
+# See bug 1811830
+- name: browser.download.force_save_internally_handled_attachments
+ type: bool
+ value: false
+ mirror: always
+
+- name: browser.download.sanitize_non_media_extensions
+ type: bool
+ value: true
+ mirror: always
+
+# Image document's automatic image sizing.
+- name: browser.enable_automatic_image_resizing
+ type: bool
+ value: true
+ mirror: always
+
+# Image document's click-to-resize.
+- name: browser.enable_click_image_resizing
+ type: bool
+ value: @IS_NOT_MOBILE@
+ mirror: always
+
+- name: browser.find.ignore_ruby_annotations
+ type: bool
+ value: true
+ mirror: always
+
+#if defined(XP_MACOSX)
+# Whether pressing Esc will exit fullscreen.
+- name: browser.fullscreen.exit_on_escape
+ type: bool
+ value: true
+ mirror: always
+#endif
+
+# The max url length we'll store in history.
+#
+# The default value is mostly a guess based on various facts:
+#
+# * IE didn't support urls longer than 2083 chars
+# * Sitemaps protocol used to support a maximum of 2048 chars
+# * Various SEO guides suggest to not go over 2000 chars
+# * Various apps/services are known to have issues over 2000 chars
+# * RFC 2616 - HTTP/1.1 suggests being cautious about depending
+# on URI lengths above 255 bytes
+#
+- name: browser.history.maxUrlLength
+ type: uint32_t
+ value: 2000
+ mirror: always
+
+# Max size of push/replaceState data parameter
+- name: browser.history.maxStateObjectSize
+ type: int32_t
+ value: 16777216
+ mirror: always
+
+# True to collect wireframes upon navigations / pushState
+- name: browser.history.collectWireframes
+ type: bool
+ value: false
+ mirror: always
+
+# If false, show internal error page for HTTP responses with error
+# codes (4xx, 5xx) and "Content-Length": 0 instead of blank page
+# See https://bugzilla.mozilla.org/show_bug.cgi?id=1325876#c32 for why this
+# is disabled on Android.
+- name: browser.http.blank_page_with_error_response.enabled
+ type: bool
+#if !defined(ANDROID)
+ value: false
+#else
+ value: true
+#endif
+ mirror: always
+
+# The minimum area for a rect to be included in a wireframe, in CSS pixels.
+#
+# The current value of 50 is pretty arbitrary, and will be tuned as we refine
+# and test the wireframing capability.
+- name: browser.history.wireframeAreaThreshold
+ type: uint32_t
+ value: 50
+ mirror: always
+
+#if defined(XP_WIN) || defined(XP_LINUX)
+ # Notify TabUnloader or send the memory pressure if the memory resource
+ # notification is signaled AND the available commit space is lower than
+ # this value.
+- name: browser.low_commit_space_threshold_mb
+ type: RelaxedAtomicUint32
+ value: 200
+ mirror: always
+#endif
+
+#ifdef XP_LINUX
+ # On Linux we also check available memory in comparison to total memory,
+ # and use this percent value (out of 100) to determine if we are in a
+ # low memory scenario.
+- name: browser.low_commit_space_threshold_percent
+ type: RelaxedAtomicUint32
+ value: 5
+ mirror: always
+#endif
+
+# Render animations and videos as a solid color
+- name: browser.measurement.render_anims_and_video_solid
+ type: RelaxedAtomicBool
+ value: false
+ mirror: always
+
+# When set, the HWInference parent resolves model availability and install
+# requests from an in-process mock instead of the ModelHub (no network,
+# IndexedDB or downloads). The full content->utility->parent IPC chain is
+# still exercised. Used by tests.
+- name: browser.ml.modelHub.testing
+ type: bool
+ value: false
+ mirror: always
+
+# How many times a crashed HWInference process is restarted before giving up,
+# leaving the features relying on it unavailable. Reset once the process is
+# shut down cleanly, i.e. because its last consumer went away.
+- name: browser.ml.hwinference.max_restarts
+ type: uint32_t
+ value: 3
+ mirror: always
+
+# How long the HWInference process the browser's own features run in outlives
+# its last consumer, in milliseconds, so that the next one skips the launch.
+# Zero shuts it down at once.
+- name: browser.ml.hwinference.browser_idle_shutdown_grace_ms
+ type: uint32_t
+ value: 120000
+ mirror: always
+
+- name: browser.navigation.requireUserInteraction
+ type: bool
+ value: true
+ mirror: always
+
+# Indicates if about:newtab shows content (enabled) or just blank.
+- name: browser.newtabpage.enabled
+ type: bool
+ value: true
+ mirror: always
+
+# Open PDFs in Edge with the --app flag if it is the default.
+- name: browser.pdf.launchDefaultEdgeAsApp
+ type: bool
+ value: true
+ mirror: always
+
+# Maximium delay between keystrokes that will be considered typing (milliseconds).
+- name: browser.places.interactions.typing_timeout_ms
+ type: RelaxedAtomicUint32
+ value: 3000
+ mirror: always
+
+# Maximum delay between scroll input events that will be considered a scrolling interaction (milliseconds).
+- name: browser.places.interactions.scrolling_timeout_ms
+ type: RelaxedAtomicUint32
+ value: 5000
+ mirror: always
+
+# Number of seconds till the sponsored session is timeout.
+- name: browser.places.sponsoredSession.timeoutSecs
+ type: RelaxedAtomicUint32
+ value: 3600
+ mirror: always
+
+# Whether to start the private browsing mode at application startup
+- name: browser.privatebrowsing.autostart
+ type: bool
+ value: false
+ mirror: always
+
+# Force usage of in-memory (rather than file on disk) media cache for video streaming when private browsing
+- name: browser.privatebrowsing.forceMediaMemoryCache
+ type: bool
+ value: false
+ mirror: always
+
+# Whether to enable honoring the XUL window position.
+#
+# Historically, GTK has ignored it, but doing so causes some interesting edge
+# cases on multi-monitor situations which Windows suffers from. It seems Linux
+# WMs are better at auto-positioning the windows than Windows, tho.
+#
+# This still allows toggling it at runtime, both for testing and for users that
+# care more about avoiding things like session restore flicker.
+- name: browser.load-xul-position.enabled
+ type: bool
+#ifdef MOZ_WIDGET_GTK
+ value: false
+#else
+ value: true
+#endif
+ mirror: always
+
+# Disable state restoration, allowing the kiosk desktop environment to manage state and position.
+- name: browser.restoreWindowState.disabled
+ type: bool
+ value: false
+ mirror: always
+
+# Communicates the toolbar color to platform (for e.g., prefers-color-scheme).
+#
+# Returns whether the toolbar is dark (0), light (1), or system (2). The
+# theming code overrides it if appropriate.
+- name: browser.theme.toolbar-theme
+ type: RelaxedAtomicUint32
+ value: 2
+ mirror: always
+
+# Whether (-moz-native-theme) evaluates to true by default.
+- name: browser.theme.native-theme
+ type: RelaxedAtomicBool
+#ifdef MOZ_WIDGET_GTK
+ value: true
+#else
+ value: false
+#endif
+ mirror: always
+ rust: true
+
+# Communicates the preferred content theme color to platform (for e.g.,
+# prefers-color-scheme).
+#
+# dark (0), light (1), or system (2)
+#
+# Default to "system", the theming code sets it appropriately.
+- name: browser.theme.content-theme
+ type: RelaxedAtomicUint32
+ value: 2
+ mirror: always
+ rust: true
+
+# Whether the firefox titlebar respects the
+# -moz-windows-accent-color-in-titlebar setting on the tab strip.
+- name: browser.theme.windows.accent-color-in-tabs.enabled
+ type: RelaxedAtomicBool
+ value: false
+ mirror: always
+ rust: true
+
+# Blocked plugin content
+- name: browser.safebrowsing.blockedURIs.enabled
+ type: bool
+ value: true
+ mirror: always
+
+# Malware protection
+- name: browser.safebrowsing.malware.enabled
+ type: bool
+ value: true
+ mirror: always
+
+# Phishing protection
+- name: browser.safebrowsing.phishing.enabled
+ type: bool
+ value: true
+ mirror: always
+
+# Global Cache
+- name: browser.safebrowsing.globalCache.enabled
+ type: bool
+ value: @IS_NIGHTLY_BUILD@
+ mirror: always
+
+# SafeBrowsing Real-Time Lookup
+- name: browser.safebrowsing.realTime.enabled
+ type: bool
+ value: @IS_NIGHTLY_BUILD@
+ mirror: always
+
+# SafeBrowsing Real-Time Request Simulation
+- name: browser.safebrowsing.realTime.simulation.enabled
+ type: bool
+ value: @IS_NIGHTLY_BUILD@
+ mirror: always
+
+# Hit probability for the simulation, expressed as parts per million.
+# 1000000 = 100%, 1 = 0.0001%, 0 = never hit.
+# Lower values = more simulated requests over time.
+- name: browser.safebrowsing.realTime.simulation.hitProbability
+ type: RelaxedAtomicUint32
+ value: 5
+ mirror: always
+
+# TTL for cached full hashes in the simulation cache (seconds)
+# Default: 5 minutes (300 seconds)
+- name: browser.safebrowsing.realTime.simulation.cacheTTLSec
+ type: RelaxedAtomicUint32
+ value: 300
+ mirror: always
+
+# Whether to enable the negative cache for the simulation.
+# When enabled, full hashes that don't trigger a simulated hit are cached
+# to skip sending real-time requests for subsequent lookups.
+- name: browser.safebrowsing.realTime.simulation.negativeCacheEnabled
+ type: RelaxedAtomicBool
+ value: false
+ mirror: always
+
+# TTL for negative cache entries in the simulation cache (seconds).
+- name: browser.safebrowsing.realTime.simulation.negativeCacheTTLSec
+ type: RelaxedAtomicUint32
+ value: 300
+ mirror: always
+
+# Number of noise entries to include in simulated requests.
+# These are random hash prefixes added to mask the true URL being checked.
+- name: browser.safebrowsing.realTime.simulation.noiseEntryCount
+ type: RelaxedAtomicUint32
+ value: 4
+ mirror: always
+
+# Maximum size for an array to store the safebrowsing prefixset.
+- name: browser.safebrowsing.prefixset_max_array_size
+ type: RelaxedAtomicUint32
+ value: 512*1024
+ mirror: always
+
+# Whether to only classify top-level channels for safe browsing.
+- name: browser.safebrowsing.only_top_level
+ type: bool
+ value: true
+ mirror: always
+
+# SessionStore prefs
+# Maximum number of bytes of DOMSessionStorage data we collect per origin.
+- name: browser.sessionstore.dom_storage_limit
+ type: uint32_t
+ value: 2048
+ mirror: always
+
+# Maximum number of characters of form field data per field we collect.
+- name: browser.sessionstore.dom_form_limit
+ type: uint32_t
+ value: 1024*1024*2
+ mirror: always
+
+# Maximum number of characters of form data we collect per origin.
+- name: browser.sessionstore.dom_form_max_limit
+ type: uint32_t
+ value: 1024*1024*50
+ mirror: always
+
+# Minimal interval between two save operations in milliseconds (while the user is active).
+- name: browser.sessionstore.interval
+ type: RelaxedAtomicUint32
+ value: 15000
+ mirror: always
+
+# Disable collection of data for session store using the native collector code,
+# instead use the older implementation that's not compatible with session
+# history in the parent (and thus Fission).
+- name: browser.sessionstore.disable_platform_collection
+ type: bool
+#if defined(MOZ_THUNDERBIRD)
+ value: true
+#else
+ value: false
+#endif
+ mirror: once
+ do_not_use_directly: true
+
+# Enables file IO for testing Windows shortcut and shortcut log.
+- name: browser.shell.shortcut.test
+ type: RelaxedAtomicBool
+ value: false
+ mirror: always
+
+# Gates about:smartpage, the viewer for pages Firefox generated on the user's
+# request. Read from C++ on the load and history paths, so it is static.
+- name: browser.smartwindow.aitab.enabled
+ type: bool
+ value: @IS_NIGHTLY_BUILD@
+ mirror: always
+
+# Whether to show an about:blank window as early as possible for quick startup feedback.
+# Held to nightly on Linux due to bug 1450626.
+# Disabled on Mac because the bouncing dock icon already provides feedback.
+- name: browser.startup.blankWindow
+ type: bool
+#if defined(XP_WIN) || defined(MOZ_WIDGET_GTK) && defined(NIGHTLY_BUILD)
+ value: true
+#else
+ value: false
+#endif
+ mirror: always
+
+# Whether to attempt to use the skeleton UI when starting up.
+- name: browser.startup.preXulSkeletonUI
+ type: bool
+ value: false
+ mirror: always
+
+#if defined(NIGHTLY_BUILD) || defined(MOZ_DEV_EDITION) || defined(DEBUG)
+- name: browser.startup.record
+ type: bool
+ value: false
+ mirror: always
+#endif
+
+# Causes SessionStore to ignore non-final update messages from
+# browser tabs that were not caused by a flush from the parent.
+# This is a testing flag and should not be used by end-users.
+- name: browser.sessionstore.debug.no_auto_updates
+ type: RelaxedAtomicBool
+ value: false
+ mirror: always
+
+# Whether to restore windows to the virtual desktop (aka workspace)
+# they were on when they were closed.
+- name: browser.sessionstore.restore_windows_to_virtual_desktop
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+
+# If set, when a link is opened to a new tab, do not switch to the new tab.
+#
+# This pref is used when the link is opened with "Open Link in New Tab",
+# middle-click, etc.
+#
+# See also browser.tabs.loadDivertedInBackground, which is used when the website
+# diverts the link into a new tab.
+- name: browser.tabs.loadInBackground
+ type: bool
+ value: true
+ mirror: always
+
+# Whether we should draw the tabs on top of the titlebar.
+#
+# no (0), yes (1), or default (2), which is true everywhere except Linux.
+- name: browser.tabs.inTitlebar
+ type: int32_t
+ value: 2
+ mirror: always
+
+# If set, middle clicking on a link opens the link in a new tab.
+- name: browser.tabs.opentabfor.middleclick
+ type: bool
+ value: true
+ mirror: always
+
+# Testing-only pref which makes data: URIs be loaded in a "web" content process
+# instead of within a process based on the URI's loader.
+- name: browser.tabs.remote.dataUriInDefaultWebProcess
+ type: RelaxedAtomicBool
+ value: false
+ mirror: always
+
+# Testing-only pref to force system-triggered about:blank loads to not change
+# content processes. This is used for performance tests which load an
+# about:blank document between navigations for historical reasons to avoid
+# unnecessary process switches.
+- name: browser.tabs.remote.systemTriggeredAboutBlankAnywhere
+ type: bool
+ value: false
+ mirror: always
+
+# Testing-only pref to cause PBrowser creation for a specific BrowsingContext to
+# fail, to test the errored codepath.
+- name: browser.tabs.remote.testOnly.failPBrowserCreation.enabled
+ type: bool
+ value: false
+ mirror: always
+
+- name: browser.tabs.remote.force-paint
+ type: bool
+ value: true
+ mirror: always
+
+# When this pref is enabled document loads with a mismatched
+# Cross-Origin-Embedder-Policy header will fail to load
+- name: browser.tabs.remote.useCrossOriginEmbedderPolicy
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+
+# This pref makes `credentialless` a valid value for
+# Cross-Origin-Embedder-Policy header
+- name: browser.tabs.remote.coep.credentialless
+ type: RelaxedAtomicBool
+#if defined(ANDROID)
+ value: @IS_NIGHTLY_BUILD@
+#else
+ value: true
+#endif
+ mirror: always
+ do_not_use_directly: true
+
+# When this pref is enabled top level loads with a mismatched
+# Cross-Origin-Opener-Policy header will be loaded in a separate process.
+- name: browser.tabs.remote.useCrossOriginOpenerPolicy
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+
+# When this pref is enabled then we use a separate content process for
+# top-level load of file:// URIs
+- name: browser.tabs.remote.separateFileUriProcess
+ type: RelaxedAtomicBool
+#if !defined(ANDROID)
+ value: true
+#else
+ value: false
+#endif
+ mirror: always
+
+# Pref to control whether we use a separate privileged content process
+# for certain mozilla webpages (which are listed in the pref
+# browser.tabs.remote.separatedMozillaDomains).
+- name: browser.tabs.remote.separatePrivilegedMozillaWebContentProcess
+ type: bool
+ value: false
+ mirror: always
+
+# Whether or not process selection for subframes will prefer re-using an
+# existing content process over creating a new one. Enabling this pref should
+# reduce the number of processes allocated for non-first-party domains if
+# dom.ipc.processCount.webIsolated > 1.
+- name: browser.tabs.remote.subframesPreferUsed
+ type: bool
+ value: true
+ mirror: always
+
+# When this pref is enabled, opaque response is only allowed to enter the
+# content process if it's a response for media (audio, image, video), CSS, or
+# JavaScript.
+- name: browser.opaqueResponseBlocking
+ type: RelaxedAtomicBool
+#if defined(ANDROID)
+ value: @IS_NIGHTLY_BUILD@
+#else
+ value: true
+#endif
+ mirror: always
+
+# When this pref is enabled, the JS validator will be enabled for
+# ORB.
+- name: browser.opaqueResponseBlocking.javascriptValidator
+ type: bool
+ value: true
+ mirror: always
+
+# This pref controls how filtering of opaque responses for calls to `Window.fetch`.
+# (and similar) is performed in the parent process. This is intended to make sure
+# that data that would be filtered in a content process never actually reaches that
+# content process.
+# See https://fetch.spec.whatwg.org/#concept-filtered-response-opaque
+# 0) Don't filter in the parent process at all, and let content processes handle
+# opaque filtering. Regardless of if ORB is enabled or not. N.B. that if ORB
+# is enabled opaque responses will be blocked.
+# 1) If ORB is enabled, in the parent process, filter the responses that ORB allows.
+# N.B. any responses ORB doesn't allow will not send data to a content process
+# since they will return a NetworkError. If the request is allowed by ORB, the
+# internal response will be intact and sent to the content process as is.
+# 2) If ORB is enabled, in the parent process, filter the responses that ORB blocks,
+# when they were issued by `Window.fetch` (and similar).
+# 3) Filter all responses in the parent, regardless of if ORB is enabled or not.
+# This means that opaque responses coming from `Window.fetch` won't even be
+# considered for being blocked by ORB.
+- name: browser.opaqueResponseBlocking.filterFetchResponse
+ type: uint32_t
+ value: 2
+ mirror: always
+ do_not_use_directly: true
+
+# This pref controls how exceptions to opaque response blocking for the media MIME types
+# `audio/*` and `video/*` are handled. This is because step 8 in the spec that performs
+# audio or video type pattern matching cannot handle certain MIME types (yet).
+# See https://whatpr.org/fetch/1442.html#orb-algorithm
+# 0) No exceptions
+# 1) Some exceptions, explicitly hard coded in `IsOpaqueSafeListedSpecBreakingMIMEType`
+# 2) Allow all MIME types beginning with `audio/*` or `video/*`.
+- name: browser.opaqueResponseBlocking.mediaExceptionsStrategy
+ type: uint32_t
+ value: 1
+ mirror: always
+ do_not_use_directly: true
+
+# When true, zooming will be enabled on all sites, even ones that declare
+# user-scalable=no or use touch-action to disable pinch gestures.
+- name: browser.ui.zoom.force-user-scalable
+ type: RelaxedAtomicBool
+ value: false
+ mirror: always
+
+- name: browser.viewport.desktopWidth
+ type: RelaxedAtomicInt32
+ value: 980
+ mirror: always
+
+- name: browser.visited_color
+ type: String
+ value: "#551A8B"
+ mirror: never
+
+# If you change this, you probably also want to change
+# nsXPLookAndFeel::GenericDarkColor for Visitedtext.
+- name: browser.visited_color.dark
+ type: String
+ value: "#FFADFF"
+ mirror: never
+
+# When true, soft reloads (including location.reload())
+# will only froce validate the top level document, subresources will
+# be loaded normally as-if users normally navigated to the page.
+- name: browser.soft_reload.only_force_validate_top_level_document
+ type: bool
+ value: true
+ mirror: always
+
+# Whether or not to save and restore zoom levels on a per-site basis.
+- name: browser.zoom.siteSpecific
+ type: bool
+ value: @IS_NOT_ANDROID@
+ mirror: always
+
+# Whether we block opening pickers from background tabs.
+- name: browser.disable_pickers_background_tabs
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+
+# Whether we block opening pickers from hidden extension pages in WebExtensions.
+# This includes background pages and devtools pages, but not background tabs.
+- name: browser.disable_pickers_in_hidden_extension_pages
+ type: RelaxedAtomicBool
+ value: @IS_NIGHTLY_BUILD@
+ mirror: always
+
+#---------------------------------------------------------------------------
+# Prefs starting with "channelclassifier."
+#---------------------------------------------------------------------------
+
+- name: channelclassifier.allowlist_example
+ type: bool
+ value: false
+ mirror: always
+
+#---------------------------------------------------------------------------
+# Prefs starting with "clipboard."
+#---------------------------------------------------------------------------
+
+# Clipboard behavior.
+- name: clipboard.autocopy
+ type: bool
+#if !defined(ANDROID) && !defined(XP_MACOSX) && defined(XP_UNIX)
+ value: true
+#else
+ value: false
+#endif
+ mirror: always
+
+# Allow clipboard data to be copied to the clipboard history/cloud
+# (used for sensitive data from about:logins and Private Browsing)
+# On GTK this controls the usage of the x-kde-passwordManagerHint MIME.
+- name: clipboard.copyPrivateDataToClipboardCloudOrHistory
+ type: bool
+ value: false
+ mirror: always
+
+#ifdef XP_WIN
+ # Whether to put a file promise onto the clipboard when copying images on Windows
+- name: clipboard.imageAsFile.enabled
+ type: bool
+ value: false
+ mirror: always
+
+ # On Windows, whether to add PNG before BMP (CF_DIB) in the list of supported
+ # formats when copying an image to the clipboard.
+- name: clipboard.copy_image.as_png
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+
+ # On Windows, whether we encode an image as PNG (instead of the previous
+ # default of BMP) when an application to which we are copying an image
+ # requests that it be provided as a temporary file (CF_HDROP).
+- name: clipboard.copy_image_file.as_png
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+#endif
+
+# When false, web custom format flavors written by other applications are
+# hidden from the Async Clipboard read paths (Firefox-authored content read
+# back from the in-process clipboard cache is unaffected).
+- name: clipboard.readCustomFormatsFromClipboard.enabled
+ type: RelaxedAtomicBool
+ value: @IS_NIGHTLY_BUILD@
+ mirror: always
+
+#---------------------------------------------------------------------------
+# Prefs starting with "consoleservice."
+#---------------------------------------------------------------------------
+
+#if defined(ANDROID)
+ # Disable sending console to logcat on release builds.
+- name: consoleservice.logcat
+ type: RelaxedAtomicBool
+ value: @IS_NOT_RELEASE_OR_BETA@
+ mirror: always
+#endif
+
+#---------------------------------------------------------------------------
+# Prefs starting with "content."
+#---------------------------------------------------------------------------
+
+- name: content.cors.disable
+ type: bool
+ value: false
+ mirror: always
+
+# If true, we'll use the triggering principal rather than the loading principal
+# when doing CORS checks. Doing so is generally not correct, but we shipped
+# with this behavior for a long time, so we're leaving it preffable in case
+# it's needed for testing or if we discover some edge case that requires it.
+#
+# TODO(dholbert): Remove this pref after the 'false' default-value has
+# successfully shipped for a release or two.
+- name: content.cors.use_triggering_principal
+ type: bool
+ value: false
+ mirror: always
+
+# How many times to deflect in interactive mode.
+- name: content.sink.interactive_deflect_count
+ type: int32_t
+ value: 0
+ mirror: always
+
+# How many times to deflect in perf mode.
+- name: content.sink.perf_deflect_count
+ type: int32_t
+ value: 200
+ mirror: always
+
+# Parse mode for handling pending events.
+# 0 = don't check for pending events
+# 1 = don't deflect if there are pending events
+# 2 = bail if there are pending events
+- name: content.sink.pending_event_mode
+ type: int32_t
+#ifdef XP_WIN
+ value: 1
+#else
+ value: 0
+#endif
+ mirror: always
+
+# How often to probe for pending events. 1 = every token.
+- name: content.sink.event_probe_rate
+ type: int32_t
+ value: 1
+ mirror: always
+
+# How long to stay off the event loop in interactive mode (microseconds).
+- name: content.sink.interactive_parse_time
+ type: int32_t
+ value: 3000
+ mirror: always
+
+# How long to stay off the event loop in perf mode.
+- name: content.sink.perf_parse_time
+ type: int32_t
+ value: 30000
+ mirror: always
+
+# How long to be in interactive mode after an event.
+- name: content.sink.interactive_time
+ type: uint32_t
+ value: 750000
+ mirror: always
+
+# How long to stay in perf mode after initial loading.
+- name: content.sink.initial_perf_time
+ type: uint32_t
+ value: 2000000
+ mirror: always
+
+# Should we switch between perf-mode and interactive-mode?
+# 0 = Switch
+# 1 = Interactive mode
+# 2 = Perf mode
+- name: content.sink.enable_perf_mode
+ type: int32_t
+ value: 0
+ mirror: always
+
+#---------------------------------------------------------------------------
+# Prefs starting with "converter."
+#---------------------------------------------------------------------------
+
+# Whether we include ruby annotation in the text despite whether it
+# is requested. This was true because we didn't explicitly strip out
+# annotations. Set false by default to provide a better behavior, but
+# we want to be able to pref-off it if user doesn't like it.
+- name: converter.html2txt.always_include_ruby
+ type: bool
+ value: false
+ mirror: always
+
+#---------------------------------------------------------------------------
+# Prefs starting with "datareporting."
+#---------------------------------------------------------------------------
+
+# Do note that the toggle on Fenix and Focus does NOT reflect to this pref.
+- name: datareporting.healthreport.uploadEnabled
+ type: RelaxedAtomicBool
+ value: false
+ mirror: always
+ rust: true
+
+#---------------------------------------------------------------------------
+# Prefs starting with "device."
+#---------------------------------------------------------------------------
+
+# Is support for the device sensors API enabled?
+- name: device.sensors.enabled
+ type: bool
+ value: true
+ mirror: always
+
+# KaiOS-only, see https://bugzilla.mozilla.org/show_bug.cgi?id=1699707#c10
+- name: device.sensors.ambientLight.enabled
+ type: bool
+ value: false
+ mirror: always
+
+- name: device.sensors.motion.enabled
+ type: bool
+ value: true
+ mirror: always
+
+- name: device.sensors.orientation.enabled
+ type: bool
+ value: true
+ mirror: always
+
+# KaiOS-only, see https://bugzilla.mozilla.org/show_bug.cgi?id=1699707#c10
+- name: device.sensors.proximity.enabled
+ type: bool
+ value: false
+ mirror: always
+
+- name: device.sensors.test.events
+ type: bool
+ value: false
+ mirror: always
+
+#---------------------------------------------------------------------------
+# Prefs starting with "devtools."
+#---------------------------------------------------------------------------
+
+- name: devtools.console.stdout.chrome
+ type: RelaxedAtomicBool
+ value: @IS_NOT_MOZILLA_OFFICIAL@
+ mirror: always
+
+- name: devtools.console.stdout.content
+ type: RelaxedAtomicBool
+ value: false
+ mirror: always
+
+#---------------------------------------------------------------------------
+# Prefs starting with "docshell."
+#---------------------------------------------------------------------------
+
+# If true, pages with an opener won't be bfcached.
+- name: docshell.shistory.bfcache.require_no_opener
+ type: bool
+ value: @IS_ANDROID@
+ mirror: always
+
+# If true, page with beforeunload or unload event listeners can be bfcached.
+- name: docshell.shistory.bfcache.allow_unload_listeners
+ type: bool
+ value: @IS_ANDROID@
+ mirror: always
+
+# If true, page with beforeunload event listeners can be bfcached.
+- name: docshell.shistory.bfcache.ship_allow_beforeunload_listeners
+ type: bool
+ value: true
+ mirror: always
+
+- name: docshell.shistory.sameDocumentNavigationOverridesLoadType
+ type: bool
+ value: @IS_NOT_NIGHTLY_BUILD@
+ mirror: always
+
+- name: docshell.shistory.sameDocumentNavigationOverridesLoadType.forceDisable
+ type: String
+ value: ""
+ mirror: never
+
+# Bug 2037346
+- name: docshell.shistory.restoreSubframesOnReload
+ type: bool
+ value: @IS_NOT_NIGHTLY_BUILD@
+ mirror: always
+
+#---------------------------------------------------------------------------
+# Prefs starting with "dom."
+#---------------------------------------------------------------------------
+
+# Allow cut/copy
+- name: dom.allow_cut_copy
+ type: bool
+ value: true
+ mirror: always
+
+# Audio Session API: navigator.audioSession surface
+# https://w3c.github.io/audio-session/
+- name: dom.audio_session.enabled
+ type: RelaxedAtomicBool
+ value: @IS_NIGHTLY_BUILD@
+ mirror: always
+
+# Audio Session API: enables the state changes for Audio Session. Separate from
+# the pref above so the state surface can be turned off on its own, without
+# withdrawing the whole API.
+- name: dom.audio_session.state_enabled
+ type: RelaxedAtomicBool
+ value: @IS_NIGHTLY_BUILD@
+ mirror: always
+
+# While the platform has interrupted the tab's audio (an audio-focus loss that
+# disallows any audible sound), block the page from starting or resuming audio
+# (media element, Web Audio, Web Speech) on its own until the interrupt ends.
+- name: dom.audio_session.block_start_during_interrupt.enabled
+ type: RelaxedAtomicBool
+ value: @IS_NIGHTLY_BUILD@
+ mirror: always
+
+# Checks if offscreen animation throttling is enabled.
+- name: dom.animations.offscreen-throttling
+ type: bool
+ value: true
+ mirror: always
+
+# Should CommitStyles use the end-point inclusive timing?
+- name: dom.animations.commit-styles-endpoint-inclusive
+ type: bool
+ value: true
+ mirror: always
+
+# Is support for Navigator.getBattery enabled?
+- name: dom.battery.enabled
+ type: bool
+ value: true
+ mirror: always
+
+# Block multiple external protocol URLs in iframes per single event.
+- name: dom.block_external_protocol_in_iframes
+ type: bool
+ value: true
+ mirror: always
+
+# Block Insecure downloads from Secure Origins
+- name: dom.block_download_insecure
+ type: bool
+ value: true
+ mirror: always
+
+# The maximum number of popup that is allowed to be opened. Set to -1 for no
+# limit.
+- name: dom.popup_maximum
+ type: int32_t
+ value: -1
+ mirror: always
+
+# Enable CacheAPI in private browsing mode with encryption
+- name: dom.cache.privateBrowsing.enabled
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+
+# Exposes window.caches and skips SecureContext check.
+# dom.serviceWorkers.testing.enabled also includes the same effect.
+- name: dom.caches.testing.enabled
+ type: RelaxedAtomicBool
+ value: false
+ mirror: always
+
+# A pref that is used to slow down database initialization for testing purposes.
+- name: dom.cache.databaseInitialization.pauseOnIOThreadMs
+ type: RelaxedAtomicUint32
+ value: 0
+ mirror: always
+
+# Disable capture attribute for input elements; only supported on GeckoView.
+- name: dom.capture.enabled
+ type: bool
+ value: false
+ mirror: always
+
+# Similar to caretPositionFromPoint, but non-standard.
+- name: dom.caretRangeFromPoint.enabled
+ type: bool
+ value: true
+ mirror: always
+
+# Master gate for the web custom format support in the Async Clipboard API.
+- name: dom.clipboard.customFormatSupport.enabled
+ type: RelaxedAtomicBool
+ value: @IS_NIGHTLY_BUILD@
+ mirror: always
+
+# HTML specification says the level should be 5
+# https://html.spec.whatwg.org/#timer-initialisation-steps
+- name: dom.clamp.timeout.nesting.level
+ type: RelaxedAtomicUint32
+ value: 5
+ mirror: always
+
+# Skip the security checks for document.cookie.
+- name: dom.cookie.testing.enabled
+ type: RelaxedAtomicBool
+ value: false
+ mirror: always
+
+# https://whatpr.org/html/10168/interaction.html#closewatcher
+- name: dom.closewatcher.enabled
+ type: bool
+ value: true
+ mirror: always
+
+# https://github.com/whatwg/html/pull/10737
+- name: dom.dialog.light-dismiss.enabled
+ type: bool
+ value: true
+ mirror: always
+
+# Allow control characters appear in composition string.
+# When this is false, control characters except
+# CHARACTER TABULATION (horizontal tab) are removed from
+# both composition string and data attribute of compositionupdate
+# and compositionend events.
+- name: dom.compositionevent.allow_control_characters
+ type: bool
+ value: false
+ mirror: always
+
+# Whether to enable large window for brotli on DecompressionStream.
+- name: dom.compression_streams.brotli.large_window.enabled
+ type: RelaxedAtomicBool
+ value: false
+ mirror: always
+
+# Compression Streams (zstd) (CompressionStream/DecompressionStream)
+# Whether or not "zstd" is a supported format for these streams.
+- name: dom.compression_streams.zstd.enabled
+ type: RelaxedAtomicBool
+ value: false
+ mirror: always
+
+# Enable cookie-store API
+- name: dom.cookieStore.enabled
+ type: RelaxedAtomicBool
+ value: true
+ mirror: always
+
+# Is support for CSSPseudoElement enabled?
+- name: dom.css_pseudo_element.enabled
+ type: bool
+ value: false
+ mirror: always
+
+# After how many seconds we allow external protocol URLs in iframe when not in
+# single events
+- name: dom.delay.block_external_protocol_in_iframes
+ type: uint32_t
+ value: 10 # in seconds
+ mirror: always
+
+# Whether the above pref has any effect at all.
+# Make sure cases like bug 1795380 work before trying to turn this off. See
+# bug 1680721 for some other context that might be relevant.
+- name: dom.delay.block_external_protocol_in_iframes.enabled
+ type: bool
+ value: true
+ mirror: always
+
+# Only propagate the open window click permission if the setTimeout() is equal
+# to or less than this value.
+- name: dom.disable_open_click_delay
+ type: int32_t
+ value: 1000
+ mirror: always
+
+- name: dom.disable_open_during_load
+ type: bool
+ value: false
+ mirror: always
+
+- name: dom.disable_beforeunload
+ type: bool
+ value: false
+ mirror: always
+
+- name: dom.require_user_interaction_for_beforeunload
+ type: bool
+ value: true
+ mirror: always
+
+# Fire DOMContentLoaded at the end of parsing, instead of from a task.
+- name: dom.document.domcontentloaded.synchronous.enabled
+ type: bool
+ value: true
+ mirror: always
+
+# Enable/disable Gecko specific edit commands
+- name: dom.document.edit_command.contentReadOnly.enabled
+ type: bool
+ value: false
+ mirror: always
+
+- name: dom.document.edit_command.insertBrOnReturn.enabled
+ type: bool
+ value: false
+ mirror: always
+
+# Preferences for document-language metadata extraction.
+#
+# How long a metadata request waits for the document load event before
+# collecting a single text sample from the current document anyway.
+- name: dom.document_language_metadata.load_timeout_ms
+ type: uint32_t
+ value: 4000
+ mirror: always
+
+# Base delay for metadata request retries. Each retry waits for this
+# duration multiplied by the retry count.
+- name: dom.document_language_metadata.retry_delay_base_ms
+ type: uint32_t
+ value: 500
+ mirror: always
+
+# Maximum number of retry attempts for metadata requests that extract less
+# than the requested minimum code units.
+- name: dom.document_language_metadata.max_retries
+ type: uint32_t
+ value: 3
+ mirror: always
+
+# Legacy behavior: include named properties in [[OwnPropertyKeys]] for the
+# Window named properties object (see bug 2011056).
+- name: dom.window.named_properties_object.legacy_own_property_keys
+ type: bool
+ value: false
+ mirror: always
+
+# Only intended for fuzzing purposes, this will break mozPrintCallback, etc.
+- name: dom.window_print.fuzzing.block_while_printing
+ type: bool
+ value: false
+ mirror: always
+
+# Whether to enable EditContext API
+# https://w3c.github.io/edit-context/#dom-editcontext
+- name: dom.editcontext.enabled
+ type: bool
+ value: false
+ mirror: always
+
+# Whether to allow attaching EditContext to
Nice!
+