elfmz / far2l

Linux port of FAR v2
GNU General Public License v2.0
1.76k stars 173 forks source link

Macro engines as separate backends #1409

Open unxed opened 1 year ago

unxed commented 1 year ago

Currntly we have two implementations of macro subsystem for far2l developed in separate repos. The one present here is classic macro subsystem of far2. The other, @shmuz 's one, is lua-based, somewhat similar to one present in far3. Both have advantages and disadvantages.

Classic (far2): no need for additional dependencies, lightweight, can be built and used even on embedded systems. Limited language possibilities, limited functionality.

Shnuz (lua based): Needs additional dependency on lua libs, more complex and heavy. Far more possibilities, many far3 useful lua scripts can be ported and used, potential to extend user base.

But what if we implement architecture that allows building macro engines as separate binaries, just as its done with gui or ttyx modules now?

This approach will combine advantages of both engines without forcing user to install additional libs if he do not need them — just as it currently works for python or rendering backends.

akruphi commented 1 year ago

Good suggestion. Lua allow more flexible macro functionality and compatibility with far3 utilities.

unxed commented 1 year ago

English translation is below.

Мне ОЧЕНЬ нравится идея глубокой интеграции какого-то скриптового языка (ну в смысле где динамическая типизация и автосборка мусора) вплоть до замены штатной макросистемы. Питон-плагин по состоянию на сейчас в такое не может, и там нет огромной базы готовых скриптов, которые, как показала практика, вполне реально адаптировать под far2l/m.

При этом мне также нравится, что мы только-только привели far2l к состоянию "может работать вообще без единой runtime зависимости", и от такого отказываться не хотелось бы.

Я сам скорее вебщик чем сишник, и у нас на вебе есть такое понятие graceful degradation. Это когда браузер не умеет какую-то фичу, и тогда подгружается прокладка, дающая настолько адекватную замену этой фичи, насколько возможно. А если не заработает даже прокладка, то допустимо, чтобы отвалилась часть функциональности интерфейса, но критические функции все равно должны работать.

Так и тут: Линукс это не Винда с предсказуемым гигагерцовым железом под ней. far2l могут и под роутер с 32 мб памяти собирать (я и сам такое делал). Так вот, если на целевой платформе совсем некуда запихнуть Lua, far2l имхо все равно должен собираться и работать на классической макросистеме, не требующей зависимостей, или уметь собираться и работать без макросистемы вовсе (начать можно с этого, кстати).

Думаю, причина, по которой elfmz не стал интегрировать макросистему на Lua, именно в этом. Моё предложение (заменяемая маросистема, собирающаяся в отдельный модуль, как far2l_gui.so, чтобы, в зависимости от опций сборки, собиралась либо классическая макросистема Far 2, либо макросистема из far2m) решило бы проблему, но это повозиться надо, чтобы сделать. Хотя возня тут, имхо, прикольная и увлекательная и вполне оправданная интересной целью.

--

I REALLY like the idea of deep integration of some kind of scripting language (well, in the sense of dynamic typing and auto garbage collection) up to replacing the integrated macro system. As of now, the Python plugin cannot do this, and there is no huge base of ready-made scripts, which, as practice has shown, is quite possible to adapt to far2l/m.

At the same time, I also like that we have just brought far2l to the state "it can work without a single runtime dependency at all", and I would not want to break this.

I myself am more of a web developer than a C/C++ one, and we on the web have such a concept "graceful degradation". This is when the browser does not know how to do some feature, and then some kind of shim is loaded, giving as adequate a replacement for this feature as possible. And if even the shim does not work, then it is acceptable that some parts of the interface may fall off, but critical functions should still work.

So it is here: Linux is not Windows with predictable GHz hardware under it. far2l can also be built for a router with as less as 32 MB of memory (I myself also had been doing it for a while). So, if there is absolutely no space to install Lua on the target platform, IMHO far2l should still build and work using a classic macro system from Far2 that does not require any dependencies, or it should be able to build and work without a macro system at all (we can start with this, by the way).

I think the reason why elfmz did not integrate the Lua macro system is precisely this. My suggestion (a replaceable marosystem that assembles into a separate module, like far2l_gui.so, so that, depending on the build options, either the classic Far 2 macrosystem or the macrosystem from far2m is built) would solve the problem, but it will take some time to implement it. Although IMHO this task is cool and exciting and quite justified by an interesting goal.

unxed commented 1 year ago

Автор far2m пишет, что LuaJIT занимает примерно 500 Кб, а версия без JIT около 200. При этом JIT там не особо критичен, потому что по тестам время расходуется больше в фаре, чем в луа.

Выходит, это не будет «тяжелой» зависимостью вроде Python.

Из чего можно сделать осторожный вывод, что использование Lua в качестве макросиcтемы, хоть и добавляет зависимость, общее утяжеление добавляет не критическое даже для роутера.

unxed commented 1 year ago

Также в чате принесли ссылку, обосновывающую выбор именно Lua в качестве скриптового языка приложения. Пожалуй, будет уместно здесь: https://habr.com/ru/companies/socialquantum/articles/428253/

И книжку по Lua тут оставлю тоже: https://articles.opexflow.com/wp-content/uploads/2022/02/lua.pdf

unxed commented 11 months ago

Интерпретатор lua, кстати, всего 800 Кб весит. Примерно как либы 7z в multiarc. Так что, в принципе, можно его и встроенным сделать, если системной версии нету.

akruphi commented 11 months ago

Интерпретатор lua, кстати, всего 800 Кб весит. Примерно как либы 7z в multiarc. Так что, в принципе, можно его и встроенным сделать, если системной версии нету.

К этой мысли хотелось бы пояснений @shmuz - насколько lua-плагины (пока про макросы рассуждать рано и как первый шаг возможность цеплять lua-плагины) из https://github.com/shmuz/luafar2m зависимы от версии lua и смогут ли использовать произвольный lua из системы.

shmuz commented 11 months ago

@akruphi В far2m lua-плагины работают только с luajit-2.1 или lua5.1, другие версии lua не предусмотрены. Кроме того, текущие версии этих плагинов (из коробки) не будут работать с far2l, поскольку они используют некоторые расширения API, добавленные в far2m.