Есть ли способ сохранить настройки моего монитора? У меня есть внешний монитор на работе, но каждое утро я должен подключить его, переставить окна так, чтобы они были рядом друг с другом. Могу я просто сохранить это?
Первые три шага для подключения внешнего монитора так, как вы хотите, и четвертый - для сохранения настроек.
Подключите внешний монитор и проверьте его поддерживаемое разрешение:
xrandr -q
Дайте следующую команду (Это отключит монитор вашего ноутбука):
xrandr --output LVDS1 --off --output TV1 --off --output VGA1 --mode 1280x1024 --pos 0x0 --rotate normal
Если вы хотите включить как ноутбук, так и внешний:
xrandr --output LVDS1 --mode yyyyXzzzz --pos 0x0 --rotate normal --output TV1 --off --output VGA1 --mode 1280x1024 --pos 0x0 --rotate normal
(yyyyXzzzz - разрешение вашего ноутбука.)
Приведенная выше конфигурация клонирует экран. Поиграйте с опцией «--right-of
/ --left-of
», если хотите.
Если вам нужны эти настройки при входе в систему, добавьте чеки в /etc/X11/Xsession.d/45custom_xrandr-settings
(вам может понадобиться создать их).
xrandr |grep VGA1 | grep " connected " | if [ $? -eq 0 ]; then xrandr --output LVDS1 --off --output TV1 --off --output VGA1 --mode 1280x1024 --pos 0x0 --rotate normal #Change the way u need ; fi
Конфигурация для всех ваших мониторов - с возможностью «горячего» подключения или нет - следует сохранить в $HOME/.config/monitors.xml
с помощью плагина xrandr
для gnome-settings-daemon
, который фактически применяет конфигурацию, которую вы делаете в Мониторы капплеты.
Так как кажется, что это не работает должным образом для всех, где-то явно есть ошибка. Urgh.
Ubuntu 12.04 запоминает настройки монитора с «горячей» заменой. Но они применяются только при повторном открытии «Конфигурация системы»> «Дисплеи». По крайней мере, это касается меня, и это определенно ошибка.
Нет, нет возможности сохранить конфигурации на мониторах с горячей заменой. Если вы подключаете перед загрузкой, GNOME должен запоминать конфигурацию при каждой загрузке для каждого устройства (т. Е. Подключаться к монитору на работе, а не дома).
Я предпочитаю запускать этот скрипт из терминала, так как сначала открываю один после входа в систему.
Первый вход в систему с неправильной конфигурацией - мониторы размещены неправильно:
cd ~/.config
mv ~/.config/monitors.xml{,.bak}
Теперь настройте свои мониторы с настройками системы, чтобы создать новый файл ~/.config/monitors.xml
с правильными настройками.
Скопируйте фиксированный сценарий Николя Бернаертса из моего репо: https://raw.githubusercontent.com/alextomko/monitors/master/monitors и поместите его в путь для запуска из терминала.
$ ls -l ~/bin
# if you don't have this directory then create it - do not be logged in as root here.
$ mkdir /home/$USER/bin
$ echo $PATH
# should show /home/username/bin if the dir existed or if you had to create.
$ wget -P ~/bin https://raw.githubusercontent.com/alextomko/monitors/master/monitors
$ chmod +x ~/bin/monitors
# Log out, lock, reboot or whatever it takes to make monitor settings lost for you and run the script.
$ monitors
Короче говоря (то есть: делайте то, что предлагает Николя Бернартс , но я не буду вдаваться в подробности): конфигурация мониторов фактически сохраняется в ~/.config/monitors.xml
, но не применяется при запуске / входе в систему. [ 1118]
Шаги для преодоления этого:
Войдите в систему с неправильной конфигурацией мониторов.
Удалите текущую конфигурацию монитора:
cd .config
mv monitors.xml{,.bak}
Используйте приложение Дисплеи , чтобы расположить мониторы так, как вы хотите (у меня монитор на одной стороне повернут против часовой стрелки).
Когда вы нажимаете Применить , создается новый monitors.xml
.
Теперь загрузите и сделайте исполняемый скрипт и модуль запуска, которые принудительно настраивают конфигурацию монитора на основе вновь созданного файла конфигурации:
$ sudo wget -O /usr/local/sbin/update-monitor-position https://raw.githubusercontent.com/NicolasBernaerts/ubuntu-scripts/master/ubuntugnome/update-monitor-position
$ sudo chmod +x /usr/local/sbin/update-monitor-position
$ sudo wget -O /usr/share/applications/update-monitor-position.desktop https://raw.githubusercontent.com/NicolasBernaerts/ubuntu-scripts/master/ubuntugnome/update-monitor-position.desktop
$ sudo chmod +x /usr/share/applications/update-monitor-position.desktop
На этом этапе настройку мониторов можно исправить, запустив Обновление положения монитора приложения.
Если вы хотите, чтобы это было автоматически, просто добавьте запускаемое приложение со следующими записями:
Update Monitors Position
update-monitor-position 5
Force monitors position 5 seconds after login
В офисе у меня 3 ноутбука на моем ноутбуке и 2 дома. Два из офисных мониторов установлены вертикально, в то время как другие мониторы находятся в нормальной ориентации.
а. Файл monitors.xml находится в ~ / .config.
B. Получить скрипт оболочки "update-monitor-position".
Измените определение «MONITOR_XML», «monitors.xml», на «monitors-office.xml».
Сохраните его как «update-monitor-position-office» по пути к исполняемому файлу (/usr/local/sbin/).
С. Получить ярлык на рабочем столе, "update-monitor-position.desktop"
update-monitor-position-office.desktop:
[Desktop Entry]
Type=Application
Exec=update-monitor-position-office
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
Name[en_US]=Office Monitors Position
Name=Office Monitors Position
Comment[en_US]=Force monitors position from monitor-office.xml
Comment=Force monitors position from monitor-office.xml
Icon=display
Сценарий оболочки, update-monitor-position-office
#!/bin/bash
# -------------------------------------------------
# Get monitors configuration from monitor.xml and apply it for current user session.
# In case of multiple definitions in monitor.xml only first one is used.
#
# See http://bernaerts.dyndns.org/linux/74-ubuntu/309-ubuntu-dual-display-monitor-position-lost
# for instructions
#
# Parameters :
# $1 : waiting time in sec. before forcing configuration (optional)
#
# Revision history :
# 19/04/2014, V1.0 - Creation by N. Bernaerts
# 10/07/2014, V1.1 - Wait 5 seconds for X to fully initialize
# 01/09/2014, V1.2 - Correct NULL file bug (thanks to Ivan Harmady) and handle rotation
# 07/10/2014, V1.3 - Add monitors size and rate handling (idea from jescalante)
# 08/10/2014, V1.4 - Handle primary display parameter
# 08/12/2014, V1.5 - Waiting time in seconds becomes a parameter
# -------------------------------------------------
# monitor.xml path
MONITOR_XML="$HOME/.config/monitors-office.xml"
# get number of declared monitors
NUM=$(xmllint --xpath 'count(//monitors/configuration['1']/output)' $MONITOR_XML)
# loop thru declared monitors to create the command line parameters
for (( i=1; i<=$NUM; i++)); do
# get attributes of current monitor (name and x & y positions)
NAME=$(xmllint --xpath 'string(//monitors/configuration['1']/output['$i']/@name)' $MONITOR_XML 2>/dev/null)
POS_X=$(xmllint --xpath '//monitors/configuration['1']/output['$i']/x/text()' $MONITOR_XML 2>/dev/null)
POS_Y=$(xmllint --xpath '//monitors/configuration['1']/output['$i']/y/text()' $MONITOR_XML 2>/dev/null)
ROTATE=$(xmllint --xpath '//monitors/configuration['1']/output['$i']/rotation/text()' $MONITOR_XML 2>/dev/null)
WIDTH=$(xmllint --xpath '//monitors/configuration['1']/output['$i']/width/text()' $MONITOR_XML 2>/dev/null)
HEIGHT=$(xmllint --xpath '//monitors/configuration['1']/output['$i']/height/text()' $MONITOR_XML 2>/dev/null)
RATE=$(xmllint --xpath '//monitors/configuration['1']/output['$i']/rate/text()' $MONITOR_XML 2>/dev/null)
PRIMARY=$(xmllint --xpath '//monitors/configuration['1']/output['$i']/primary/text()' $MONITOR_XML 2>/dev/null)
# if position is defined for current monitor, add its position and orientation to command line parameters
[ -n "$POS_X" ] && PARAM_ARR=("${PARAM_ARR[@]}" "--output" "$NAME" "--pos" "${POS_X}x${POS_Y}" "--fbmm" "${WIDTH}x${HEIGHT}" "--rate" "$RATE" "--rotate" "$ROTATE")
# if monitor is defined as primary, adds it to command line parameters
[ "$PRIMARY" = "yes" ] && PARAM_ARR=("${PARAM_ARR[@]}" "--primary")
done
# if needed, wait for some seconds (for X to finish initialisation)
[ -n "$1" ] && sleep $1
# position all monitors
xrandr "${PARAM_ARR[@]}"
Ответ Джея почти сработал для меня, но мне нужно было сделать пару дополнительных шагов. Я бы прокомментировал его ответ, но у меня нет репутации.
В файле update-monitor-position-office:
Спасибо, что указали мне на ~ /. config / monitors.xml
файл.
Я обнаружил, что в то время, когда я указывал желаемый макет, был создан один, а также какая-то резервная копия, monitors.xml ~
, которая отличалась только характеристикой, которую я хотел изменить.
Если я просто удалил этот файл резервной копии, то обнаружил, что моя вновь созданная копия вступит в силу при следующем перезапуске машины. Нет необходимости скачивать скрипт.
Я думаю, что если и была ошибка, то с тех пор она исправлена.
Также предполагаю, я предполагаю, что файл резервной копии каким-то образом был восстановлен, но после его удаления основной файл остается единственным действующим файлом.
Это сработало как на установке с Ubu 16.04, так и с 19.10
Еще раз спасибо, что указали мне на файл.
Обратите внимание, что в Ubuntu 18.04 макет monitors.xml выглядит иначе, поэтому некоторые запросы xpath больше не работают. Я адаптировал сценарий оболочки, опубликованный @jay, чтобы он работал соответственно:
#!/bin/bash
# -------------------------------------------------
# Get monitors configuration from monitor.xml and apply it for current user session.
# In case of multiple definitions in monitor.xml only first one is used.
#
# See http://bernaerts.dyndns.org/linux/74-ubuntu/309-ubuntu-dual-display-monitor-position-lost
# for instructions
#
# Parameters :
# $1 : waiting time in sec. before forcing configuration (optional)
#
# Revision history :
# 19/04/2014, V1.0 - Creation by N. Bernaerts
# 10/07/2014, V1.1 - Wait 5 seconds for X to fully initialize
# 01/09/2014, V1.2 - Correct NULL file bug (thanks to Ivan Harmady) and handle rotation
# 07/10/2014, V1.3 - Add monitors size and rate handling (idea from jescalante)
# 08/10/2014, V1.4 - Handle primary display parameter
# 08/12/2014, V1.5 - Waiting time in seconds becomes a parameter
# 06/17/2020, V1.6 - Adapted to new monitors version = 2 (see https://askubuntu.com/a/993592/93077)
# -------------------------------------------------
# monitor.xml path
MONITOR_XML="$HOME/.config/monitors-office.xml"
# get number of declared monitors
NUM=$(xmllint --xpath 'count(//monitors/configuration['1']/logicalmonitor)' $MONITOR_XML)
# loop thru declared monitors to create the command line parameters
for (( i=1; i<=$NUM; i++)); do
# get attributes of current monitor (name and x & y positions)
NAME=$(xmllint --xpath 'string(//monitors/configuration['1']/logicalmonitor['$i']//connector/text())' $MONITOR_XML 2>/dev/null)
POS_X=$(xmllint --xpath '//monitors/configuration['1']/logicalmonitor['$i']/x/text()' $MONITOR_XML 2>/dev/null)
POS_Y=$(xmllint --xpath '//monitors/configuration['1']/logicalmonitor['$i']/y/text()' $MONITOR_XML 2>/dev/null)
#ROTATE=$(xmllint --xpath '//monitors/configuration['1']/logicalmonitor['$i']/rotation/text()' $MONITOR_XML 2>/dev/null)
WIDTH=$(xmllint --xpath '//monitors/configuration['1']/logicalmonitor['$i']//width/text()' $MONITOR_XML 2>/dev/null)
HEIGHT=$(xmllint --xpath '//monitors/configuration['1']/logicalmonitor['$i']//height/text()' $MONITOR_XML 2>/dev/null)
RATE=$(xmllint --xpath '//monitors/configuration['1']/logicalmonitor['$i']//rate/text()' $MONITOR_XML 2>/dev/null)
PRIMARY=$(xmllint --xpath '//monitors/configuration['1']/logicalmonitor['$i']/primary/text()' $MONITOR_XML 2>/dev/null)
# if position is defined for current monitor, add its position and orientation to command line parameters
[ -n "$POS_X" ] && PARAM_ARR=("${PARAM_ARR[@]}" "--output" "$NAME" "--pos" "${POS_X}x${POS_Y}" "--fbmm" "${WIDTH}x${HEIGHT}" "--rate" "$RATE" "--rotate" "normal")
# if monitor is defined as primary, adds it to command line parameters
[ "$PRIMARY" = "yes" ] && PARAM_ARR=("${PARAM_ARR[@]}" "--primary")
done
# if needed, wait for some seconds (for X to finish initialisation)
[ -n "$1" ] && sleep $1
# position all monitors
xrandr "${PARAM_ARR[@]}"