无伤大雅的的小修改

main
lensfrex 3 years ago
parent d49c52c70c
commit b446921b42
Signed by: lensfrex
GPG Key ID: 947ADABD8533C476
  1. 7
      Dogename/dogename.iml
  2. 7
      Dogename/pom.xml
  3. 34
      Dogename/src/main/java/log4j2.xml
  4. 32
      Dogename/src/main/java/me/lensferno/dogename/Main.java
  5. 145
      Dogename/src/main/java/me/lensferno/dogename/configs/ConfigLoader.java
  6. 135
      Dogename/src/main/java/me/lensferno/dogename/configs/MainConfig.java
  7. 46
      Dogename/src/main/java/me/lensferno/dogename/configs/VoiceConfig.java
  8. 8
      Dogename/src/main/java/me/lensferno/dogename/configs/adapters/BooleanPropertyAdapter.java
  9. 8
      Dogename/src/main/java/me/lensferno/dogename/configs/adapters/DoublePropertyAdapter.java
  10. 8
      Dogename/src/main/java/me/lensferno/dogename/configs/adapters/IntegerPropertyAdapter.java
  11. 8
      Dogename/src/main/java/me/lensferno/dogename/configs/adapters/StringPropertyAdapter.java
  12. 17
      Dogename/src/main/java/me/lensferno/dogename/controllers/GushiciPaneController.java
  13. 96
      Dogename/src/main/java/me/lensferno/dogename/controllers/HistoryPaneController.java
  14. 16
      Dogename/src/main/java/me/lensferno/dogename/controllers/HitokotoPaneController.java
  15. 152
      Dogename/src/main/java/me/lensferno/dogename/controllers/MainInterfaceController.java
  16. 25
      Dogename/src/main/java/me/lensferno/dogename/controllers/MiniPaneController.java
  17. 74
      Dogename/src/main/java/me/lensferno/dogename/controllers/NameManagerPaneController.java
  18. 25
      Dogename/src/main/java/me/lensferno/dogename/controllers/NumberSettingsPaneController.java
  19. 11
      Dogename/src/main/java/me/lensferno/dogename/controllers/OcrPaneController.java
  20. 54
      Dogename/src/main/java/me/lensferno/dogename/controllers/ProgramInfoPaneController.java
  21. 58
      Dogename/src/main/java/me/lensferno/dogename/controllers/SettingsPaneController.java
  22. 28
      Dogename/src/main/java/me/lensferno/dogename/controllers/VoiceSettingsPaneController.java
  23. 2
      Dogename/src/main/java/me/lensferno/dogename/controllers/WindowListeners/MoveWindowByMouse.java
  24. 2
      Dogename/src/main/java/me/lensferno/dogename/controllers/WindowListeners/MoveWindowByTouch.java
  25. 115
      Dogename/src/main/java/me/lensferno/dogename/data/Data.java
  26. 55
      Dogename/src/main/java/me/lensferno/dogename/data/History.java
  27. 53
      Dogename/src/main/java/me/lensferno/dogename/sayings/Gushici.java
  28. 30
      Dogename/src/main/java/me/lensferno/dogename/sayings/Hitokoto.java
  29. 5
      Dogename/src/main/java/me/lensferno/dogename/select/Selector.java
  30. 73
      Dogename/src/main/java/me/lensferno/dogename/select/core/Worker.java
  31. 53
      Dogename/src/main/java/me/lensferno/dogename/utils/DialogMaker.java
  32. 7
      Dogename/src/main/java/me/lensferno/dogename/utils/IOUtil.java
  33. 12
      Dogename/src/main/java/me/lensferno/dogename/utils/NetworkUtil.java
  34. 8
      Dogename/src/main/java/me/lensferno/dogename/utils/Random.java
  35. 34
      Dogename/src/main/java/me/lensferno/dogename/utils/ocr/OcrTool.java
  36. 83
      Dogename/src/main/java/me/lensferno/dogename/utils/ocr/ScreenCapture.java
  37. 12
      Dogename/src/main/java/me/lensferno/dogename/voice/Token.java
  38. 97
      Dogename/src/main/java/me/lensferno/dogename/voice/TokenManager.java
  39. 7
      Dogename/src/main/java/me/lensferno/dogename/voice/VoicePlayer.java

@ -13,14 +13,7 @@
<orderEntry type="library" name="Maven: com.google.code.gson:gson:2.8.6" level="project" /> <orderEntry type="library" name="Maven: com.google.code.gson:gson:2.8.6" level="project" />
<orderEntry type="library" name="Maven: commons-codec:commons-codec:1.14" level="project" /> <orderEntry type="library" name="Maven: commons-codec:commons-codec:1.14" level="project" />
<orderEntry type="library" name="Maven: com.jfoenix:jfoenix:8.0.9" level="project" /> <orderEntry type="library" name="Maven: com.jfoenix:jfoenix:8.0.9" level="project" />
<orderEntry type="library" name="Maven: org.apache.logging.log4j:log4j-core:2.13.2" level="project" />
<orderEntry type="library" name="Maven: org.apache.logging.log4j:log4j-api:2.13.2" level="project" />
<orderEntry type="library" name="Maven: commons-io:commons-io:2.7" level="project" /> <orderEntry type="library" name="Maven: commons-io:commons-io:2.7" level="project" />
<orderEntry type="library" name="Maven: com.squareup.okhttp3:okhttp:4.2.2" level="project" />
<orderEntry type="library" name="Maven: com.squareup.okio:okio:2.2.2" level="project" />
<orderEntry type="library" name="Maven: org.jetbrains.kotlin:kotlin-stdlib:1.3.50" level="project" />
<orderEntry type="library" name="Maven: org.jetbrains.kotlin:kotlin-stdlib-common:1.3.50" level="project" />
<orderEntry type="library" name="Maven: org.jetbrains:annotations:13.0" level="project" />
<orderEntry type="library" name="Maven: com.baidu.aip:java-sdk:4.12.0" level="project" /> <orderEntry type="library" name="Maven: com.baidu.aip:java-sdk:4.12.0" level="project" />
<orderEntry type="library" name="Maven: org.json:json:20160810" level="project" /> <orderEntry type="library" name="Maven: org.json:json:20160810" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.25" level="project" /> <orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.25" level="project" />

@ -52,13 +52,6 @@
<version>8.0.9</version> <version>8.0.9</version>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.13.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency> <dependency>
<groupId>commons-io</groupId> <groupId>commons-io</groupId>

@ -1,34 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="error">
<!--先定义所有的appender-->
<appenders>
<!--这个输出控制台的配置-->
<Console name="Console" target="SYSTEM_OUT">
<!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
<ThresholdFilter level="trace" onMatch="ACCEPT" onMismatch="DENY"/>
<!--这个都知道是输出日志的格式-->
<PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %l:%m%n "/>
</Console>
<!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,这个也挺有用的,适合临时测试用-->
<File name="log" fileName="log/test.log" append="false">
<PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %l:%m%n "/>
</File>
<!--这个会打印出所有的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
<RollingFile name="RollingFile" fileName="log/app.log"
filePattern="log/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
<PatternLayout pattern=" %-5level %class{36} %L %M - %msg%xEx%n"/>
<SizeBasedTriggeringPolicy size="50MB"/>
</RollingFile>
</appenders>
<!--然后定义logger,只有定义了logger并引入的appender,appender才会生效-->
<loggers>
<!--建立一个默认的root的logger-->
<root level="trace">
<appender-ref ref="RollingFile"/>
<appender-ref ref="Console"/>
</root>
</loggers>
</configuration>

@ -9,8 +9,6 @@ import me.lensferno.dogename.configs.ConfigLoader;
import me.lensferno.dogename.controllers.MainInterfaceController; import me.lensferno.dogename.controllers.MainInterfaceController;
import me.lensferno.dogename.sayings.Gushici; import me.lensferno.dogename.sayings.Gushici;
import me.lensferno.dogename.sayings.Hitokoto; import me.lensferno.dogename.sayings.Hitokoto;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.File; import java.io.File;
import java.lang.management.ManagementFactory; import java.lang.management.ManagementFactory;
@ -18,9 +16,9 @@ import java.util.Random;
public class Main extends Application { public class Main extends Application {
Logger log = LogManager.getLogger(); public static void main(String[] args) {
launch(args);
public static void main(String[] args){ launch(args);} }
@Override @Override
public void start(Stage primaryStage) { public void start(Stage primaryStage) {
@ -34,30 +32,30 @@ public class Main extends Application {
tempFile.createNewFile(); tempFile.createNewFile();
tempFile.deleteOnExit(); tempFile.deleteOnExit();
}catch (Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
FXMLLoader fxmlLoader; FXMLLoader fxmlLoader;
Parent parent; Parent parent;
try{ try {
fxmlLoader=new FXMLLoader(getClass().getResource("/me/lensferno/dogename/FXMLs/MainInterface.fxml")); fxmlLoader = new FXMLLoader(getClass().getResource("/me/lensferno/dogename/FXMLs/MainInterface.fxml"));
parent=fxmlLoader.load(); parent = fxmlLoader.load();
}catch (Exception e){ } catch (Exception e) {
log.error("Error to load main interface FXML :"+e.toString()); System.out.println("Error to load main interface FXML :" + e);
return; return;
} }
Scene scene=new Scene(parent,990,700); Scene scene = new Scene(parent, 990, 700);
primaryStage.setTitle("DogeName 叁号姬"); primaryStage.setTitle("DogeName 叁号姬");
primaryStage.setScene(scene); primaryStage.setScene(scene);
primaryStage.show(); primaryStage.show();
ConfigLoader configLoader=new ConfigLoader(); ConfigLoader configLoader = new ConfigLoader();
MainInterfaceController mainInterfaceController=fxmlLoader.getController(); MainInterfaceController mainInterfaceController = fxmlLoader.getController();
mainInterfaceController.setToggleGroup(); mainInterfaceController.setToggleGroup();
@ -78,10 +76,10 @@ public class Main extends Application {
System.exit(0); System.exit(0);
}); });
if (new Random().nextBoolean()){ if (new Random().nextBoolean()) {
new Gushici().showGushici(mainInterfaceController.getRootPane(),mainInterfaceController.getTopBar(), mainInterfaceController.getMainConfig().isShowSaying()); new Gushici().showGushici(mainInterfaceController.getRootPane(), mainInterfaceController.getTopBar(), mainInterfaceController.getMainConfig().isShowSaying());
} else { } else {
new Hitokoto().showHitokoto(mainInterfaceController.getRootPane(),mainInterfaceController.getTopBar(), mainInterfaceController.getMainConfig().isShowSaying()); new Hitokoto().showHitokoto(mainInterfaceController.getRootPane(), mainInterfaceController.getTopBar(), mainInterfaceController.getMainConfig().isShowSaying());
} }

@ -2,29 +2,28 @@ package me.lensferno.dogename.configs;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import javafx.beans.property.*; import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import me.lensferno.dogename.configs.adapters.BooleanPropertyAdapter; import me.lensferno.dogename.configs.adapters.BooleanPropertyAdapter;
import me.lensferno.dogename.configs.adapters.DoublePropertyAdapter; import me.lensferno.dogename.configs.adapters.DoublePropertyAdapter;
import me.lensferno.dogename.configs.adapters.IntegerPropertyAdapter; import me.lensferno.dogename.configs.adapters.IntegerPropertyAdapter;
import me.lensferno.dogename.configs.adapters.StringPropertyAdapter; import me.lensferno.dogename.configs.adapters.StringPropertyAdapter;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.*; import java.io.*;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
public class ConfigLoader { public class ConfigLoader {
Logger log = LogManager.getLogger();
private final String mainConfigLocation = "files" + File.separator + "Config.json";
private final String voiceConfigLocation = "files" + File.separator + "VoiceConfig.json";
//ConfigValuesBean config; //ConfigValuesBean config;
private MainConfig mainConfig; private MainConfig mainConfig;
private VoiceConfig voiceConfig; private VoiceConfig voiceConfig;
private final String mainConfigLocation = "files"+ File.separator+"Config.json";
private final String voiceConfigLocation = "files"+ File.separator+"VoiceConfig.json";
public String getMainConfigLocation() { public String getMainConfigLocation() {
return mainConfigLocation; return mainConfigLocation;
} }
@ -37,43 +36,43 @@ public class ConfigLoader {
return mainConfig; return mainConfig;
} }
public MainConfig readConfigFromFile(String fileLocation){ public MainConfig readConfigFromFile(String fileLocation) {
//property属性应该要自定义一个json适配器才能解析出来 //property属性应该要自定义一个json适配器才能解析出来
Gson gson=new GsonBuilder() Gson gson = new GsonBuilder()
.registerTypeAdapter(SimpleBooleanProperty.class,new BooleanPropertyAdapter()) .registerTypeAdapter(SimpleBooleanProperty.class, new BooleanPropertyAdapter())
.registerTypeAdapter(SimpleIntegerProperty.class,new IntegerPropertyAdapter()) .registerTypeAdapter(SimpleIntegerProperty.class, new IntegerPropertyAdapter())
.registerTypeAdapter(SimpleStringProperty.class,new StringPropertyAdapter()) .registerTypeAdapter(SimpleStringProperty.class, new StringPropertyAdapter())
.registerTypeAdapter(SimpleDoubleProperty.class,new DoublePropertyAdapter()) .registerTypeAdapter(SimpleDoubleProperty.class, new DoublePropertyAdapter())
.setPrettyPrinting() .setPrettyPrinting()
.create(); .create();
String ConfigJSON; String ConfigJSON;
try{ try {
File configFile=new File(fileLocation); File configFile = new File(fileLocation);
if(!configFile.exists()){ if (!configFile.exists()) {
configFile.getParentFile().mkdirs(); configFile.getParentFile().mkdirs();
configFile.createNewFile(); configFile.createNewFile();
mainConfig=new MainConfig(); mainConfig = new MainConfig();
writeMainConfigToFile(mainConfigLocation); writeMainConfigToFile(mainConfigLocation);
return mainConfig; return mainConfig;
} }
InputStream inputStream=new FileInputStream(configFile); InputStream inputStream = new FileInputStream(configFile);
ConfigJSON=IOUtils.toString(inputStream, StandardCharsets.UTF_8); ConfigJSON = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
mainConfig=gson.fromJson(ConfigJSON,MainConfig.class); mainConfig = gson.fromJson(ConfigJSON, MainConfig.class);
if (mainConfig == null) { if (mainConfig == null) {
mainConfig=new MainConfig(); mainConfig = new MainConfig();
writeMainConfigToFile(mainConfigLocation); writeMainConfigToFile(mainConfigLocation);
return mainConfig; return mainConfig;
} }
}catch (Exception e){ } catch (Exception e) {
log.error("Error to load config file:"+e+"\nUse Default config."); System.out.println("Error to load config file:" + e + "\nUse Default config.");
mainConfig=new MainConfig(); mainConfig = new MainConfig();
writeMainConfigToFile(mainConfigLocation); writeMainConfigToFile(mainConfigLocation);
return mainConfig; return mainConfig;
} }
@ -81,44 +80,44 @@ public class ConfigLoader {
return this.mainConfig; return this.mainConfig;
} }
public VoiceConfig readVoiceConfigFromFile(String fileLocation){ public VoiceConfig readVoiceConfigFromFile(String fileLocation) {
//property属性应该要自定义一个json适配器才能解析出来 //property属性应该要自定义一个json适配器才能解析出来
Gson gson=new GsonBuilder() Gson gson = new GsonBuilder()
.registerTypeAdapter(SimpleBooleanProperty.class,new BooleanPropertyAdapter()) .registerTypeAdapter(SimpleBooleanProperty.class, new BooleanPropertyAdapter())
.registerTypeAdapter(SimpleIntegerProperty.class,new IntegerPropertyAdapter()) .registerTypeAdapter(SimpleIntegerProperty.class, new IntegerPropertyAdapter())
.registerTypeAdapter(SimpleStringProperty.class,new StringPropertyAdapter()) .registerTypeAdapter(SimpleStringProperty.class, new StringPropertyAdapter())
.registerTypeAdapter(SimpleDoubleProperty.class,new DoublePropertyAdapter()) .registerTypeAdapter(SimpleDoubleProperty.class, new DoublePropertyAdapter())
.setPrettyPrinting() .setPrettyPrinting()
.create(); .create();
String ConfigJSON; String ConfigJSON;
try{ try {
File configFile=new File(fileLocation); File configFile = new File(fileLocation);
if(!configFile.exists()){ if (!configFile.exists()) {
configFile.getParentFile().mkdirs(); configFile.getParentFile().mkdirs();
configFile.createNewFile(); configFile.createNewFile();
voiceConfig=new VoiceConfig(); voiceConfig = new VoiceConfig();
writeVoiceConfigToFile(voiceConfigLocation); writeVoiceConfigToFile(voiceConfigLocation);
return voiceConfig; return voiceConfig;
} }
InputStream inputStream=new FileInputStream(configFile); InputStream inputStream = new FileInputStream(configFile);
ConfigJSON=IOUtils.toString(inputStream, StandardCharsets.UTF_8); ConfigJSON = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
writeVoiceConfigToFile(voiceConfigLocation); writeVoiceConfigToFile(voiceConfigLocation);
voiceConfig=gson.fromJson(ConfigJSON,VoiceConfig.class); voiceConfig = gson.fromJson(ConfigJSON, VoiceConfig.class);
if (voiceConfig == null) { if (voiceConfig == null) {
voiceConfig=new VoiceConfig(); voiceConfig = new VoiceConfig();
writeVoiceConfigToFile(voiceConfigLocation); writeVoiceConfigToFile(voiceConfigLocation);
return voiceConfig; return voiceConfig;
} }
}catch (Exception e){ } catch (Exception e) {
log.error("Error to load voice config file:"+e+"\nUse Default voice config."); System.out.println("Error to load voice config file:" + e + "\nUse Default voice config.");
voiceConfig=new VoiceConfig(); voiceConfig = new VoiceConfig();
writeVoiceConfigToFile(voiceConfigLocation); writeVoiceConfigToFile(voiceConfigLocation);
return voiceConfig; return voiceConfig;
} }
@ -127,85 +126,85 @@ public class ConfigLoader {
} }
// //
public MainConfig setValuesToProperty(){ public MainConfig setValuesToProperty() {
//mainconfig.set..(config.get..) //mainconfig.set..(config.get..)
//...so on //...so on
// //
return this.mainConfig; return this.mainConfig;
} }
private String toJSON(MainConfig config){ private String toJSON(MainConfig config) {
Gson gson=new GsonBuilder() Gson gson = new GsonBuilder()
.registerTypeAdapter(SimpleBooleanProperty.class,new BooleanPropertyAdapter()) .registerTypeAdapter(SimpleBooleanProperty.class, new BooleanPropertyAdapter())
.registerTypeAdapter(SimpleIntegerProperty.class,new IntegerPropertyAdapter()) .registerTypeAdapter(SimpleIntegerProperty.class, new IntegerPropertyAdapter())
.registerTypeAdapter(SimpleStringProperty.class,new StringPropertyAdapter()) .registerTypeAdapter(SimpleStringProperty.class, new StringPropertyAdapter())
.setPrettyPrinting() .setPrettyPrinting()
.create(); .create();
return gson.toJson(config); return gson.toJson(config);
} }
private String VoiceConfigtoJSON(VoiceConfig config){ private String VoiceConfigtoJSON(VoiceConfig config) {
Gson gson=new GsonBuilder() Gson gson = new GsonBuilder()
.registerTypeAdapter(SimpleDoubleProperty.class,new DoublePropertyAdapter()) .registerTypeAdapter(SimpleDoubleProperty.class, new DoublePropertyAdapter())
.setPrettyPrinting() .setPrettyPrinting()
.create(); .create();
return gson.toJson(config); return gson.toJson(config);
} }
public void writeAllConfigToFile(String outputLocation, String voiceConfigFile){ public void writeAllConfigToFile(String outputLocation, String voiceConfigFile) {
File outputFile = new File(outputLocation); File outputFile = new File(outputLocation);
try{ try {
if(! outputFile.exists()){ if (!outputFile.exists()) {
outputFile.getParentFile().mkdirs(); outputFile.getParentFile().mkdirs();
outputFile.createNewFile(); outputFile.createNewFile();
} }
OutputStream stream=new FileOutputStream(outputFile); OutputStream stream = new FileOutputStream(outputFile);
IOUtils.write(toJSON(this.mainConfig).getBytes(StandardCharsets.UTF_8),stream); IOUtils.write(toJSON(this.mainConfig).getBytes(StandardCharsets.UTF_8), stream);
OutputStream voiceConfigFileStream=new FileOutputStream(voiceConfigFile); OutputStream voiceConfigFileStream = new FileOutputStream(voiceConfigFile);
IOUtils.write(VoiceConfigtoJSON(this.voiceConfig).getBytes(StandardCharsets.UTF_8),voiceConfigFileStream); IOUtils.write(VoiceConfigtoJSON(this.voiceConfig).getBytes(StandardCharsets.UTF_8), voiceConfigFileStream);
}catch (Exception e){ } catch (Exception e) {
log.error("Error in writing all config:"+e); System.out.println("Error in writing all config:" + e);
} }
} }
public void writeMainConfigToFile(String outputLocation){ public void writeMainConfigToFile(String outputLocation) {
File outputFile = new File(outputLocation); File outputFile = new File(outputLocation);
try{ try {
if(! outputFile.exists()){ if (!outputFile.exists()) {
outputFile.getParentFile().mkdirs(); outputFile.getParentFile().mkdirs();
outputFile.createNewFile(); outputFile.createNewFile();
} }
OutputStream stream=new FileOutputStream(outputFile); OutputStream stream = new FileOutputStream(outputFile);
IOUtils.write(toJSON(this.mainConfig).getBytes(StandardCharsets.UTF_8),stream); IOUtils.write(toJSON(this.mainConfig).getBytes(StandardCharsets.UTF_8), stream);
}catch (Exception e){ } catch (Exception e) {
log.error("Error in writing main config:"+e); System.out.println("Error in writing main config:" + e);
} }
} }
public void writeVoiceConfigToFile(String voiceConfigFile){ public void writeVoiceConfigToFile(String voiceConfigFile) {
File outputFile = new File(voiceConfigFile); File outputFile = new File(voiceConfigFile);
try{ try {
if(! outputFile.exists()) { if (!outputFile.exists()) {
outputFile.getParentFile().mkdirs(); outputFile.getParentFile().mkdirs();
outputFile.createNewFile(); outputFile.createNewFile();
} }
OutputStream voiceConfigFileStream=new FileOutputStream(voiceConfigFile); OutputStream voiceConfigFileStream = new FileOutputStream(voiceConfigFile);
IOUtils.write(VoiceConfigtoJSON(this.voiceConfig).getBytes(StandardCharsets.UTF_8),voiceConfigFileStream); IOUtils.write(VoiceConfigtoJSON(this.voiceConfig).getBytes(StandardCharsets.UTF_8), voiceConfigFileStream);
}catch (Exception e){ } catch (Exception e) {
log.error("Error in writing voice config:"+e); System.out.println("Error in writing voice config:" + e);
} }
} }

@ -1,55 +1,48 @@
package me.lensferno.dogename.configs; package me.lensferno.dogename.configs;
import com.google.gson.annotations.Expose; import com.google.gson.annotations.Expose;
import javafx.beans.property.*; import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
public class MainConfig { public class MainConfig {
// ---------------------- Default values --------------------------------------------------------- // ---------------------- Default values ---------------------------------------------------------
private final int currentVersion = 3;
@Expose @Expose
public static final boolean DEFAULT_NAME_CHOOSE = true; public static final boolean DEFAULT_NAME_CHOOSE = true;
public static final int METHOD_NAME = 0; // 名字挑选法 public static final int METHOD_NAME = 0; // 名字挑选法
public static final int METHOD_NUMBER = 1; // 数字挑选法 public static final int METHOD_NUMBER = 1; // 数字挑选法
public static final int DEFAULT_MAX_TOTAL_COUNT = 120; // 默认轮回次数:120 public static final int DEFAULT_MAX_TOTAL_COUNT = 120; // 默认轮回次数:120
public static final int DEFAULT_SPEED = 80; // 默认速度:20ms,对应滑动条80的位置 public static final int DEFAULT_SPEED = 80; // 默认速度:20ms,对应滑动条80的位置
public static final boolean DEFAULT_RANDOM_TIMES = true; // 默认挑选轮回次数是否随机:ture public static final boolean DEFAULT_RANDOM_TIMES = true; // 默认挑选轮回次数是否随机:ture
public static final boolean DEFAULT_IGNORE_PAST = true; // 默认忽略已经点过的名字:ture public static final boolean DEFAULT_IGNORE_PAST = true; // 默认忽略已经点过的名字:ture
public static final boolean DEFAULT_EQUAL_MODE = true; // 默认开启"机会均等" public static final boolean DEFAULT_EQUAL_MODE = true; // 默认开启"机会均等"
public static final boolean DEFAULT_NEW_ALGO = true; // 默认使用新算法"Java sec random" public static final boolean DEFAULT_NEW_ALGO = true; // 默认使用新算法"Java sec random"
public static final boolean DEFAULT_VOICE_PLAY = true; // 默认使用语音播报 public static final boolean DEFAULT_VOICE_PLAY = true; // 默认使用语音播报
public static final boolean DEFAULT_SHOW_SAYING = true; public static final boolean DEFAULT_SHOW_SAYING = true;
private final int currentVersion = 3;
// ----------------------Properties---------------------------------------------------------------- // ----------------------Properties----------------------------------------------------------------
private final SimpleBooleanProperty nameChoose;
private SimpleBooleanProperty nameChoose; private final SimpleBooleanProperty randomCount; // 挑选次数是否随机
private final SimpleBooleanProperty passSelectedResult; // 是否忽略已经被点过的名字/数字
private SimpleBooleanProperty randomCount; // 挑选次数是否随机
private SimpleBooleanProperty passSelectedResult; // 是否忽略已经被点过的名字/数字
private SimpleIntegerProperty chooseMethod; // 挑选方式: 0->名字挑选法 1->数字挑选法 private final SimpleIntegerProperty chooseMethod; // 挑选方式: 0->名字挑选法 1->数字挑选法
private SimpleIntegerProperty maxTotalCount; // 挑选轮回次数 private final SimpleIntegerProperty maxTotalCount; // 挑选轮回次数
private SimpleIntegerProperty speed; // 速度 private final SimpleIntegerProperty speed; // 速度
private SimpleStringProperty minNumber; // 最小值 private final SimpleStringProperty minNumber; // 最小值
private SimpleStringProperty maxNumber; // 最大值 private final SimpleStringProperty maxNumber; // 最大值
private SimpleBooleanProperty equalMode; // 是否开启"机会均等" private final SimpleBooleanProperty equalMode; // 是否开启"机会均等"
private SimpleBooleanProperty secureRandom; // 是否使用secure random private final SimpleBooleanProperty secureRandom; // 是否使用secure random
private SimpleBooleanProperty voicePlay; // 是否使用语音播报 private final SimpleBooleanProperty voicePlay; // 是否使用语音播报
private SimpleBooleanProperty showSaying; private final SimpleBooleanProperty showSaying;
// -------------------------- 初始化 -------------------------------------------------------------- // -------------------------- 初始化 --------------------------------------------------------------
public MainConfig() { public MainConfig() {
@ -80,146 +73,146 @@ public class MainConfig {
return nameChoose.get(); return nameChoose.get();
} }
public SimpleBooleanProperty nameChooseProperty() {
return nameChoose;
}
public void setNameChoose(boolean nameChoose) { public void setNameChoose(boolean nameChoose) {
this.nameChoose.set(nameChoose); this.nameChoose.set(nameChoose);
} }
public boolean getRandomCount() { public SimpleBooleanProperty nameChooseProperty() {
return randomCount.get(); return nameChoose;
} }
public SimpleBooleanProperty randomCountProperty() { public boolean getRandomCount() {
return randomCount; return randomCount.get();
} }
public void setRandomCount(boolean randomCount) { public void setRandomCount(boolean randomCount) {
this.randomCount.set(randomCount); this.randomCount.set(randomCount);
} }
public boolean getPassSelectedResult() { public SimpleBooleanProperty randomCountProperty() {
return passSelectedResult.get(); return randomCount;
} }
public SimpleBooleanProperty passSelectedResultProperty() { public boolean getPassSelectedResult() {
return passSelectedResult; return passSelectedResult.get();
} }
public void setPassSelectedResult(boolean passSelectedResult) { public void setPassSelectedResult(boolean passSelectedResult) {
this.passSelectedResult.set(passSelectedResult); this.passSelectedResult.set(passSelectedResult);
} }
public int getChooseMethod() { public SimpleBooleanProperty passSelectedResultProperty() {
return chooseMethod.get(); return passSelectedResult;
} }
public SimpleIntegerProperty chooseMethodProperty() { public int getChooseMethod() {
return chooseMethod; return chooseMethod.get();
} }
public void setChooseMethod(int chooseMethod) { public void setChooseMethod(int chooseMethod) {
this.chooseMethod.set(chooseMethod); this.chooseMethod.set(chooseMethod);
} }
public int getMaxTotalCount() { public SimpleIntegerProperty chooseMethodProperty() {
return maxTotalCount.get(); return chooseMethod;
} }
public SimpleIntegerProperty maxTotalCountProperty() { public int getMaxTotalCount() {
return maxTotalCount; return maxTotalCount.get();
} }
public void setMaxTotalCount(int maxTotalCount) { public void setMaxTotalCount(int maxTotalCount) {
this.maxTotalCount.set(maxTotalCount); this.maxTotalCount.set(maxTotalCount);
} }
public int getSpeed() { public SimpleIntegerProperty maxTotalCountProperty() {
return speed.get(); return maxTotalCount;
} }
public SimpleIntegerProperty speedProperty() { public int getSpeed() {
return speed; return speed.get();
} }
public void setSpeed(int speed) { public void setSpeed(int speed) {
this.speed.set(speed); this.speed.set(speed);
} }
public String getMinNumber() { public SimpleIntegerProperty speedProperty() {
return minNumber.get(); return speed;
} }
public SimpleStringProperty minNumberProperty() { public String getMinNumber() {
return minNumber; return minNumber.get();
} }
public void setMinNumber(String minNumber) { public void setMinNumber(String minNumber) {
this.minNumber.set(minNumber); this.minNumber.set(minNumber);
} }
public String getMaxNumber() { public SimpleStringProperty minNumberProperty() {
return maxNumber.get(); return minNumber;
} }
public SimpleStringProperty maxNumberProperty() { public String getMaxNumber() {
return maxNumber; return maxNumber.get();
} }
public void setMaxNumber(String maxNumber) { public void setMaxNumber(String maxNumber) {
this.maxNumber.set(maxNumber); this.maxNumber.set(maxNumber);
} }
public boolean getEqualMode() { public SimpleStringProperty maxNumberProperty() {
return equalMode.get(); return maxNumber;
} }
public SimpleBooleanProperty equalModeProperty() { public boolean getEqualMode() {
return equalMode; return equalMode.get();
} }
public void setEqualMode(boolean equalMode) { public void setEqualMode(boolean equalMode) {
this.equalMode.set(equalMode); this.equalMode.set(equalMode);
} }
public boolean getSecureRandom() { public SimpleBooleanProperty equalModeProperty() {
return secureRandom.get(); return equalMode;
} }
public SimpleBooleanProperty secureRandomProperty() { public boolean getSecureRandom() {
return secureRandom; return secureRandom.get();
} }
public void setSecureRandom(boolean secureRandom) { public void setSecureRandom(boolean secureRandom) {
this.secureRandom.set(secureRandom); this.secureRandom.set(secureRandom);
} }
public boolean getVoicePlay() { public SimpleBooleanProperty secureRandomProperty() {
return voicePlay.get(); return secureRandom;
} }
public SimpleBooleanProperty voicePlayProperty() { public boolean getVoicePlay() {
return voicePlay; return voicePlay.get();
} }
public void setVoicePlay(boolean voicePlay) { public void setVoicePlay(boolean voicePlay) {
this.voicePlay.set(voicePlay); this.voicePlay.set(voicePlay);
} }
public boolean isShowSaying() { public SimpleBooleanProperty voicePlayProperty() {
return showSaying.get(); return voicePlay;
} }
public SimpleBooleanProperty showSayingProperty() { public boolean isShowSaying() {
return showSaying; return showSaying.get();
} }
public void setShowSaying(boolean showSaying) { public void setShowSaying(boolean showSaying) {
this.showSaying.set(showSaying); this.showSaying.set(showSaying);
} }
public SimpleBooleanProperty showSayingProperty() {
return showSaying;
}
public int getCurrentConfigVersion() { public int getCurrentConfigVersion() {
return currentVersion; return currentVersion;
} }

@ -6,15 +6,23 @@ import javafx.fxml.FXML;
public class VoiceConfig { public class VoiceConfig {
private String speaker; public final int DEFAULT_SPEED = 5;
private int selectedSpeaker; public final int DEFAULT_INTONATION = 5;
//度小宇=1,度小美=0,度逍遥=3,度丫丫=4 //度小宇=1,度小美=0,度逍遥=3,度丫丫=4
//度博文=106,度小童=110,度小萌=111,度米朵=103,度小娇=5 //度博文=106,度小童=110,度小萌=111,度米朵=103,度小娇=5
private String speaker;
private SimpleDoubleProperty speed; private int selectedSpeaker;
private SimpleDoubleProperty intonation; private final SimpleDoubleProperty speed;
private final SimpleDoubleProperty intonation;
public VoiceConfig() {
selectedSpeaker = 0;
speaker = "1";
speed = new SimpleDoubleProperty(DEFAULT_SPEED);
intonation = new SimpleDoubleProperty(DEFAULT_INTONATION);
}
public String getSpeaker() { public String getSpeaker() {
return speaker; return speaker;
@ -24,16 +32,6 @@ public class VoiceConfig {
this.speaker = speaker; this.speaker = speaker;
} }
public final int DEFAULT_SPEED=5;
public final int DEFAULT_INTONATION=5;
public VoiceConfig(){
selectedSpeaker=0;
speaker="1";
speed=new SimpleDoubleProperty(DEFAULT_SPEED);
intonation=new SimpleDoubleProperty(DEFAULT_INTONATION);
}
public int getSelectedSpeaker() { public int getSelectedSpeaker() {
return selectedSpeaker; return selectedSpeaker;
} }
@ -41,35 +39,35 @@ public class VoiceConfig {
public void setSelectedSpeaker(int selectedSpeaker) { public void setSelectedSpeaker(int selectedSpeaker) {
this.selectedSpeaker = selectedSpeaker; this.selectedSpeaker = selectedSpeaker;
} }
public double getSpeed() { public double getSpeed() {
return speed.get(); return speed.get();
} }
public SimpleDoubleProperty speedProperty() {
return speed;
}
public void setSpeed(double speed) { public void setSpeed(double speed) {
this.speed.set(speed); this.speed.set(speed);
} }
public double getIntonation() { public SimpleDoubleProperty speedProperty() {
return intonation.get(); return speed;
} }
public SimpleDoubleProperty intonationProperty() { public double getIntonation() {
return intonation; return intonation.get();
} }
public void setIntonation(double intonation) { public void setIntonation(double intonation) {
this.intonation.set(intonation); this.intonation.set(intonation);
} }
public SimpleDoubleProperty intonationProperty() {
return intonation;
}
@FXML @FXML
void showAdvancedVoiceSettings(ActionEvent event) { void showAdvancedVoiceSettings(ActionEvent event) {
} }
} }

@ -9,18 +9,18 @@ public class BooleanPropertyAdapter implements JsonSerializer<SimpleBooleanPrope
@Override @Override
public SimpleBooleanProperty deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { public SimpleBooleanProperty deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
if(jsonElement==null) { if (jsonElement == null) {
throw new JsonParseException("Json is wrong."); throw new JsonParseException("Json is wrong.");
}else { } else {
return new SimpleBooleanProperty(jsonElement.getAsBoolean()); return new SimpleBooleanProperty(jsonElement.getAsBoolean());
} }
} }
@Override @Override
public JsonElement serialize(SimpleBooleanProperty simpleBooleanProperty, Type type, JsonSerializationContext jsonSerializationContext) { public JsonElement serialize(SimpleBooleanProperty simpleBooleanProperty, Type type, JsonSerializationContext jsonSerializationContext) {
if(simpleBooleanProperty==null){ if (simpleBooleanProperty == null) {
throw new JsonParseException("Json is wrong."); throw new JsonParseException("Json is wrong.");
}else { } else {
return new JsonPrimitive(simpleBooleanProperty.get()); return new JsonPrimitive(simpleBooleanProperty.get());
} }
} }

@ -9,18 +9,18 @@ public class DoublePropertyAdapter implements JsonSerializer<SimpleDoublePropert
@Override @Override
public SimpleDoubleProperty deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { public SimpleDoubleProperty deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
if(jsonElement==null) { if (jsonElement == null) {
throw new JsonParseException("Json is wrong."); throw new JsonParseException("Json is wrong.");
}else { } else {
return new SimpleDoubleProperty(jsonElement.getAsDouble()); return new SimpleDoubleProperty(jsonElement.getAsDouble());
} }
} }
@Override @Override
public JsonElement serialize(SimpleDoubleProperty simpleDoubleProperty, Type type, JsonSerializationContext jsonSerializationContext) { public JsonElement serialize(SimpleDoubleProperty simpleDoubleProperty, Type type, JsonSerializationContext jsonSerializationContext) {
if(simpleDoubleProperty==null){ if (simpleDoubleProperty == null) {
throw new JsonParseException("Json is wrong."); throw new JsonParseException("Json is wrong.");
}else { } else {
return new JsonPrimitive(simpleDoubleProperty.get()); return new JsonPrimitive(simpleDoubleProperty.get());
} }
} }

@ -8,18 +8,18 @@ import java.lang.reflect.Type;
public class IntegerPropertyAdapter implements JsonSerializer<SimpleIntegerProperty>, JsonDeserializer<SimpleIntegerProperty> { public class IntegerPropertyAdapter implements JsonSerializer<SimpleIntegerProperty>, JsonDeserializer<SimpleIntegerProperty> {
@Override @Override
public SimpleIntegerProperty deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { public SimpleIntegerProperty deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
if(jsonElement==null) { if (jsonElement == null) {
throw new JsonParseException("Json is wrong."); throw new JsonParseException("Json is wrong.");
}else { } else {
return new SimpleIntegerProperty(jsonElement.getAsInt()); return new SimpleIntegerProperty(jsonElement.getAsInt());
} }
} }
@Override @Override
public JsonElement serialize(SimpleIntegerProperty simpleIntegerProperty, Type type, JsonSerializationContext jsonSerializationContext) { public JsonElement serialize(SimpleIntegerProperty simpleIntegerProperty, Type type, JsonSerializationContext jsonSerializationContext) {
if(simpleIntegerProperty==null){ if (simpleIntegerProperty == null) {
throw new JsonParseException("Json is wrong."); throw new JsonParseException("Json is wrong.");
}else { } else {
return new JsonPrimitive(simpleIntegerProperty.get()); return new JsonPrimitive(simpleIntegerProperty.get());
} }
} }

@ -8,18 +8,18 @@ import java.lang.reflect.Type;
public class StringPropertyAdapter implements JsonSerializer<SimpleStringProperty>, JsonDeserializer<SimpleStringProperty> { public class StringPropertyAdapter implements JsonSerializer<SimpleStringProperty>, JsonDeserializer<SimpleStringProperty> {
@Override @Override
public SimpleStringProperty deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { public SimpleStringProperty deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
if(jsonElement==null) { if (jsonElement == null) {
throw new JsonParseException("Json is wrong."); throw new JsonParseException("Json is wrong.");
}else { } else {
return new SimpleStringProperty(jsonElement.getAsString()); return new SimpleStringProperty(jsonElement.getAsString());
} }
} }
@Override @Override
public JsonElement serialize(SimpleStringProperty simpleStringProperty, Type type, JsonSerializationContext jsonSerializationContext) { public JsonElement serialize(SimpleStringProperty simpleStringProperty, Type type, JsonSerializationContext jsonSerializationContext) {
if(simpleStringProperty==null) { if (simpleStringProperty == null) {
throw new JsonParseException("Json is wrong."); throw new JsonParseException("Json is wrong.");
}else { } else {
return new JsonPrimitive(simpleStringProperty.get()); return new JsonPrimitive(simpleStringProperty.get());
} }
} }

@ -4,13 +4,10 @@ import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader; import javafx.fxml.FXMLLoader;
import javafx.scene.layout.VBox; import javafx.scene.layout.VBox;
import javafx.scene.text.Text; import javafx.scene.text.Text;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class GushiciPaneController extends VBox { public class GushiciPaneController extends VBox {
Logger log= LogManager.getLogger();
@FXML @FXML
public Text contentText; public Text contentText;
@ -20,20 +17,18 @@ public class GushiciPaneController extends VBox {
@FXML @FXML
public Text contentInfo; public Text contentInfo;
public GushiciPaneController (String content,String title,String author,String type){ public GushiciPaneController(String content, String title, String author, String type) {
FXMLLoader loader=new FXMLLoader(getClass().getResource("/me/lensferno/dogename/FXMLs/GushiciPane.fxml")); FXMLLoader loader = new FXMLLoader(getClass().getResource("/me/lensferno/dogename/FXMLs/GushiciPane.fxml"));
loader.setRoot(this); loader.setRoot(this);
loader.setController(this); loader.setController(this);
try { try {
loader.load(); loader.load();
}catch(Exception e){ } catch (Exception e) {
log.error("Error to load Gushici pane FXML: "+e.toString()); e.printStackTrace();
//e.printStackTrace();
} }
contentText.setText("“"+content+"”"); contentText.setText("“" + content + "”");
contentInfo.setText("《"+title+"》"+"——"+author); contentInfo.setText("《" + title + "》" + "——" + author);
contentType.setText(type); contentType.setText(type);
} }
} }

@ -1,6 +1,8 @@
package me.lensferno.dogename.controllers; package me.lensferno.dogename.controllers;
import com.jfoenix.controls.*; import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXListView;
import com.jfoenix.controls.JFXTextField;
import javafx.collections.FXCollections; import javafx.collections.FXCollections;
import javafx.collections.ObservableList; import javafx.collections.ObservableList;
import javafx.event.ActionEvent; import javafx.event.ActionEvent;
@ -8,25 +10,33 @@ import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader; import javafx.fxml.FXMLLoader;
import javafx.scene.layout.Pane; import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox; import javafx.scene.layout.VBox;
import me.lensferno.dogename.utils.DialogMaker;
import me.lensferno.dogename.data.History; import me.lensferno.dogename.data.History;
import org.apache.logging.log4j.LogManager; import me.lensferno.dogename.utils.DialogMaker;
import org.apache.logging.log4j.Logger;
public class HistoryPaneController extends VBox { public class HistoryPaneController extends VBox {
Logger log= LogManager.getLogger(HitokotoPaneController.class);
public static final ObservableList<String> shownHistoryList = FXCollections.observableArrayList();
History history; History history;
Pane rootPane; Pane rootPane;
int pointer = 0;
@FXML
private JFXListView<String> historyList;
public static final ObservableList<String> shownHistoryList = FXCollections.observableArrayList(); @FXML
private JFXTextField searchBar;
@FXML
private JFXButton previousBtn;
@FXML
private JFXButton nextBtn;
public HistoryPaneController(History history, Pane rootPane){ public HistoryPaneController(History history, Pane rootPane) {
FXMLLoader loader=new FXMLLoader(getClass().getResource("/me/lensferno/dogename/FXMLs/HistoryPane.fxml")); FXMLLoader loader = new FXMLLoader(getClass().getResource("/me/lensferno/dogename/FXMLs/HistoryPane.fxml"));
loader.setRoot(this); loader.setRoot(this);
loader.setController(this); loader.setController(this);
this.history=history; this.history = history;
this.rootPane=rootPane; this.rootPane = rootPane;
try { try {
loader.load(); loader.load();
@ -34,54 +44,40 @@ public class HistoryPaneController extends VBox {
historyList.setItems(shownHistoryList); historyList.setItems(shownHistoryList);
searchBar.textProperty().addListener((observable, oldValue, newValue) -> pointer = 0); searchBar.textProperty().addListener((observable, oldValue, newValue) -> pointer = 0);
}catch(Exception e){ } catch (Exception e) {
log.error("Error in loading history Fxml:"+e.toString()); e.printStackTrace();
} }
} }
@FXML private void pointOutSearchResult(int pointer) {
private JFXListView<String> historyList;
@FXML
private JFXTextField searchBar;
@FXML
private JFXButton previousBtn;
@FXML
private JFXButton nextBtn;
private void pointOutSearchResult(int pointer){
historyList.getSelectionModel().select(pointer); historyList.getSelectionModel().select(pointer);
} }
int pointer=0;
@FXML @FXML
void upSearch(ActionEvent event) { void upSearch(ActionEvent event) {
String searchText=searchBar.getText(); String searchText = searchBar.getText();
String[] historyArrayList =history.getHistoryList().toArray(new String[0]); String[] historyArrayList = history.getHistoryList().toArray(new String[0]);
if (historyArrayList.length==0){ if (historyArrayList.length == 0) {
return; return;
} }
if (pointer>historyArrayList.length-1||pointer<0){ if (pointer > historyArrayList.length - 1 || pointer < 0) {
pointer=historyArrayList.length-1; pointer = historyArrayList.length - 1;
} }
while (!historyArrayList[pointer].contains(searchText)){ while (!historyArrayList[pointer].contains(searchText)) {
pointer--; pointer--;
if (pointer<0){ if (pointer < 0) {
pointer=historyArrayList.length-1; pointer = historyArrayList.length - 1;
return; return;
} }
} }
pointOutSearchResult(pointer); pointOutSearchResult(pointer);
pointer--; pointer--;
if (pointer<0){ if (pointer < 0) {
pointer=historyArrayList.length-1; pointer = historyArrayList.length - 1;
} }
} }
@ -89,37 +85,37 @@ public class HistoryPaneController extends VBox {
@FXML @FXML
void downSearch(ActionEvent event) { void downSearch(ActionEvent event) {
String searchText=searchBar.getText(); String searchText = searchBar.getText();
String[] historyArrayList =history.getHistoryList().toArray(new String[0]); String[] historyArrayList = history.getHistoryList().toArray(new String[0]);
if (historyArrayList.length==0){ if (historyArrayList.length == 0) {
return; return;
} }
if (pointer>historyArrayList.length-1||pointer<0){ if (pointer > historyArrayList.length - 1 || pointer < 0) {
pointer=0; pointer = 0;
} }
while (!historyArrayList[pointer].contains(searchText)){ while (!historyArrayList[pointer].contains(searchText)) {
pointer++; pointer++;
if (pointer<historyArrayList.length-1){ if (pointer < historyArrayList.length - 1) {
pointer=0; pointer = 0;
return; return;
} }
} }
pointOutSearchResult(pointer); pointOutSearchResult(pointer);
pointer++; pointer++;
if (pointer<historyArrayList.length-1){ if (pointer < historyArrayList.length - 1) {
pointer=0; pointer = 0;
} }
} }
@FXML @FXML
void clearHistory(){ void clearHistory() {
new DialogMaker(rootPane).createDialogWithOKAndCancel("且慢!","真的要清除全部历史记录吗?",(e)-> { new DialogMaker(rootPane).createDialogWithOKAndCancel("且慢!", "真的要清除全部历史记录吗?", (e) -> {
this.history.clearHistory(); this.history.clearHistory();
pointer=0; pointer = 0;
}); });
} }

@ -5,12 +5,9 @@ import javafx.fxml.FXMLLoader;
import javafx.scene.layout.VBox; import javafx.scene.layout.VBox;
import javafx.scene.text.Text; import javafx.scene.text.Text;
import java.util.logging.Logger;
public class HitokotoPaneController extends VBox { public class HitokotoPaneController extends VBox {
Logger log=Logger.getLogger("HitokotoPaneLogger");
@FXML @FXML
private Text hitokotoContent; private Text hitokotoContent;
@ -20,19 +17,18 @@ public class HitokotoPaneController extends VBox {
@FXML @FXML
private Text contentInfo; private Text contentInfo;
public HitokotoPaneController(String hitokoto, String from,String author,String creator,String type){ public HitokotoPaneController(String hitokoto, String from, String author, String creator, String type) {
FXMLLoader loader=new FXMLLoader(getClass().getResource("/me/lensferno/dogename/FXMLs/HitokotoPane.fxml")); FXMLLoader loader = new FXMLLoader(getClass().getResource("/me/lensferno/dogename/FXMLs/HitokotoPane.fxml"));
loader.setRoot(this); loader.setRoot(this);
loader.setController(this); loader.setController(this);
try { try {
loader.load(); loader.load();
}catch(Exception e){ } catch (Exception e) {
log.warning("Error to load Gushici pane FXML: "+e.toString()); e.printStackTrace();
//e.printStackTrace();
} }
hitokotoContent.setText("『 "+hitokoto+" 』"); hitokotoContent.setText("『 " + hitokoto + " 』");
contentInfo.setText("出自:"+from+"  |  作者:"+author+"  |  上传者:"+creator); contentInfo.setText("出自:" + from + "  |  作者:" + author + "  |  上传者:" + creator);
contentType.setText(type); contentType.setText(type);
} }
} }

@ -1,27 +1,28 @@
package me.lensferno.dogename.controllers; package me.lensferno.dogename.controllers;
import com.jfoenix.controls.*; import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXRadioButton;
import com.jfoenix.controls.JFXTextArea;
import javafx.event.ActionEvent; import javafx.event.ActionEvent;
import javafx.fxml.FXML; import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader; import javafx.fxml.FXMLLoader;
import javafx.scene.Parent; import javafx.scene.Parent;
import javafx.scene.Scene; import javafx.scene.Scene;
import javafx.scene.control.*; import javafx.scene.control.Label;
import javafx.scene.control.ToggleGroup;
import javafx.scene.image.Image; import javafx.scene.image.Image;
import javafx.scene.image.ImageView; import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane; import javafx.scene.layout.Pane;
import javafx.stage.Stage; import javafx.stage.Stage;
import javafx.stage.StageStyle; import javafx.stage.StageStyle;
import me.lensferno.dogename.select.Selector;
import me.lensferno.dogename.utils.DialogMaker;
import me.lensferno.dogename.configs.ConfigLoader; import me.lensferno.dogename.configs.ConfigLoader;
import me.lensferno.dogename.configs.MainConfig; import me.lensferno.dogename.configs.MainConfig;
import me.lensferno.dogename.configs.VoiceConfig; import me.lensferno.dogename.configs.VoiceConfig;
import me.lensferno.dogename.data.History;
import me.lensferno.dogename.data.Data; import me.lensferno.dogename.data.Data;
import me.lensferno.dogename.data.History;
import me.lensferno.dogename.select.Selector;
import me.lensferno.dogename.utils.DialogMaker;
import me.lensferno.dogename.utils.ocr.OcrTool; import me.lensferno.dogename.utils.ocr.OcrTool;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -32,54 +33,44 @@ public final class MainInterfaceController {
public JFXTextArea message; public JFXTextArea message;
OcrTool ocrTool=null; OcrTool ocrTool = null;
History history=new History();
History history = new History();
MainConfig mainConfig;
VoiceConfig voiceConfig;
Random random = new Random();
Data data = new Data();
Selector selector = new Selector();
@FXML @FXML
private Pane rootPane; private Pane rootPane;
@FXML @FXML
private JFXRadioButton nameChoose; private JFXRadioButton nameChoose;
@FXML @FXML
private JFXButton showHistoryBtn; private JFXButton showHistoryBtn;
@FXML @FXML
private JFXRadioButton numbChoose; private JFXRadioButton numbChoose;
@FXML @FXML
private JFXButton anPaiBtn; private JFXButton anPaiBtn;
@FXML @FXML
private Pane mainPane; private Pane mainPane;
@FXML @FXML
private Label topBar; private Label topBar;
@FXML @FXML
private JFXButton showNameMangerButton; private JFXButton showNameMangerButton;
@FXML @FXML
private Label upperLabel; private Label upperLabel;
@FXML @FXML
private ImageView mainView; private ImageView mainView;
@FXML @FXML
private JFXButton miniModeBtn; private JFXButton miniModeBtn;
@FXML @FXML
private Label downLabel; private Label downLabel;
public MainInterfaceController(){ public MainInterfaceController() {
history.loadHistory(); history.loadHistory();
} }
MainConfig mainConfig; public void bindProperties() {
VoiceConfig voiceConfig;
public void bindProperties(){
nameChoose.selectedProperty().bindBidirectional(mainConfig.nameChooseProperty()); nameChoose.selectedProperty().bindBidirectional(mainConfig.nameChooseProperty());
numbChoose.selectedProperty().bind(mainConfig.nameChooseProperty().not()); numbChoose.selectedProperty().bind(mainConfig.nameChooseProperty().not());
@ -90,67 +81,64 @@ public final class MainInterfaceController {
}); });
} }
public void setImg(InputStream stream){ public void setImg(InputStream stream) {
mainView.setImage(new Image(stream)); mainView.setImage(new Image(stream));
} }
public void setUpConfig(ConfigLoader configLoader){ public void setUpConfig(ConfigLoader configLoader) {
mainConfig=configLoader.readConfigFromFile("files"+ File.separator +"Config.json"); mainConfig = configLoader.readConfigFromFile("files" + File.separator + "Config.json");
voiceConfig=configLoader.readVoiceConfigFromFile("files"+ File.separator +"VoiceConfig.json"); voiceConfig = configLoader.readVoiceConfigFromFile("files" + File.separator + "VoiceConfig.json");
} }
@FXML @FXML
void showProgramInfo(ActionEvent event) { void showProgramInfo(ActionEvent event) {
new DialogMaker(rootPane).createDialogWithOneBtn("程序信息",new ProgramInfoPaneController(rootPane)); new DialogMaker(rootPane).createDialogWithOneBtn("程序信息", new ProgramInfoPaneController(rootPane));
} }
@FXML @FXML
void showNameManger(ActionEvent event) { void showNameManger(ActionEvent event) {
if (selector.isWorkerRunning()){ if (selector.isWorkerRunning()) {
new DialogMaker(rootPane).createMessageDialog("(・。・)","安排中......\n为保证运行的稳定,此时还不能进行该操作哦。"); new DialogMaker(rootPane).createMessageDialog("(・。・)", "安排中......\n为保证运行的稳定,此时还不能进行该操作哦。");
return; return;
} }
NameManagerPaneController nameManagerPaneController =new NameManagerPaneController(data,rootPane,ocrTool); NameManagerPaneController nameManagerPaneController = new NameManagerPaneController(data, rootPane, ocrTool);
new DialogMaker(rootPane).createDialogWithOneBtn("名单管理",nameManagerPaneController); new DialogMaker(rootPane).createDialogWithOneBtn("名单管理", nameManagerPaneController);
} }
@FXML @FXML
void showNunberSetting(ActionEvent event) { void showNunberSetting(ActionEvent event) {
if (selector.isWorkerRunning()){ if (selector.isWorkerRunning()) {
new DialogMaker(rootPane).createMessageDialog("(・。・)","安排中......\n为保证运行的稳定,此时还不能进行该操作哦。"); new DialogMaker(rootPane).createMessageDialog("(・。・)", "安排中......\n为保证运行的稳定,此时还不能进行该操作哦。");
return; return;
} }
NumberSettingsPaneController numberSettingsPaneController =new NumberSettingsPaneController(data); NumberSettingsPaneController numberSettingsPaneController = new NumberSettingsPaneController(data);
numberSettingsPaneController.bindProperties(mainConfig); numberSettingsPaneController.bindProperties(mainConfig);
new DialogMaker(rootPane).createDialogWithOneBtn("调整数字",numberSettingsPaneController); new DialogMaker(rootPane).createDialogWithOneBtn("调整数字", numberSettingsPaneController);
} }
Logger log= LogManager.getLogger();
@FXML @FXML
void miniMode(ActionEvent event) { void miniMode(ActionEvent event) {
FXMLLoader loader=new FXMLLoader(getClass().getResource("/me/lensferno/dogename/FXMLs/MiniPane.fxml")); FXMLLoader loader = new FXMLLoader(getClass().getResource("/me/lensferno/dogename/FXMLs/MiniPane.fxml"));
Parent parent; Parent parent;
try { try {
parent=loader.load(); parent = loader.load();
} catch (IOException e) { } catch (IOException e) {
log.error("Error in loading MiniPane Fxml:"+e); e.printStackTrace();
return; return;
} }
Scene miniScene=new Scene(parent,300,134); Scene miniScene = new Scene(parent, 300, 134);
Stage miniStage=new Stage(); Stage miniStage = new Stage();
miniStage.setScene(miniScene); miniStage.setScene(miniScene);
miniStage.initStyle(StageStyle.UNDECORATED); miniStage.initStyle(StageStyle.UNDECORATED);
MiniPaneController miniPaneController=loader.getController(); MiniPaneController miniPaneController = loader.getController();
miniPaneController.setBase(data, mainConfig, selector); miniPaneController.setBase(data, mainConfig, selector);
Stage currentStage=(Stage)anPaiBtn.getScene().getWindow(); Stage currentStage = (Stage) anPaiBtn.getScene().getWindow();
miniPaneController.setOldStage(currentStage); miniPaneController.setOldStage(currentStage);
miniPaneController.setCurrentStage(miniStage); miniPaneController.setCurrentStage(miniStage);
@ -165,7 +153,7 @@ public final class MainInterfaceController {
@FXML @FXML
void showSettings(ActionEvent event) { void showSettings(ActionEvent event) {
SettingsPaneController settingsPaneController =new SettingsPaneController(); SettingsPaneController settingsPaneController = new SettingsPaneController();
settingsPaneController.setToggleGroup(); settingsPaneController.setToggleGroup();
settingsPaneController.bindProperties(mainConfig); settingsPaneController.bindProperties(mainConfig);
@ -176,27 +164,21 @@ public final class MainInterfaceController {
settingsPaneController.setData(data); settingsPaneController.setData(data);
new DialogMaker(rootPane).createDialogWithOneBtn("更多设置",settingsPaneController); new DialogMaker(rootPane).createDialogWithOneBtn("更多设置", settingsPaneController);
} }
@FXML @FXML
void showHistory(ActionEvent event) { void showHistory(ActionEvent event) {
HistoryPaneController historyPaneController =new HistoryPaneController(history,rootPane); HistoryPaneController historyPaneController = new HistoryPaneController(history, rootPane);
new DialogMaker(rootPane).createDialogWithOneBtn("历史记录",historyPaneController); new DialogMaker(rootPane).createDialogWithOneBtn("历史记录", historyPaneController);
} }
Random random=new Random(); public void init() {
Data data =new Data();
Selector selector =new Selector();
public void init(){
selector.initialVariable(mainConfig, data, history, upperLabel.textProperty(), downLabel.textProperty()); selector.initialVariable(mainConfig, data, history, upperLabel.textProperty(), downLabel.textProperty());
selector.addStoppedEventListener((observableValue, oldValue, stop)->{ selector.addStoppedEventListener((observableValue, oldValue, stop) -> {
if (stop) { if (stop) {
anPaiBtn.setText("安排一下"); anPaiBtn.setText("安排一下");
nameChoose.setDisable(false); nameChoose.setDisable(false);
@ -212,42 +194,42 @@ public final class MainInterfaceController {
@FXML @FXML
void anPai() { void anPai() {
if(selector.isWorkerRunning()){ if (selector.isWorkerRunning()) {
selector.forceStop(); selector.forceStop();
anPaiBtn.setText("安排一下"); anPaiBtn.setText("安排一下");
return; return;
} }
if(mainConfig.getRandomCount()) { if (mainConfig.getRandomCount()) {
mainConfig.setMaxTotalCount(100+random.nextInt(151)); mainConfig.setMaxTotalCount(100 + random.nextInt(151));
} }
if(mainConfig.getNameChoose()){ if (mainConfig.getNameChoose()) {
runNameMode(); runNameMode();
}else { } else {
runNumberMode(); runNumberMode();
} }
} }
public void setToggleGroup(){ public void setToggleGroup() {
ToggleGroup toggleGroup =new ToggleGroup(); ToggleGroup toggleGroup = new ToggleGroup();
nameChoose.setToggleGroup(toggleGroup); nameChoose.setToggleGroup(toggleGroup);
numbChoose.setToggleGroup(toggleGroup); numbChoose.setToggleGroup(toggleGroup);
} }
private void runNameMode(){ private void runNameMode() {
if(data.isEmpty()){ if (data.isEmpty()) {
new DialogMaker(rootPane).createMessageDialog("哦霍~","现在名单还是空的捏~请前往名单管理添加名字 或 使用数字挑选法。"); new DialogMaker(rootPane).createMessageDialog("哦霍~", "现在名单还是空的捏~请前往名单管理添加名字 或 使用数字挑选法。");
return; return;
} }
if(data.compareNameIgnoreList() && mainConfig.getPassSelectedResult()){ if (data.compareNameIgnoreList() && mainConfig.getPassSelectedResult()) {
if(mainConfig.getEqualMode()) { if (mainConfig.getEqualMode()) {
new DialogMaker(rootPane).createDialogWithOKAndCancel("啊?", "全部名字都被点完啦!\n要把名字的忽略列表重置吗?", e -> data.clearNameIgnoreList()); new DialogMaker(rootPane).createDialogWithOKAndCancel("啊?", "全部名字都被点完啦!\n要把名字的忽略列表重置吗?", e -> data.clearNameIgnoreList());
}else { } else {
new DialogMaker(rootPane).createMessageDialog("啊?", "全部名字都被点完啦!\n请多添加几个名字 或 点击“机会均等”的“重置”按钮。"); new DialogMaker(rootPane).createMessageDialog("啊?", "全部名字都被点完啦!\n请多添加几个名字 或 点击“机会均等”的“重置”按钮。");
} }
return; return;
@ -258,29 +240,29 @@ public final class MainInterfaceController {
selector.run(); selector.run();
} }
private void runNumberMode(){ private void runNumberMode() {
try{ try {
int minNumber=Integer.parseInt(mainConfig.getMinNumber()); int minNumber = Integer.parseInt(mainConfig.getMinNumber());
int maxNumber=Integer.parseInt(mainConfig.getMaxNumber()); int maxNumber = Integer.parseInt(mainConfig.getMaxNumber());
if(maxNumber-minNumber <= 0){ if (maxNumber - minNumber <= 0) {
new DialogMaker(rootPane).createMessageDialog("嗯哼?","数字要前小后大啊~"); new DialogMaker(rootPane).createMessageDialog("嗯哼?", "数字要前小后大啊~");
return; return;
} }
if(data.getNumberIgnoreListSize() >= (maxNumber-minNumber+1) && mainConfig.getPassSelectedResult()){ if (data.getNumberIgnoreListSize() >= (maxNumber - minNumber + 1) && mainConfig.getPassSelectedResult()) {
if(mainConfig.getEqualMode()) { if (mainConfig.getEqualMode()) {
new DialogMaker(rootPane).createDialogWithOKAndCancel("啊?", "全部数字都被点完啦!\n要把数字的忽略列表重置吗?", e -> data.clearNumberIgnoreList()); new DialogMaker(rootPane).createDialogWithOKAndCancel("啊?", "全部数字都被点完啦!\n要把数字的忽略列表重置吗?", e -> data.clearNumberIgnoreList());
}else { } else {
new DialogMaker(rootPane).createMessageDialog("啊?", "全部数字都被点完啦!\n请扩大数字范围 或 点击“机会均等”的“重置”按钮。"); new DialogMaker(rootPane).createMessageDialog("啊?", "全部数字都被点完啦!\n请扩大数字范围 或 点击“机会均等”的“重置”按钮。");
} }
return; return;
} }
}catch (Exception e){ } catch (Exception e) {
new DialogMaker(rootPane).createMessageDialog("嗯哼?","输入个有效的数字啊~"); new DialogMaker(rootPane).createMessageDialog("嗯哼?", "输入个有效的数字啊~");
return; return;
} }

@ -10,26 +10,30 @@ import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent; import javafx.scene.input.MouseEvent;
import javafx.scene.input.TouchEvent; import javafx.scene.input.TouchEvent;
import javafx.stage.Stage; import javafx.stage.Stage;
import me.lensferno.dogename.select.Selector;
import me.lensferno.dogename.configs.MainConfig; import me.lensferno.dogename.configs.MainConfig;
import me.lensferno.dogename.controllers.WindowListeners.MoveWindowByMouse; import me.lensferno.dogename.controllers.WindowListeners.MoveWindowByMouse;
import me.lensferno.dogename.controllers.WindowListeners.MoveWindowByTouch; import me.lensferno.dogename.controllers.WindowListeners.MoveWindowByTouch;
import me.lensferno.dogename.data.Data; import me.lensferno.dogename.data.Data;
import me.lensferno.dogename.select.Selector;
import java.util.Random; import java.util.Random;
public class MiniPaneController { public class MiniPaneController {
Stage oldStage;
Stage currentStage;
Scene currentScene;
StringProperty[] oldTextProperties = null;
@FXML @FXML
private Label chosenNameLabel; private Label chosenNameLabel;
@FXML @FXML
private JFXButton anPaiBtn; private JFXButton anPaiBtn;
@FXML @FXML
private JFXButton miniModeBtn; private JFXButton miniModeBtn;
private final Random random = new Random();
Stage oldStage; private Data data;
private MainConfig mainConfig;
private Selector selector = new Selector();
public Stage getOldStage() { public Stage getOldStage() {
return oldStage; return oldStage;
@ -39,12 +43,6 @@ public class MiniPaneController {
this.oldStage = oldStage; this.oldStage = oldStage;
} }
private Random random = new Random();
private Data data;
Stage currentStage;
Scene currentScene;
public void setCurrentScene(Scene currentScene) { public void setCurrentScene(Scene currentScene) {
this.currentScene = currentScene; this.currentScene = currentScene;
} }
@ -53,8 +51,6 @@ public class MiniPaneController {
this.currentStage = currentStage; this.currentStage = currentStage;
} }
StringProperty[] oldTextProperties = null;
public void setBase(Data data, MainConfig mainConfig, Selector selector) { public void setBase(Data data, MainConfig mainConfig, Selector selector) {
this.data = data; this.data = data;
this.mainConfig = mainConfig; this.mainConfig = mainConfig;
@ -95,9 +91,6 @@ public class MiniPaneController {
miniModeBtn.setOnTouchMoved(touchHandler); miniModeBtn.setOnTouchMoved(touchHandler);
} }
private MainConfig mainConfig;
private Selector selector = new Selector();
@FXML @FXML
void anPai() { void anPai() {

@ -1,6 +1,8 @@
package me.lensferno.dogename.controllers; package me.lensferno.dogename.controllers;
import com.jfoenix.controls.*; import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXListView;
import com.jfoenix.controls.JFXTextArea;
import javafx.collections.FXCollections; import javafx.collections.FXCollections;
import javafx.collections.ObservableList; import javafx.collections.ObservableList;
import javafx.event.ActionEvent; import javafx.event.ActionEvent;
@ -12,58 +14,50 @@ import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox; import javafx.scene.layout.VBox;
import javafx.stage.FileChooser; import javafx.stage.FileChooser;
import javafx.stage.Stage; import javafx.stage.Stage;
import me.lensferno.dogename.utils.DialogMaker;
import me.lensferno.dogename.data.Data; import me.lensferno.dogename.data.Data;
import me.lensferno.dogename.utils.ocr.OcrTool;
import me.lensferno.dogename.utils.Clipboard; import me.lensferno.dogename.utils.Clipboard;
import me.lensferno.dogename.utils.DialogMaker;
import me.lensferno.dogename.utils.ocr.OcrTool;
import java.io.File; import java.io.File;
import java.util.logging.Logger; import java.util.logging.Logger;
public class NameManagerPaneController extends VBox { public class NameManagerPaneController extends VBox {
public static final ObservableList<String> shownNameList = FXCollections.observableArrayList();
Data data; Data data;
Pane rootPane; Pane rootPane;
OcrTool ocrTool; OcrTool ocrTool;
Logger log = Logger.getLogger("NameManagerPaneLOgger"); Logger log = Logger.getLogger("NameManagerPaneLOgger");
@FXML
private JFXListView<String> nameList;
@FXML
private JFXButton deleteAll;
@FXML
private JFXButton addName;
@FXML
private JFXButton deleteName;
@FXML
private JFXTextArea inputName;
public static final ObservableList<String> shownNameList = FXCollections.observableArrayList(); public NameManagerPaneController(Data data, Pane rootPane, OcrTool ocrTool) {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/me/lensferno/dogename/FXMLs/NameManagerPane.fxml"));
public NameManagerPaneController(Data data, Pane rootPane, OcrTool ocrTool){
FXMLLoader loader=new FXMLLoader(getClass().getResource("/me/lensferno/dogename/FXMLs/NameManagerPane.fxml"));
loader.setRoot(this); loader.setRoot(this);
loader.setController(this); loader.setController(this);
try { try {
loader.load(); loader.load();
}catch(Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
this.data=data; this.data = data;
this.rootPane=rootPane; this.rootPane = rootPane;
shownNameList.setAll(data.getNameList()); shownNameList.setAll(data.getNameList());
this.nameList.setItems(shownNameList); this.nameList.setItems(shownNameList);
this.ocrTool=ocrTool; this.ocrTool = ocrTool;
} }
@FXML
private JFXListView<String> nameList;
@FXML
private JFXButton deleteAll;
@FXML
private JFXButton addName;
@FXML
private JFXButton deleteName;
@FXML
private JFXTextArea inputName;
@FXML @FXML
void deleteName(ActionEvent event) { void deleteName(ActionEvent event) {
@ -141,8 +135,8 @@ public class NameManagerPaneController extends VBox {
@FXML @FXML
void addName(ActionEvent event) { void addName(ActionEvent event) {
if(inputName.getText().equals("")){ if (inputName.getText().equals("")) {
new DialogMaker(rootPane).createMessageDialog("诶诶诶~","输入框怎么是空的呢?"); new DialogMaker(rootPane).createMessageDialog("诶诶诶~", "输入框怎么是空的呢?");
return; return;
} }
@ -161,30 +155,30 @@ public class NameManagerPaneController extends VBox {
FXMLLoader fxmlLoader; FXMLLoader fxmlLoader;
Parent parent; Parent parent;
Stage stage=new Stage(); Stage stage = new Stage();
try{ try {
fxmlLoader=new FXMLLoader(getClass().getResource("/me/lensferno/dogename/FXMLs/OcrPane.fxml")); fxmlLoader = new FXMLLoader(getClass().getResource("/me/lensferno/dogename/FXMLs/OcrPane.fxml"));
parent=fxmlLoader.load(); parent = fxmlLoader.load();
}catch (Exception e){ } catch (Exception e) {
log.warning("Error to load main interface FXML :"+e.toString()); log.warning("Error to load main interface FXML :" + e);
return; return;
} }
Scene scene=new Scene(parent,515,604); Scene scene = new Scene(parent, 515, 604);
stage.setTitle("Ocr模块"); stage.setTitle("Ocr模块");
stage.setScene(scene); stage.setScene(scene);
log.fine("窗口加载完成"); log.fine("窗口加载完成");
OcrPaneController ocrPaneController= fxmlLoader.getController(); OcrPaneController ocrPaneController = fxmlLoader.getController();
ocrPaneController.setMainStage((Stage)inputName.getScene().getWindow()); ocrPaneController.setMainStage((Stage) inputName.getScene().getWindow());
stage.show(); stage.show();
} }
@FXML @FXML
void copyTo(ActionEvent event) { void copyTo(ActionEvent event) {
inputName.setText(inputName.getText()+ Clipboard.getClipboardString()); inputName.setText(inputName.getText() + Clipboard.getClipboardString());
} }

@ -9,31 +9,30 @@ import me.lensferno.dogename.data.Data;
public class NumberSettingsPaneController extends VBox { public class NumberSettingsPaneController extends VBox {
Data data; Data data;
public NumberSettingsPaneController(Data data){ @FXML
FXMLLoader loader=new FXMLLoader(getClass().getResource("/me/lensferno/dogename/FXMLs/NumberSettingPane.fxml")); private JFXTextField minValueField;
@FXML
private JFXTextField maxValueField;
public NumberSettingsPaneController(Data data) {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/me/lensferno/dogename/FXMLs/NumberSettingPane.fxml"));
loader.setRoot(this); loader.setRoot(this);
loader.setController(this); loader.setController(this);
try { try {
loader.load(); loader.load();
}catch(Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
this.data=data; this.data = data;
} }
@FXML public void bindProperties(MainConfig mainConfig) {
private JFXTextField minValueField;
@FXML
private JFXTextField maxValueField;
public void bindProperties(MainConfig mainConfig){
minValueField.textProperty().bindBidirectional(mainConfig.minNumberProperty()); minValueField.textProperty().bindBidirectional(mainConfig.minNumberProperty());
minValueField.textProperty().addListener((observable, oldValue, newValue) -> data.clearNumberIgnoreList() ); minValueField.textProperty().addListener((observable, oldValue, newValue) -> data.clearNumberIgnoreList());
maxValueField.textProperty().bindBidirectional(mainConfig.maxNumberProperty()); maxValueField.textProperty().bindBidirectional(mainConfig.maxNumberProperty());
maxValueField.textProperty().addListener((observable, oldValue, newValue) -> data.clearNumberIgnoreList() ); maxValueField.textProperty().addListener((observable, oldValue, newValue) -> data.clearNumberIgnoreList());
} }
} }

@ -3,31 +3,26 @@ package me.lensferno.dogename.controllers;
import com.jfoenix.controls.JFXSpinner; import com.jfoenix.controls.JFXSpinner;
import javafx.fxml.FXML; import javafx.fxml.FXML;
import javafx.scene.control.TextArea; import javafx.scene.control.TextArea;
import javafx.scene.text.Text;
import javafx.stage.Stage; import javafx.stage.Stage;
import me.lensferno.dogename.utils.ocr.ScreenCapture;
import me.lensferno.dogename.utils.Clipboard; import me.lensferno.dogename.utils.Clipboard;
import me.lensferno.dogename.utils.ocr.ScreenCapture;
public class OcrPaneController { public class OcrPaneController {
Stage mainStage;
@FXML @FXML
private TextArea ocrText; private TextArea ocrText;
@FXML @FXML
private JFXSpinner loadingSpinner; private JFXSpinner loadingSpinner;
Stage mainStage;
public void setMainStage(Stage mainStage) { public void setMainStage(Stage mainStage) {
this.mainStage = mainStage; this.mainStage = mainStage;
} }
@FXML @FXML
void addNew() { void addNew() {
Stage thisStage=(Stage)ocrText.getScene().getWindow(); Stage thisStage = (Stage) ocrText.getScene().getWindow();
thisStage.hide(); thisStage.hide();
mainStage.hide(); mainStage.hide();

@ -28,13 +28,13 @@ public class ProgramInfoPaneController extends VBox {
Pane rootPane; Pane rootPane;
public ProgramInfoPaneController(Pane rootPane){ public ProgramInfoPaneController(Pane rootPane) {
FXMLLoader loader=new FXMLLoader(getClass().getResource("/me/lensferno/dogename/FXMLs/ProgramInfoPane.fxml")); FXMLLoader loader = new FXMLLoader(getClass().getResource("/me/lensferno/dogename/FXMLs/ProgramInfoPane.fxml"));
loader.setRoot(this); loader.setRoot(this);
loader.setController(this); loader.setController(this);
try { try {
loader.load(); loader.load();
}catch(Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -44,51 +44,51 @@ public class ProgramInfoPaneController extends VBox {
e.printStackTrace(); e.printStackTrace();
} }
this.rootPane=rootPane; this.rootPane = rootPane;
} }
@FXML @FXML
void showLicense() { void showLicense() {
TextArea textArea=new TextArea(IOUtil.inputStreamToString(getClass().getResourceAsStream("/gpl-3.0.txt"), StandardCharsets.UTF_8)); TextArea textArea = new TextArea(IOUtil.inputStreamToString(getClass().getResourceAsStream("/gpl-3.0.txt"), StandardCharsets.UTF_8));
textArea.setFont(Font.font("Microsoft YaHei",14)); textArea.setFont(Font.font("Microsoft YaHei", 14));
textArea.setMinWidth(600); textArea.setMinWidth(600);
textArea.setPrefHeight(400); textArea.setPrefHeight(400);
textArea.setEditable(false); textArea.setEditable(false);
new DialogMaker(rootPane).createDialogWithOneBtn("开源协议(GPL v3)",textArea); new DialogMaker(rootPane).createDialogWithOneBtn("开源协议(GPL v3)", textArea);
} }
@FXML @FXML
void showLibLicense() { void showLibLicense() {
TextArea textArea=new TextArea(IOUtil.inputStreamToString(getClass().getResourceAsStream("/LibLicense.txt"), StandardCharsets.UTF_8)); TextArea textArea = new TextArea(IOUtil.inputStreamToString(getClass().getResourceAsStream("/LibLicense.txt"), StandardCharsets.UTF_8));
textArea.setFont(Font.font("Microsoft YaHei",14)); textArea.setFont(Font.font("Microsoft YaHei", 14));
textArea.setMinWidth(600); textArea.setMinWidth(600);
textArea.setPrefHeight(400); textArea.setPrefHeight(400);
textArea.setEditable(false); textArea.setEditable(false);
new DialogMaker(rootPane).createDialogWithOneBtn("其他开源许可",textArea); new DialogMaker(rootPane).createDialogWithOneBtn("其他开源许可", textArea);
} }
@FXML @FXML
void showHelp() { void showHelp() {
JFXButton YesButton = new JFXButton("好的~去吧去吧"); JFXButton YesButton = new JFXButton("好的~去吧去吧");
YesButton.setFont(Font.font("Microsoft YaHei", FontWeight.BOLD,14)); YesButton.setFont(Font.font("Microsoft YaHei", FontWeight.BOLD, 14));
YesButton.setPrefWidth(160); YesButton.setPrefWidth(160);
YesButton.setPrefHeight(40); YesButton.setPrefHeight(40);
YesButton.addEventHandler(ActionEvent.ACTION,e -> jumpToHelp()); YesButton.addEventHandler(ActionEvent.ACTION, e -> jumpToHelp());
JFXButton cancelButton = new JFXButton("算了算了"); JFXButton cancelButton = new JFXButton("算了算了");
cancelButton.setFont(Font.font("Microsoft YaHei", FontWeight.BOLD,14)); cancelButton.setFont(Font.font("Microsoft YaHei", FontWeight.BOLD, 14));
cancelButton.setPrefWidth(100); cancelButton.setPrefWidth(100);
cancelButton.setPrefHeight(40); cancelButton.setPrefHeight(40);
Text messageText=new Text("即将跳转到本程序Github页面上的使用帮助,是否继续?"); Text messageText = new Text("即将跳转到本程序Github页面上的使用帮助,是否继续?");
messageText.setFont(Font.font("Microsoft YaHei",14)); messageText.setFont(Font.font("Microsoft YaHei", 14));
new DialogMaker(rootPane).createDialog("查看帮助",messageText,cancelButton,YesButton); new DialogMaker(rootPane).createDialog("查看帮助", messageText, cancelButton, YesButton);
} }
private void jumpToHelp(){ private void jumpToHelp() {
try { try {
Desktop.getDesktop().browse(new URI("https://github.com/lensferno/dogename/blob/main/res/usage.md")); Desktop.getDesktop().browse(new URI("https://github.com/lensferno/dogename/blob/main/res/usage.md"));
} catch (IOException | URISyntaxException e) { } catch (IOException | URISyntaxException e) {
@ -99,30 +99,30 @@ public class ProgramInfoPaneController extends VBox {
@FXML @FXML
void viewCode() { void viewCode() {
JFXButton githubButton = new JFXButton("前往Github查看"); JFXButton githubButton = new JFXButton("前往Github查看");
githubButton.setFont(Font.font("Microsoft YaHei", FontWeight.BOLD,14)); githubButton.setFont(Font.font("Microsoft YaHei", FontWeight.BOLD, 14));
githubButton.setPrefWidth(150); githubButton.setPrefWidth(150);
githubButton.setPrefHeight(40); githubButton.setPrefHeight(40);
githubButton.addEventHandler(ActionEvent.ACTION,e -> jumpToGithub()); githubButton.addEventHandler(ActionEvent.ACTION, e -> jumpToGithub());
JFXButton giteeButton = new JFXButton("前往Gitee查看"); JFXButton giteeButton = new JFXButton("前往Gitee查看");
giteeButton.setFont(Font.font("Microsoft YaHei", FontWeight.BOLD,14)); giteeButton.setFont(Font.font("Microsoft YaHei", FontWeight.BOLD, 14));
giteeButton.setPrefWidth(150); giteeButton.setPrefWidth(150);
giteeButton.setPrefHeight(40); giteeButton.setPrefHeight(40);
giteeButton.addEventHandler(ActionEvent.ACTION,e -> jumpToGitee()); giteeButton.addEventHandler(ActionEvent.ACTION, e -> jumpToGitee());
JFXButton cancelButton = new JFXButton("哪都不去"); JFXButton cancelButton = new JFXButton("哪都不去");
cancelButton.setFont(Font.font("Microsoft YaHei", FontWeight.BOLD,14)); cancelButton.setFont(Font.font("Microsoft YaHei", FontWeight.BOLD, 14));
cancelButton.setPrefWidth(100); cancelButton.setPrefWidth(100);
cancelButton.setPrefHeight(40); cancelButton.setPrefHeight(40);
Text messageText=new Text("Dogename在Github和码云(Gitee)都发布有代码和介绍。\n您想去哪里?\nGithub:将跳转到https://github.com/lensferno/dogename\nGitee:将跳转到https://gitee.com/lensferno/dogename"); Text messageText = new Text("Dogename在Github和码云(Gitee)都发布有代码和介绍。\n您想去哪里?\nGithub:将跳转到https://github.com/lensferno/dogename\nGitee:将跳转到https://gitee.com/lensferno/dogename");
messageText.setFont(Font.font("Microsoft YaHei",14)); messageText.setFont(Font.font("Microsoft YaHei", 14));
new DialogMaker(rootPane).createDialog("查看源代码",messageText,cancelButton,githubButton,giteeButton); new DialogMaker(rootPane).createDialog("查看源代码", messageText, cancelButton, githubButton, giteeButton);
} }
private void jumpToGithub(){ private void jumpToGithub() {
try { try {
Desktop.getDesktop().browse(new URI("https://github.com/lensferno/dogename")); Desktop.getDesktop().browse(new URI("https://github.com/lensferno/dogename"));
} catch (IOException | URISyntaxException e) { } catch (IOException | URISyntaxException e) {
@ -130,7 +130,7 @@ public class ProgramInfoPaneController extends VBox {
} }
} }
private void jumpToGitee(){ private void jumpToGitee() {
try { try {
Desktop.getDesktop().browse(new URI("https://gitee.com/lensferno/dogename")); Desktop.getDesktop().browse(new URI("https://gitee.com/lensferno/dogename"));
} catch (IOException | URISyntaxException e) { } catch (IOException | URISyntaxException e) {

@ -9,63 +9,48 @@ import javafx.fxml.FXMLLoader;
import javafx.scene.control.ToggleGroup; import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.Pane; import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox; import javafx.scene.layout.VBox;
import me.lensferno.dogename.utils.DialogMaker;
import me.lensferno.dogename.configs.MainConfig; import me.lensferno.dogename.configs.MainConfig;
import me.lensferno.dogename.configs.VoiceConfig; import me.lensferno.dogename.configs.VoiceConfig;
import me.lensferno.dogename.data.Data; import me.lensferno.dogename.data.Data;
import org.apache.logging.log4j.LogManager; import me.lensferno.dogename.utils.DialogMaker;
import org.apache.logging.log4j.Logger;
public class SettingsPaneController extends VBox { public class SettingsPaneController extends VBox {
MainConfig mainConfig;
VoiceConfig voiceConfig;
Pane rootPane;
Data data;
@FXML @FXML
private JFXCheckBox showSayingBtn; private JFXCheckBox showSayingBtn;
@FXML @FXML
private JFXCheckBox newAlgoBtn; private JFXCheckBox newAlgoBtn;
@FXML @FXML
private JFXSlider cycleTimesBar; private JFXSlider cycleTimesBar;
@FXML @FXML
private JFXCheckBox voicePlayBtn; private JFXCheckBox voicePlayBtn;
@FXML @FXML
private JFXSlider speedBar; private JFXSlider speedBar;
@FXML @FXML
private JFXCheckBox equalModeBtn; private JFXCheckBox equalModeBtn;
@FXML @FXML
private JFXRadioButton ignoreOnce; private JFXRadioButton ignoreOnce;
@FXML @FXML
private JFXRadioButton chooseOnce; private JFXRadioButton chooseOnce;
@FXML @FXML
private JFXRadioButton randomTimes; private JFXRadioButton randomTimes;
@FXML @FXML
private JFXRadioButton fixedTimes; private JFXRadioButton fixedTimes;
MainConfig mainConfig;
VoiceConfig voiceConfig;
Pane rootPane;
Data data;
Logger log = LogManager.getLogger("SettingsPaneControllerLogger");
public SettingsPaneController(){ public SettingsPaneController() {
FXMLLoader loader=new FXMLLoader(getClass().getResource("/me/lensferno/dogename/FXMLs/SettingsPane.fxml")); FXMLLoader loader = new FXMLLoader(getClass().getResource("/me/lensferno/dogename/FXMLs/SettingsPane.fxml"));
loader.setRoot(this); loader.setRoot(this);
loader.setController(this); loader.setController(this);
try { try {
loader.load(); loader.load();
}catch(Exception e){ } catch (Exception e) {
log.warn("Error to load settings pane FXML: "+e.toString()); e.printStackTrace();
} }
} }
@ -77,11 +62,11 @@ public class SettingsPaneController extends VBox {
this.voiceConfig = voiceConfig; this.voiceConfig = voiceConfig;
} }
public void setRootPane(Pane rootPane){ public void setRootPane(Pane rootPane) {
this.rootPane=rootPane; this.rootPane = rootPane;
} }
public void bindProperties(MainConfig mainConfig){ public void bindProperties(MainConfig mainConfig) {
setMainConfig(mainConfig); setMainConfig(mainConfig);
ignoreOnce.selectedProperty().bindBidirectional(mainConfig.passSelectedResultProperty()); ignoreOnce.selectedProperty().bindBidirectional(mainConfig.passSelectedResultProperty());
@ -103,29 +88,28 @@ public class SettingsPaneController extends VBox {
showSayingBtn.selectedProperty().bindBidirectional(mainConfig.showSayingProperty()); showSayingBtn.selectedProperty().bindBidirectional(mainConfig.showSayingProperty());
mainConfig.passSelectedResultProperty().addListener((observable, oldValue, isIgnorePast) -> { mainConfig.passSelectedResultProperty().addListener((observable, oldValue, isIgnorePast) -> {
if(!isIgnorePast) if (!isIgnorePast) {
{
//如果 忽略被点过的名字 被取消后就把机会均等模式的按钮给取消掉 //如果 忽略被点过的名字 被取消后就把机会均等模式的按钮给取消掉
equalModeBtn.setSelected(false); equalModeBtn.setSelected(false);
} }
}); });
} }
public void setToggleGroup(){ public void setToggleGroup() {
ToggleGroup pastGroup=new ToggleGroup(); ToggleGroup pastGroup = new ToggleGroup();
chooseOnce.setToggleGroup(pastGroup); chooseOnce.setToggleGroup(pastGroup);
ignoreOnce.setToggleGroup(pastGroup); ignoreOnce.setToggleGroup(pastGroup);
ToggleGroup fixedTimesGroup=new ToggleGroup(); ToggleGroup fixedTimesGroup = new ToggleGroup();
randomTimes.setToggleGroup(fixedTimesGroup); randomTimes.setToggleGroup(fixedTimesGroup);
fixedTimes.setToggleGroup(fixedTimesGroup); fixedTimes.setToggleGroup(fixedTimesGroup);
} }
@FXML @FXML
void showVoiceSettingsPane(ActionEvent event) { void showVoiceSettingsPane(ActionEvent event) {
VoiceSettingsPaneController voiceSettingsPaneController=new VoiceSettingsPaneController(); VoiceSettingsPaneController voiceSettingsPaneController = new VoiceSettingsPaneController();
voiceSettingsPaneController.bindPropertied(voiceConfig); voiceSettingsPaneController.bindPropertied(voiceConfig);
new DialogMaker(rootPane).createDialogWithOneBtn("语音设置",voiceSettingsPaneController); new DialogMaker(rootPane).createDialogWithOneBtn("语音设置", voiceSettingsPaneController);
} }
@FXML @FXML
@ -137,7 +121,7 @@ public class SettingsPaneController extends VBox {
@FXML @FXML
void clearIgnoreList(ActionEvent event) { void clearIgnoreList(ActionEvent event) {
new DialogMaker(rootPane).createDialogWithOKAndCancel("真的吗?","真的要重置吗?",(e)->{ new DialogMaker(rootPane).createDialogWithOKAndCancel("真的吗?", "真的要重置吗?", (e) -> {
data.clearNumberIgnoreList(); data.clearNumberIgnoreList();
data.clearNameIgnoreList(); data.clearNameIgnoreList();
}); });
@ -145,9 +129,9 @@ public class SettingsPaneController extends VBox {
@FXML @FXML
void equalBtnAction(ActionEvent event) { void equalBtnAction(ActionEvent event) {
if(!mainConfig.getPassSelectedResult()){ if (!mainConfig.getPassSelectedResult()) {
equalModeBtn.setSelected(false); equalModeBtn.setSelected(false);
new DialogMaker(rootPane).createMessageDialog("且慢","无法在“概率均分”的模式下使用,如需使用请在“人人有份”模式下启用。"); new DialogMaker(rootPane).createMessageDialog("且慢", "无法在“概率均分”的模式下使用,如需使用请在“人人有份”模式下启用。");
} }
} }

@ -13,25 +13,18 @@ import me.lensferno.dogename.configs.VoiceConfig;
import java.util.logging.Logger; import java.util.logging.Logger;
public class VoiceSettingsPaneController extends VBox { public class VoiceSettingsPaneController extends VBox {
public static final ObservableList<String> shownSpeakerList = FXCollections.observableArrayList();
private final String[] speakers = {
"1", "0", "3", "4",
"106", "110", "111", "103", "5"};
Logger log = Logger.getLogger("VoiceSettingsPaneControllerLogger"); Logger log = Logger.getLogger("VoiceSettingsPaneControllerLogger");
VoiceConfig voiceConfig = new VoiceConfig();
VoiceConfig voiceConfig=new VoiceConfig();
@FXML @FXML
private JFXSlider intonationBar; private JFXSlider intonationBar;
@FXML @FXML
private JFXComboBox<String> speakerSelectBar; private JFXComboBox<String> speakerSelectBar;
@FXML @FXML
private JFXSlider voiceSpeedBar; private JFXSlider voiceSpeedBar;
public static final ObservableList<String> shownSpeakerList = FXCollections.observableArrayList();
private final String[] speakers={
"1","0","3","4",
"106","110","111","103","5"};
//度小宇=1,度小美=0,度逍遥=3,度丫丫=4 //度小宇=1,度小美=0,度逍遥=3,度丫丫=4
//度博文=106,度小童=110,度小萌=111,度米朵=103,度小娇=5 //度博文=106,度小童=110,度小萌=111,度米朵=103,度小娇=5
@ -42,9 +35,9 @@ public class VoiceSettingsPaneController extends VBox {
try { try {
loader.load(); loader.load();
} catch (Exception e) { } catch (Exception e) {
log.warning("Error to load settings pane FXML: " + e.toString()); log.warning("Error to load settings pane FXML: " + e);
} }
if(shownSpeakerList.isEmpty()) { if (shownSpeakerList.isEmpty()) {
shownSpeakerList.addAll( shownSpeakerList.addAll(
"度小宇=1", "度小美=0", "度逍遥=3", "度丫丫=4", "度小宇=1", "度小美=0", "度逍遥=3", "度丫丫=4",
"度博文=106", "度小童=110", "度小萌=111", "度米朵=103", "度小娇=5"); "度博文=106", "度小童=110", "度小萌=111", "度米朵=103", "度小娇=5");
@ -53,14 +46,14 @@ public class VoiceSettingsPaneController extends VBox {
speakerSelectBar.setItems(shownSpeakerList); speakerSelectBar.setItems(shownSpeakerList);
} }
public void bindPropertied(VoiceConfig voiceConfig){ public void bindPropertied(VoiceConfig voiceConfig) {
this.voiceConfig=voiceConfig; this.voiceConfig = voiceConfig;
//speakerSelectBar. //speakerSelectBar.
speakerSelectBar.selectionModelProperty().addListener((observable, oldValue, newValue) -> { speakerSelectBar.selectionModelProperty().addListener((observable, oldValue, newValue) -> {
System.out.println("what?"+newValue.getSelectedIndex()); System.out.println("what?" + newValue.getSelectedIndex());
this.voiceConfig.setSpeaker(speakers[newValue.getSelectedIndex()]); this.voiceConfig.setSpeaker(speakers[newValue.getSelectedIndex()]);
this.voiceConfig.setSelectedSpeaker(newValue.getSelectedIndex()); this.voiceConfig.setSelectedSpeaker(newValue.getSelectedIndex());
}); });
@ -79,7 +72,6 @@ public class VoiceSettingsPaneController extends VBox {
} }
} }

@ -6,7 +6,7 @@ import javafx.stage.Stage;
public class MoveWindowByMouse implements EventHandler<MouseEvent> { public class MoveWindowByMouse implements EventHandler<MouseEvent> {
private Stage primaryStage; private final Stage primaryStage;
private double oldStageX; private double oldStageX;
private double oldStageY; private double oldStageY;
private double oldScreenX; private double oldScreenX;

@ -6,7 +6,7 @@ import javafx.stage.Stage;
public class MoveWindowByTouch implements EventHandler<TouchEvent> { public class MoveWindowByTouch implements EventHandler<TouchEvent> {
private Stage primaryStage; private final Stage primaryStage;
private double oldStageX; private double oldStageX;
private double oldStageY; private double oldStageY;
private double oldScreenX; private double oldScreenX;

@ -1,8 +1,6 @@
package me.lensferno.dogename.data; package me.lensferno.dogename.data;
import com.google.gson.Gson; import com.google.gson.Gson;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.*; import java.io.*;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
@ -11,19 +9,47 @@ import java.util.*;
public class Data { public class Data {
Logger log = LogManager.getLogger("dataLogger");
public static final int IGNORELIST_NAME_ONLY = 0; public static final int IGNORELIST_NAME_ONLY = 0;
public static final int IGNORELIST_NUMBER_ONLY = 1; public static final int IGNORELIST_NUMBER_ONLY = 1;
public static final int IGNORELIST_ALL = 2; public static final int IGNORELIST_ALL = 2;
File dataFile;
SecureRandom secRandom = new SecureRandom();
Random random = new Random();
private List<String> nameList;
private final IgnoreList ignoreList = new IgnoreList();
public Data() {
private List<String> nameList; dataFile = new File("files" + File.separator + "Namelist.data");
private IgnoreList ignoreList = new IgnoreList();
File dataFile; try {
SecureRandom secRandom = new SecureRandom(); if (!dataFile.exists()) {
dataFile.getParentFile().mkdirs();
dataFile.createNewFile();
nameList = new ArrayList<>();
saveToFile();
return;
}
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(dataFile));
this.nameList = (ArrayList) ois.readObject();
System.out.println(nameList.size() + " names loaded.");
} catch (EOFException EOFe) {
nameList = new ArrayList<>();
System.out.println("Data file is empty.");
saveToFile();
} catch (Exception e) {
nameList = new ArrayList<>();
saveToFile();
System.out.println("Failed to load data file.");
e.printStackTrace();
}
ignoreList.readIgnoreList();
}
public List<String> getNameList() { public List<String> getNameList() {
return nameList; return nameList;
@ -35,9 +61,9 @@ public class Data {
FileOutputStream oos = new FileOutputStream(path); FileOutputStream oos = new FileOutputStream(path);
oos.write(new Gson().toJson(nameList).getBytes(StandardCharsets.UTF_8)); oos.write(new Gson().toJson(nameList).getBytes(StandardCharsets.UTF_8));
oos.close(); oos.close();
log.info("Exported list to:" + path.getPath()); System.out.println("Exported list to:" + path.getPath());
} catch (Exception e) { } catch (Exception e) {
log.warn("error in export namelist: " + e.toString()); System.out.println("error in export namelist: " + e);
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -58,9 +84,9 @@ public class Data {
} }
nameList = new Gson().fromJson(sb.toString(), List.class); nameList = new Gson().fromJson(sb.toString(), List.class);
log.info("Imported list from:" + path.getPath()); System.out.println("Imported list from:" + path.getPath());
} catch (Exception e) { } catch (Exception e) {
log.warn("error in import namelist:" + e.toString()); System.out.println("error in import namelist:" + e);
e.printStackTrace(); e.printStackTrace();
} }
@ -86,56 +112,6 @@ public class Data {
} }
public Data() {
if (System.getProperty("os.name").toLowerCase().contains("window"))
dataFile = new File("files\\Namelist.data");
else
dataFile = new File("files/Namelist.data");
File oldDataFile = new File("D:\\dogename\\files\\data");
try {
if (oldDataFile.exists()) {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(oldDataFile));
this.nameList = (ArrayList) ois.readObject();
ois.close();
oldDataFile.delete();
saveToFile();
return;
}
if (!dataFile.exists()) {
dataFile.getParentFile().mkdirs();
dataFile.createNewFile();
nameList = new ArrayList<>();
saveToFile();
return;
}
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(dataFile));
this.nameList = (ArrayList) ois.readObject();
log.info(nameList.size() + " names loaded.");
} catch (EOFException EOFe) {
nameList = new ArrayList<>();
log.warn("Data file is empty.");
saveToFile();
} catch (Exception e) {
nameList = new ArrayList<>();
saveToFile();
log.warn("Failed to load data file.");
e.printStackTrace();
}
ignoreList.readIgnoreList();
}
public void add(String text) { public void add(String text) {
String[] splitedText; String[] splitedText;
@ -158,7 +134,6 @@ public class Data {
System.gc(); System.gc();
} }
public boolean compareNameIgnoreList() { public boolean compareNameIgnoreList() {
return ignoreList.getNameIgnoreListSize() >= nameList.size(); return ignoreList.getNameIgnoreListSize() >= nameList.size();
} }
@ -177,8 +152,6 @@ public class Data {
return nameList.isEmpty(); return nameList.isEmpty();
} }
Random random = new Random();
public String randomGet(boolean secureRandom) { public String randomGet(boolean secureRandom) {
if (secureRandom) if (secureRandom)
return nameList.get(secRandom.nextInt(nameList.size())); return nameList.get(secRandom.nextInt(nameList.size()));
@ -237,12 +210,10 @@ public class Data {
class IgnoreList { class IgnoreList {
private HashSet<String> ignoreNameList = new HashSet<>();
private HashSet<String> ignoreNumberList = new HashSet<>();
private final File nameIgnoreFile = new File("files" + File.separator + "IgnoredNameList.data"); private final File nameIgnoreFile = new File("files" + File.separator + "IgnoredNameList.data");
private final File numbIgnoreFile = new File("files" + File.separator + "IgnoredNumberList.data"); private final File numbIgnoreFile = new File("files" + File.separator + "IgnoredNumberList.data");
private HashSet<String> ignoreNameList = new HashSet<>();
private HashSet<String> ignoreNumberList = new HashSet<>();
public void writeIgnoreList(int switchy) { public void writeIgnoreList(int switchy) {
switch (switchy) { switch (switchy) {
@ -279,7 +250,7 @@ public class Data {
public void readIgnoreList() { public void readIgnoreList() {
readNameIgnoreList(); readNameIgnoreList();
readNumberIgnoreList(); readNumberIgnoreList();
log.info("There are " + ignoreNameList.size() + " names and " + ignoreNumberList.size() + " numbers ignored."); System.out.println("There are " + ignoreNameList.size() + " names and " + ignoreNumberList.size() + " numbers ignored.");
} }
private void readNameIgnoreList() { private void readNameIgnoreList() {
@ -319,11 +290,11 @@ public class Data {
this.ignoreNumberList = (HashSet) ois.readObject(); this.ignoreNumberList = (HashSet) ois.readObject();
} catch (EOFException e) { } catch (EOFException e) {
ignoreNumberList = new HashSet<>(); ignoreNumberList = new HashSet<>();
log.warn("Ignored number list is empty."); System.out.println("Ignored number list is empty.");
writeIgnoreList(IGNORELIST_NUMBER_ONLY); writeIgnoreList(IGNORELIST_NUMBER_ONLY);
} catch (Exception e) { } catch (Exception e) {
ignoreNumberList = new HashSet<>(); ignoreNumberList = new HashSet<>();
log.warn("Failed to load ignored number list"); System.out.println("Failed to load ignored number list");
writeIgnoreList(IGNORELIST_NUMBER_ONLY); writeIgnoreList(IGNORELIST_NUMBER_ONLY);
e.printStackTrace(); e.printStackTrace();
} }

@ -1,24 +1,17 @@
package me.lensferno.dogename.data; package me.lensferno.dogename.data;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.*; import java.io.*;
import java.util.ArrayList; import java.util.ArrayList;
public class History { public class History {
Logger log = LogManager.getLogger(); public static final String separator = File.separator;
private String HISTORY_FILE;
public static final String separator=File.separator;
ArrayList<String> history; ArrayList<String> history;
private String HISTORY_FILE;
public void loadHistory(){ public void loadHistory() {
HISTORY_FILE="files"+separator+"history.data"; HISTORY_FILE = "files" + separator + "history.data";
try { try {
File historyFile = new File(HISTORY_FILE); File historyFile = new File(HISTORY_FILE);
@ -34,57 +27,49 @@ public class History {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(historyFile)); ObjectInputStream ois = new ObjectInputStream(new FileInputStream(historyFile));
history = (ArrayList<String>) ois.readObject(); history = (ArrayList<String>) ois.readObject();
} catch (EOFException e){ } catch (EOFException e) {
history =new ArrayList<>(); history = new ArrayList<>();
log.warn("History file is empty."); System.out.println("History file is empty.");
writeHistory(); writeHistory();
}catch (Exception e) { } catch (Exception e) {
history = new ArrayList<>(); history = new ArrayList<>();
log.error("Failed to load history file:"+e.toString()); System.out.println("Failed to load history file:" + e);
e.printStackTrace(); e.printStackTrace();
} }
} }
public ArrayList<String> getHistoryList(){ public ArrayList<String> getHistoryList() {
return history; return history;
} }
public void addHistory(String name){ public void addHistory(String name) {
if(history.size()>2000) { if (history.size() > 2000) {
history.clear(); history.clear();
} }
history.add(String.format("%d. %s", (history.size() + 1), name)); history.add(String.format("%d. %s", (history.size() + 1), name));
writeHistory(); writeHistory();
} }
private void writeHistory(){ private void writeHistory() {
HISTORY_FILE="files"+separator+"history.data"; HISTORY_FILE = "files" + separator + "history.data";
File historyFile=new File(HISTORY_FILE); File historyFile = new File(HISTORY_FILE);
try{ try {
if (!historyFile.exists()) { if (!historyFile.exists()) {
historyFile.createNewFile(); historyFile.createNewFile();
} }
ObjectOutputStream oos =new ObjectOutputStream(new FileOutputStream(historyFile)); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(historyFile));
oos.writeObject(history); oos.writeObject(history);
oos.close(); oos.close();
}catch (Exception e){ } catch (Exception e) {
log.error("Error in writing history file:"+e); System.out.println("Error in writing history file:" + e);
}
} }
public int downSearch(){
return 1;
}
public int upSearch(){
return 1;
} }
public void clearHistory(){ public void clearHistory() {
this.history.clear(); this.history.clear();
} }

@ -5,13 +5,13 @@ import com.google.gson.annotations.SerializedName;
import javafx.application.Platform; import javafx.application.Platform;
import javafx.scene.control.Label; import javafx.scene.control.Label;
import javafx.scene.layout.Pane; import javafx.scene.layout.Pane;
import me.lensferno.dogename.utils.DialogMaker;
import me.lensferno.dogename.controllers.GushiciPaneController; import me.lensferno.dogename.controllers.GushiciPaneController;
import me.lensferno.dogename.utils.DialogMaker;
import me.lensferno.dogename.utils.NetworkUtil; import me.lensferno.dogename.utils.NetworkUtil;
public class Gushici { public class Gushici {
private final String GUSHICI_API="https://v1.jinrishici.com/all.json"; private final String GUSHICI_API = "https://v1.jinrishici.com/all.json";
String gushiciJSON = null; String gushiciJSON = null;
@ -19,25 +19,26 @@ public class Gushici {
return NetworkUtil.getHtml(GUSHICI_API); return NetworkUtil.getHtml(GUSHICI_API);
} }
public void showGushici(Pane rootPane, Label topBar, boolean showOnDialog){ public void showGushici(Pane rootPane, Label topBar, boolean showOnDialog) {
new Thread(()->{ new Thread(() -> {
//gushiciJSON=getGushici(); //gushiciJSON=getGushici();
String content, title, author, type; String content, title, author, type;
if((gushiciJSON=getGushici())!=null){ if ((gushiciJSON = getGushici()) != null) {
GushiciData gushiciData=new Gson().fromJson(gushiciJSON,GushiciData.class); GushiciData gushiciData = new Gson().fromJson(gushiciJSON, GushiciData.class);
content=gushiciData.getContent(); content = gushiciData.getContent();
title=gushiciData.getTitle(); title = gushiciData.getTitle();
author=gushiciData.getAuthor(); author = gushiciData.getAuthor();
type=gushiciData.getType(); type = gushiciData.getType();
Platform.runLater(()->{ Platform.runLater(() -> {
topBar.setText(content+" ——"+author+"《"+title+"》"); topBar.setText(content + " ——" + author + "《" + title + "》");
topBar.setText(String.format("%s ——%s 《%s》", content, author, title));
if (showOnDialog) { if (showOnDialog) {
GushiciPaneController gushiciPaneController=new GushiciPaneController(content, title, author, type); GushiciPaneController gushiciPaneController = new GushiciPaneController(content, title, author, type);
new DialogMaker(rootPane).createDialogWithOneBtn("每日古诗词",gushiciPaneController); new DialogMaker(rootPane).createDialogWithOneBtn("每日古诗词", gushiciPaneController);
} }
}); });
} }
@ -45,7 +46,7 @@ public class Gushici {
} }
static class GushiciData{ static class GushiciData {
private String content;//诗歌的内容 private String content;//诗歌的内容
@ -57,32 +58,36 @@ public class Gushici {
@SerializedName("category") @SerializedName("category")
private String type;//诗歌类型 private String type;//诗歌类型
public void setContent(String content) {
this.content = content;
}
public String getContent() { public String getContent() {
return content; return content;
} }
public void setTitle(String title) { public void setContent(String content) {
this.title = title; this.content = content;
} }
public String getTitle() { public String getTitle() {
return title; return title;
} }
public void setAuthor(String author) { public void setTitle(String title) {
this.author = author; this.title = title;
} }
public String getAuthor() { public String getAuthor() {
return author; return author;
} }
public void setType(String type) { public void setAuthor(String author) {
this.type = type; this.author = author;
} }
public String getType() { public String getType() {
return type; return type;
} }
public void setType(String type) {
this.type = type;
}
} }
} }

@ -5,8 +5,8 @@ import com.google.gson.annotations.SerializedName;
import javafx.application.Platform; import javafx.application.Platform;
import javafx.scene.control.Label; import javafx.scene.control.Label;
import javafx.scene.layout.Pane; import javafx.scene.layout.Pane;
import me.lensferno.dogename.utils.DialogMaker;
import me.lensferno.dogename.controllers.HitokotoPaneController; import me.lensferno.dogename.controllers.HitokotoPaneController;
import me.lensferno.dogename.utils.DialogMaker;
import me.lensferno.dogename.utils.NetworkUtil; import me.lensferno.dogename.utils.NetworkUtil;
public class Hitokoto { public class Hitokoto {
@ -60,24 +60,20 @@ public class Hitokoto {
private String creator; private String creator;
public void setId(int id) {
this.id = id;
}
public int getId() { public int getId() {
return id; return id;
} }
public void setHitokoto(String hitokoto) { public void setId(int id) {
this.hitokoto = hitokoto; this.id = id;
} }
public String getHitokoto() { public String getHitokoto() {
return hitokoto; return hitokoto;
} }
public void setType(String type) { public void setHitokoto(String hitokoto) {
this.type = type; this.hitokoto = hitokoto;
} }
/** /**
@ -143,29 +139,33 @@ public class Hitokoto {
return type; return type;
} }
public void setFrom(String from) { public void setType(String type) {
this.from = from; this.type = type;
} }
public String getFrom() { public String getFrom() {
return from; return from;
} }
public void setAuthor(String author) { public void setFrom(String from) {
this.author = author; this.from = from;
} }
public String getAuthor() { public String getAuthor() {
return author; return author;
} }
public void setCreator(String creator) { public void setAuthor(String author) {
this.creator = creator; this.author = author;
} }
public String getCreator() { public String getCreator() {
return creator; return creator;
} }
public void setCreator(String creator) {
this.creator = creator;
}
} }
} }

@ -6,8 +6,8 @@ import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener; import javafx.beans.value.ChangeListener;
import me.lensferno.dogename.configs.MainConfig; import me.lensferno.dogename.configs.MainConfig;
import me.lensferno.dogename.configs.VoiceConfig; import me.lensferno.dogename.configs.VoiceConfig;
import me.lensferno.dogename.data.History;
import me.lensferno.dogename.data.Data; import me.lensferno.dogename.data.Data;
import me.lensferno.dogename.data.History;
import me.lensferno.dogename.select.core.Worker; import me.lensferno.dogename.select.core.Worker;
import me.lensferno.dogename.voice.TokenManager; import me.lensferno.dogename.voice.TokenManager;
import me.lensferno.dogename.voice.VoicePlayer; import me.lensferno.dogename.voice.VoicePlayer;
@ -62,9 +62,8 @@ public final class Selector {
// --------------------------------------------------- // ---------------------------------------------------
static class Processor extends AnimationTimer { static class Processor extends AnimationTimer {
private Worker coreWorker;
MainConfig config = null; MainConfig config = null;
private Worker coreWorker;
protected void initialVariable(MainConfig config, VoicePlayer voicePlayer, Data data, History history, StringProperty... labelTexts) { protected void initialVariable(MainConfig config, VoicePlayer voicePlayer, Data data, History history, StringProperty... labelTexts) {
coreWorker = new Worker(labelTexts, config, data, history, voicePlayer); coreWorker = new Worker(labelTexts, config, data, history, voicePlayer);

@ -3,55 +3,40 @@ package me.lensferno.dogename.select.core;
import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.StringProperty; import javafx.beans.property.StringProperty;
import me.lensferno.dogename.configs.MainConfig; import me.lensferno.dogename.configs.MainConfig;
import me.lensferno.dogename.data.History;
import me.lensferno.dogename.data.Data; import me.lensferno.dogename.data.Data;
import me.lensferno.dogename.data.History;
import me.lensferno.dogename.utils.Random; import me.lensferno.dogename.utils.Random;
import me.lensferno.dogename.voice.VoicePlayer; import me.lensferno.dogename.voice.VoicePlayer;
public final class Worker { public final class Worker {
private final Random randomNumber = new Random(); private final Random randomNumber = new Random();
private StringProperty[] labelTexts;
private final SimpleBooleanProperty stoppedIndicator = new SimpleBooleanProperty(true); private final SimpleBooleanProperty stoppedIndicator = new SimpleBooleanProperty(true);
private final MainConfig config; private final MainConfig config;
//挑选方法 //挑选方法
private final int selectMethod = MainConfig.METHOD_NAME; private final int selectMethod = MainConfig.METHOD_NAME;
private final Data data; private final Data data;
private final History history; private final History history;
private final VoicePlayer voicePlayer; private final VoicePlayer voicePlayer;
private int speed = 0;
//数值范围最大最小值 //数值范围最大最小值
private final int[] numberRange = new int[2]; private final int[] numberRange = new int[2];
private final int MIN_NUMBER = 0; private final int MIN_NUMBER = 0;
private final int MAX_NUMBER = 1; private final int MAX_NUMBER = 1;
private final Counter counter = new Counter();
private StringProperty[] labelTexts;
private int speed = 0;
//挑选次数和每一轮的挑选次数 //挑选次数和每一轮的挑选次数
private int maxTotalCount = MainConfig.DEFAULT_MAX_TOTAL_COUNT; private int maxTotalCount = MainConfig.DEFAULT_MAX_TOTAL_COUNT;
private int maxCycleCount = 0; private int maxCycleCount = 0;
//已经挑选了多少次 //已经挑选了多少次
private int totalCount = 0; private int totalCount = 0;
private int cycleCount = 0; private int cycleCount = 0;
private boolean finalResult = true; private boolean finalResult = true;
private boolean forceStop = false; private boolean forceStop = false;
private String selectedResult; private String selectedResult;
private boolean continueSelecting = false; private boolean continueSelecting = false;
private int resultLabelId = 0; private int resultLabelId = 0;
private final Counter counter = new Counter();
public Worker(StringProperty[] labelTexts, MainConfig config, Data data, History history, VoicePlayer voicePlayer) { public Worker(StringProperty[] labelTexts, MainConfig config, Data data, History history, VoicePlayer voicePlayer) {
this.labelTexts = labelTexts; this.labelTexts = labelTexts;
this.config = config; this.config = config;
@ -150,6 +135,31 @@ public final class Worker {
} }
} }
public boolean getStoppedIndicator() {
return stoppedIndicator.get();
}
public SimpleBooleanProperty stoppedIndicatorProperty() {
return stoppedIndicator;
}
public void setNumberRange(int minNumber, int maxNumber) {
this.numberRange[MIN_NUMBER] = minNumber;
this.numberRange[MAX_NUMBER] = maxNumber;
}
public void setForceStop(boolean forceStop) {
this.forceStop = forceStop;
}
public void setMaxTotalCount(int maxTotalCount) {
this.maxTotalCount = maxTotalCount;
}
public void setSpeed(int speed) {
this.speed = speed;
}
// 这里有个内部类Counter计数菌 // 这里有个内部类Counter计数菌
final class Counter { final class Counter {
@ -183,29 +193,4 @@ public final class Worker {
return newResultLabelId; return newResultLabelId;
} }
} }
public boolean getStoppedIndicator() {
return stoppedIndicator.get();
}
public SimpleBooleanProperty stoppedIndicatorProperty() {
return stoppedIndicator;
}
public void setNumberRange(int minNumber, int maxNumber) {
this.numberRange[MIN_NUMBER] = minNumber;
this.numberRange[MAX_NUMBER] = maxNumber;
}
public void setForceStop(boolean forceStop) {
this.forceStop = forceStop;
}
public void setMaxTotalCount(int maxTotalCount) {
this.maxTotalCount = maxTotalCount;
}
public void setSpeed(int speed) {
this.speed = speed;
}
} }

@ -19,84 +19,85 @@ import javafx.scene.text.Text;
public class DialogMaker { public class DialogMaker {
Pane rootPane; Pane rootPane;
JFXDialog dialog;
public DialogMaker(@NamedArg("rootPane") Pane rootPane){
this.rootPane=rootPane;
}
JFXDialog dialog; public DialogMaker(@NamedArg("rootPane") Pane rootPane) {
this.rootPane = rootPane;
}
public void createMessageDialog(@NamedArg("title") String title, @NamedArg("message") String message){ public void createMessageDialog(@NamedArg("title") String title, @NamedArg("message") String message) {
JFXButton OKButton = new JFXButton("了解!"); JFXButton OKButton = new JFXButton("了解!");
OKButton.setFont(Font.font("Microsoft YaHei",FontWeight.BOLD,12)); OKButton.setFont(Font.font("Microsoft YaHei", FontWeight.BOLD, 12));
OKButton.setPrefWidth(60); OKButton.setPrefWidth(60);
OKButton.setPrefHeight(30); OKButton.setPrefHeight(30);
Text messageText=new Text(message); Text messageText = new Text(message);
messageText.setFont(Font.font("Microsoft YaHei",14)); messageText.setFont(Font.font("Microsoft YaHei", 14));
createDialog(title,messageText,OKButton); createDialog(title, messageText, OKButton);
} }
//创建只有一个按钮的dialog //创建只有一个按钮的dialog
public void createDialogWithOneBtn(@NamedArg("title") String title, @NamedArg("theBody") Node body){ public void createDialogWithOneBtn(@NamedArg("title") String title, @NamedArg("theBody") Node body) {
//dialog.setPrefHeight(rootPane.getPrefHeight()); //dialog.setPrefHeight(rootPane.getPrefHeight());
//dialog.setPrefWidth(rootPane.getPrefWidth()); //dialog.setPrefWidth(rootPane.getPrefWidth());
JFXButton OKButton = new JFXButton("好的!"); JFXButton OKButton = new JFXButton("好的!");
OKButton.setFont(Font.font("Microsoft YaHei",FontWeight.BOLD,12)); OKButton.setFont(Font.font("Microsoft YaHei", FontWeight.BOLD, 12));
OKButton.setPrefWidth(60); OKButton.setPrefWidth(60);
OKButton.setPrefHeight(30); OKButton.setPrefHeight(30);
createDialog(title,body,OKButton); createDialog(title, body, OKButton);
dialog.show(); dialog.show();
} }
//创建有OK和cancel按钮的dialog //创建有OK和cancel按钮的dialog
public void createDialogWithOKAndCancel(@NamedArg("title") String title, @NamedArg("message") String message, @NamedArg("OKEvent") EventHandler<ActionEvent> OKEvent){ public void createDialogWithOKAndCancel(@NamedArg("title") String title, @NamedArg("message") String message, @NamedArg("OKEvent") EventHandler<ActionEvent> OKEvent) {
//dialog.setPrefHeight(rootPane.getPrefHeight()); //dialog.setPrefHeight(rootPane.getPrefHeight());
//dialog.setPrefWidth(rootPane.getPrefWidth()); //dialog.setPrefWidth(rootPane.getPrefWidth());
JFXButton CancelButton = new JFXButton("手滑了"); JFXButton CancelButton = new JFXButton("手滑了");
CancelButton.setFont(Font.font("Microsoft YaHei",FontWeight.BOLD,12)); CancelButton.setFont(Font.font("Microsoft YaHei", FontWeight.BOLD, 12));
CancelButton.setPrefWidth(60); CancelButton.setPrefWidth(60);
CancelButton.setPrefHeight(30); CancelButton.setPrefHeight(30);
JFXButton OKButton = new JFXButton("是!"); JFXButton OKButton = new JFXButton("是!");
OKButton.setFont(Font.font("Microsoft YaHei",FontWeight.BOLD,12)); OKButton.setFont(Font.font("Microsoft YaHei", FontWeight.BOLD, 12));
OKButton.setPrefWidth(60); OKButton.setPrefWidth(60);
OKButton.setPrefHeight(30); OKButton.setPrefHeight(30);
OKButton.setTextFill(Paint.valueOf("red")); OKButton.setTextFill(Paint.valueOf("red"));
OKButton.addEventHandler(ActionEvent.ACTION,e -> {dialog.close();}); OKButton.addEventHandler(ActionEvent.ACTION, e -> {
OKButton.addEventHandler(ActionEvent.ACTION,OKEvent); dialog.close();
});
OKButton.addEventHandler(ActionEvent.ACTION, OKEvent);
Text messageText=new Text(message); Text messageText = new Text(message);
messageText.setFont(Font.font("Microsoft YaHei",14)); messageText.setFont(Font.font("Microsoft YaHei", 14));
createDialog(title,messageText,CancelButton,OKButton); createDialog(title, messageText, CancelButton, OKButton);
dialog.show(); dialog.show();
} }
public void createDialog(@NamedArg("title") String title, @NamedArg("theBody") Node body, @NamedArg("buttons") JFXButton...buttons){ public void createDialog(@NamedArg("title") String title, @NamedArg("theBody") Node body, @NamedArg("buttons") JFXButton... buttons) {
JFXDialogLayout content = new JFXDialogLayout(); JFXDialogLayout content = new JFXDialogLayout();
Label titleLabel=new Label(title); Label titleLabel = new Label(title);
titleLabel.setFont(Font.font("Microsoft YaHei", FontWeight.BOLD,20)); titleLabel.setFont(Font.font("Microsoft YaHei", FontWeight.BOLD, 20));
content.setHeading(titleLabel); content.setHeading(titleLabel);
content.setBody(body); content.setBody(body);
content.setAlignment(Pos.CENTER); content.setAlignment(Pos.CENTER);
StackPane tempPane=new StackPane(); StackPane tempPane = new StackPane();
tempPane.setPrefHeight(rootPane.getPrefHeight()); tempPane.setPrefHeight(rootPane.getPrefHeight());
tempPane.setPrefWidth(rootPane.getPrefWidth()); tempPane.setPrefWidth(rootPane.getPrefWidth());
rootPane.getChildren().add(tempPane); rootPane.getChildren().add(tempPane);
dialog = new JFXDialog(tempPane,content,JFXDialog.DialogTransition.TOP); dialog = new JFXDialog(tempPane, content, JFXDialog.DialogTransition.TOP);
dialog.setOnDialogClosed(event -> rootPane.getChildren().remove(tempPane)); dialog.setOnDialogClosed(event -> rootPane.getChildren().remove(tempPane));

@ -1,6 +1,9 @@
package me.lensferno.dogename.utils; package me.lensferno.dogename.utils;
import java.io.*; import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.charset.Charset; import java.nio.charset.Charset;
public class IOUtil { public class IOUtil {
@ -38,7 +41,7 @@ public class IOUtil {
} }
} }
public static void writeFile(byte[] bytes, File file) throws Exception{ public static void writeFile(byte[] bytes, File file) throws Exception {
FileOutputStream fileOutputStream = new FileOutputStream(file); FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(bytes); fileOutputStream.write(bytes);
fileOutputStream.close(); fileOutputStream.close();

@ -1,10 +1,10 @@
package me.lensferno.dogename.utils; package me.lensferno.dogename.utils;
import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.codec.digest.DigestUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.*; import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.NetworkInterface; import java.net.NetworkInterface;
import java.net.URL; import java.net.URL;
@ -16,8 +16,6 @@ import java.util.zip.InflaterInputStream;
public class NetworkUtil { public class NetworkUtil {
private static Logger log = LogManager.getLogger();
public static final String REQUEST_USERAGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.67"; public static final String REQUEST_USERAGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.67";
public static String getHtml(String address) { public static String getHtml(String address) {
@ -61,12 +59,12 @@ public class NetworkUtil {
is.close(); is.close();
} catch (Exception e) { } catch (Exception e) {
log.error("Error in getting HTML:" + e); System.out.println("Error in getting HTML:" + e);
return null; return null;
} }
if (output) if (output)
System.out.println("[INFO]Got:" + sb.toString()); System.out.println("[INFO]Got:" + sb);
return sb.toString(); return sb.toString();
} }

@ -13,16 +13,16 @@ public final class Random {
this.useSecureRandom = useSecureRandom; this.useSecureRandom = useSecureRandom;
} }
public int getRandomNumber (int minNumber, int maxNumber) { public int getRandomNumber(int minNumber, int maxNumber) {
if (useSecureRandom){ if (useSecureRandom) {
return minNumber + secRandom.nextInt(maxNumber - minNumber + 1); return minNumber + secRandom.nextInt(maxNumber - minNumber + 1);
} else { } else {
return minNumber + random.nextInt(maxNumber - minNumber + 1); return minNumber + random.nextInt(maxNumber - minNumber + 1);
} }
} }
public int getRandomNumber (int maxNumber) { public int getRandomNumber(int maxNumber) {
if (useSecureRandom){ if (useSecureRandom) {
return secRandom.nextInt(maxNumber + 1); return secRandom.nextInt(maxNumber + 1);
} else { } else {
return random.nextInt(maxNumber + 1); return random.nextInt(maxNumber + 1);

@ -15,37 +15,37 @@ public class OcrTool {
AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY); AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
String result; String result;
int resultNum=0; int resultNum = 0;
public void requestOcrAPI(String imageFileLocation){ public void requestOcrAPI(String imageFileLocation) {
JSONObject respondJSON=client.basicGeneral(imageFileLocation, new HashMap<>()); JSONObject respondJSON = client.basicGeneral(imageFileLocation, new HashMap<>());
if (respondJSON==null){ if (respondJSON == null) {
result="错误:返回了空的数据。"; result = "错误:返回了空的数据。";
return; return;
} }
if(!respondJSON.has("words_result")){ if (!respondJSON.has("words_result")) {
String errorCode=respondJSON.get("error_code").toString(); String errorCode = respondJSON.get("error_code").toString();
result=findErrorMsg(errorCode); result = findErrorMsg(errorCode);
return; return;
} }
resultNum=respondJSON.getInt("words_result_num"); resultNum = respondJSON.getInt("words_result_num");
System.out.println("total result:"+resultNum); System.out.println("total result:" + resultNum);
JSONArray resultArray=respondJSON.getJSONArray("words_result"); JSONArray resultArray = respondJSON.getJSONArray("words_result");
StringBuffer stringBuffer=new StringBuffer(); StringBuffer stringBuffer = new StringBuffer();
for(int i=0;i<resultArray.length();i++){ for (int i = 0; i < resultArray.length(); i++) {
stringBuffer.append(resultArray.getJSONObject(i).getString("words")).append("\n"); stringBuffer.append(resultArray.getJSONObject(i).getString("words")).append("\n");
} }
result=stringBuffer.toString(); result = stringBuffer.toString();
} }
public String getResult() { public String getResult() {
return result; return result;
} }
private String findErrorMsg(String errorCode){ private String findErrorMsg(String errorCode) {
switch (errorCode){ switch (errorCode) {
case "1": case "1":
return "服务器内部错误,请尝试再次请求。"; return "服务器内部错误,请尝试再次请求。";
case "3": case "3":
@ -77,7 +77,7 @@ public class OcrTool {
case "282000": case "282000":
return "服务器内部错误,如果您使用的是\n高精度接口,原因可能是您上传的图片\n中文字过多,识别超时导致的\n建议您对图片进行切割后再识别,\n其他情况请再次请求。"; return "服务器内部错误,如果您使用的是\n高精度接口,原因可能是您上传的图片\n中文字过多,识别超时导致的\n建议您对图片进行切割后再识别,\n其他情况请再次请求。";
default: default:
return "未知错误。错误码:"+errorCode; return "未知错误。错误码:" + errorCode;
} }
} }

@ -20,10 +20,18 @@ import java.io.File;
public class ScreenCapture { public class ScreenCapture {
private OcrTool ocrTool;
private final String cacheImageFileLocation = "caches/image/ocrImageCache.png"; private final String cacheImageFileLocation = "caches/image/ocrImageCache.png";
private final SimpleStringProperty result = new SimpleStringProperty();
private final SimpleBooleanProperty end = new SimpleBooleanProperty(true);
private final ImageView screenImageView = new ImageView();
private final Pane rootPane = new Pane();
private final Stage stage = new Stage();
private final int screenWidth = Toolkit.getDefaultToolkit().getScreenSize().width;
private final int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height;
private final Line MouseLine_X = new Line();
private final Line MouseLine_Y = new Line();
ScreenshotTool screenshotTool = new ScreenshotTool();
private OcrTool ocrTool;
private final Runnable finalEvent = new Runnable() { private final Runnable finalEvent = new Runnable() {
@Override @Override
public void run() { public void run() {
@ -35,18 +43,19 @@ public class ScreenCapture {
result.set(ocrTool.getResult()); result.set(ocrTool.getResult());
} }
}; };
private double dragStartX = 0;
private double dragStartY = 0;
private final SimpleStringProperty result = new SimpleStringProperty(); private double dragEndX = 0;
private final SimpleBooleanProperty end = new SimpleBooleanProperty(true); private double dragEndY = 0;
private final ImageView screenImageView = new ImageView();
private final Pane rootPane = new Pane();
private final Stage stage = new Stage();
private final int screenWidth = Toolkit.getDefaultToolkit().getScreenSize().width; private double selectedAreaWidth = 0;
private final int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height; private double selectedAreaHeight = 0;
ScreenshotTool screenshotTool = new ScreenshotTool(); private Line Width_Follow;
private Line Height_Follow;
private Line Width_Fixed;
private Line Height_Fixed;
public void startCapture() { public void startCapture() {
end.set(false); end.set(false);
@ -70,7 +79,7 @@ public class ScreenCapture {
Scene scene = new Scene(rootPane, screenWidth, screenHeight); Scene scene = new Scene(rootPane, screenWidth, screenHeight);
//rootPane.setStyle("-fx-background-color: black"); //rootPane.setStyle("-fx-background-color: black");
scene.setOnKeyPressed(e -> { scene.setOnKeyPressed(e -> {
if (e.getCode().equals(KeyCode.ESCAPE)){ if (e.getCode().equals(KeyCode.ESCAPE)) {
stage.close(); stage.close();
end.set(true); end.set(true);
} }
@ -85,20 +94,6 @@ public class ScreenCapture {
stage.show(); stage.show();
} }
private double dragStartX = 0;
private double dragStartY = 0;
private double dragEndX = 0;
private double dragEndY = 0;
private double selectedAreaWidth = 0;
private double selectedAreaHeight = 0;
private Line Width_Follow;
private Line Height_Follow;
private Line Width_Fixed;
private Line Height_Fixed;
private void addEventListeners() { private void addEventListeners() {
rootPane.setOnMousePressed(e -> { rootPane.setOnMousePressed(e -> {
dragStartX = e.getX(); dragStartX = e.getX();
@ -113,16 +108,16 @@ public class ScreenCapture {
rootPane.setOnMouseReleased(e -> { rootPane.setOnMouseReleased(e -> {
dragEndX = e.getX(); dragEndX = e.getX();
dragEndY = e.getY(); dragEndY = e.getY();
int clipPositionX = (int)dragStartX; int clipPositionX = (int) dragStartX;
int clipPositionY = (int)dragStartY; int clipPositionY = (int) dragStartY;
if (selectedAreaWidth < 0) { if (selectedAreaWidth < 0) {
clipPositionX = (int)dragEndX; clipPositionX = (int) dragEndX;
} }
if (selectedAreaHeight < 0) { if (selectedAreaHeight < 0) {
clipPositionY = (int)dragEndY; clipPositionY = (int) dragEndY;
} }
try { try {
this.saveImage(clipPositionX, clipPositionY, Math.abs((int)selectedAreaWidth), Math.abs((int)selectedAreaHeight)); this.saveImage(clipPositionX, clipPositionY, Math.abs((int) selectedAreaWidth), Math.abs((int) selectedAreaHeight));
this.runFinalEvent(finalEvent); this.runFinalEvent(finalEvent);
} catch (Exception exc) { } catch (Exception exc) {
exc.printStackTrace(); exc.printStackTrace();
@ -136,7 +131,7 @@ public class ScreenCapture {
Platform.runLater(finalEvent); Platform.runLater(finalEvent);
} }
private void saveImage(int x, int y, int width, int height){ private void saveImage(int x, int y, int width, int height) {
try { try {
File outputFile = new File(cacheImageFileLocation); File outputFile = new File(cacheImageFileLocation);
File outputDir = outputFile.getParentFile(); File outputDir = outputFile.getParentFile();
@ -181,9 +176,6 @@ public class ScreenCapture {
Height_Follow.layoutYProperty().set(dragStartY); Height_Follow.layoutYProperty().set(dragStartY);
} }
private final Line MouseLine_X = new Line();
private final Line MouseLine_Y = new Line();
private void addMouseLine() { private void addMouseLine() {
MouseLine_X.layoutXProperty().set(0); MouseLine_X.layoutXProperty().set(0);
MouseLine_X.endXProperty().set(screenWidth); MouseLine_X.endXProperty().set(screenWidth);
@ -215,8 +207,17 @@ public class ScreenCapture {
Height_Follow.endYProperty().set(selectedAreaHeight); Height_Follow.endYProperty().set(selectedAreaHeight);
} }
public SimpleStringProperty resultProperty() {
return result;
}
public SimpleBooleanProperty endProperty() {
return end;
}
class ScreenshotTool { class ScreenshotTool {
BufferedImage fullscreenBufferedImage; BufferedImage fullscreenBufferedImage;
public Image getFullScreenshotImageData() { public Image getFullScreenshotImageData() {
try { try {
Robot robot = new Robot(); Robot robot = new Robot();
@ -232,16 +233,8 @@ public class ScreenCapture {
} }
} }
public void saveClippedImage(int x, int y, int width, int height, String formateName, File output) throws Exception{ public void saveClippedImage(int x, int y, int width, int height, String formateName, File output) throws Exception {
ImageIO.write(fullscreenBufferedImage.getSubimage(x, y, width, height), formateName, output); ImageIO.write(fullscreenBufferedImage.getSubimage(x, y, width, height), formateName, output);
} }
} }
public SimpleStringProperty resultProperty() {
return result;
}
public SimpleBooleanProperty endProperty() {
return end;
}
} }

@ -34,20 +34,20 @@ aue =6 ,返回为二进制wav文件,具体header信息 Content-Type: audio/w
return System.currentTimeMillis() > expTime; return System.currentTimeMillis() > expTime;
} }
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getAccessToken() { public String getAccessToken() {
return accessToken; return accessToken;
} }
public void setExpiresIn(long expiresIn) { public void setAccessToken(String accessToken) {
this.expiresIn = expiresIn; this.accessToken = accessToken;
} }
public long getExpiresIn() { public long getExpiresIn() {
return expiresIn; return expiresIn;
} }
public void setExpiresIn(long expiresIn) {
this.expiresIn = expiresIn;
}
} }

@ -2,8 +2,6 @@ package me.lensferno.dogename.voice;
import com.google.gson.Gson; import com.google.gson.Gson;
import me.lensferno.dogename.utils.NetworkUtil; import me.lensferno.dogename.utils.NetworkUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.*; import java.io.*;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
@ -11,29 +9,20 @@ import java.net.URL;
public class TokenManager { public class TokenManager {
Logger log= LogManager.getLogger(); public static final String separator = File.separator;
public static final String separator=File.separator;
private final int TOKEN_NULL = -2;
private final int TOKEN_EXPIRED = -1;
public static final int TOKEN_OK = 0; public static final int TOKEN_OK = 0;
public static final int TOKEN_BAD = 1; public static final int TOKEN_BAD = 1;
final String API_KEY = "dIHCtamVdD0ERO1yyFir2iI4";
final String SEC_KEY = "HmpBQY3gG4PyZ0cmudnCbMeoMcMejuuW";
final String TOKEN_API_URL = "https://openapi.baidu.com/oauth/2.0/token";
private final int TOKEN_NULL = -2;
private final int TOKEN_EXPIRED = -1;
File tokenFile = new File("API_voice.token");
private int tokenStatus = TOKEN_OK; private int tokenStatus = TOKEN_OK;
final String API_KEY="dIHCtamVdD0ERO1yyFir2iI4";
final String SEC_KEY="HmpBQY3gG4PyZ0cmudnCbMeoMcMejuuW";
final String TOKEN_API_URL ="https://openapi.baidu.com/oauth/2.0/token";
File tokenFile=new File("API_voice.token");
private Token token = null; private Token token = null;
private void updateTokenStatus(int statusCode){ private void updateTokenStatus(int statusCode) {
switch(statusCode){ switch (statusCode) {
case TOKEN_OK: case TOKEN_OK:
tokenStatus = TOKEN_OK; tokenStatus = TOKEN_OK;
break; break;
@ -41,42 +30,42 @@ public class TokenManager {
case TOKEN_EXPIRED: case TOKEN_EXPIRED:
case TOKEN_NULL: case TOKEN_NULL:
if(netAvailable()){ if (netAvailable()) {
refreshToken(); refreshToken();
} }
if(checkTokenAvailable()!=0){ if (checkTokenAvailable() != 0) {
tokenStatus = TOKEN_BAD; tokenStatus = TOKEN_BAD;
} }
break; break;
default : default:
tokenStatus = TOKEN_BAD; tokenStatus = TOKEN_BAD;
break; break;
} }
} }
private void refreshToken(){ private void refreshToken() {
fetchToken(); fetchToken();
writeToken(); writeToken();
} }
public void init(){ public void init() {
if(tokenFile.exists()){ if (tokenFile.exists()) {
loadToken(); loadToken();
updateTokenStatus(checkTokenAvailable()); updateTokenStatus(checkTokenAvailable());
}else{ } else {
if(netAvailable()){ if (netAvailable()) {
refreshToken(); refreshToken();
updateTokenStatus(checkTokenAvailable()); updateTokenStatus(checkTokenAvailable());
}else { } else {
tokenStatus = TOKEN_BAD; tokenStatus = TOKEN_BAD;
} }
@ -95,40 +84,40 @@ public class TokenManager {
//token是空的就返回-2 //token是空的就返回-2
if (token == null || token.getAccessToken() == null) { if (token == null || token.getAccessToken() == null) {
log.info("Token was null"); System.out.println("Token was null");
return -2; return -2;
} }
//token过期了就返回-1 //token过期了就返回-1
if (token.isTokenTimeOut()) { if (token.isTokenTimeOut()) {
log.info("Token expired."); System.out.println("Token expired.");
return -1; return -1;
} }
//正常的话就返回0 //正常的话就返回0
log.info("Token OK."); System.out.println("Token OK.");
return 0; return 0;
} }
void fetchToken(){ void fetchToken() {
try{ try {
token=new Gson().fromJson( token = new Gson().fromJson(
NetworkUtil.getHtml( NetworkUtil.getHtml(
TOKEN_API_URL TOKEN_API_URL
+ "?grant_type=client_credentials&client_id=" + API_KEY + "?grant_type=client_credentials&client_id=" + API_KEY
+ "&client_secret=" + SEC_KEY, + "&client_secret=" + SEC_KEY,
true) true)
,Token.class); , Token.class);
token.setExpTime(); token.setExpTime();
}catch (Exception e){ } catch (Exception e) {
log.error("Error to get Token:"+e); System.out.println("Error to get Token:" + e);
token=null; token = null;
} }
} }
private boolean netAvailable(){ private boolean netAvailable() {
try { try {
URL sourcesURL = new URL("http://www.baidu.com"); URL sourcesURL = new URL("http://www.baidu.com");
@ -141,32 +130,32 @@ public class TokenManager {
stream.close(); stream.close();
return true; return true;
}catch (Exception e){ } catch (Exception e) {
log.info("Network is not available."); System.out.println("Network is not available.");
return false; return false;
} }
} }
private void loadToken(){ private void loadToken() {
ObjectInputStream ois; ObjectInputStream ois;
try{ try {
ois =new ObjectInputStream(new FileInputStream(tokenFile)); ois = new ObjectInputStream(new FileInputStream(tokenFile));
this.token =(Token) ois.readObject(); this.token = (Token) ois.readObject();
ois.close(); ois.close();
}catch (Exception e){ } catch (Exception e) {
log.error("Error in loading Token:"+e); System.out.println("Error in loading Token:" + e);
this.token=null; this.token = null;
} }
} }
private void writeToken(){ private void writeToken() {
try{ try {
ObjectOutputStream oos =new ObjectOutputStream(new FileOutputStream(tokenFile)); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(tokenFile));
oos.writeObject(token); oos.writeObject(token);
oos.close(); oos.close();
}catch (Exception e){ } catch (Exception e) {
log.error("Error in writing Token:"+e); System.out.println("Error in writing Token:" + e);
} }
} }

@ -14,11 +14,10 @@ public class VoicePlayer {
public static final String separator = File.separator; public static final String separator = File.separator;
private final String VOICE_API = "https://tsn.baidu.com/text2audio"; private final String VOICE_API = "https://tsn.baidu.com/text2audio";
private VoiceConfig voiceConfig = null;
String cachePath = "caches" + separator + "voice" + separator; String cachePath = "caches" + separator + "voice" + separator;
Token token; Token token;
StreamPlayer streamPlayer = new StreamPlayer();
private VoiceConfig voiceConfig = null;
public VoicePlayer(Token token, VoiceConfig voiceConfig) { public VoicePlayer(Token token, VoiceConfig voiceConfig) {
this.token = token; this.token = token;
@ -90,8 +89,6 @@ public class VoicePlayer {
return success; return success;
} }
StreamPlayer streamPlayer = new StreamPlayer();
private void playSound(File file) { private void playSound(File file) {
try { try {
streamPlayer.open(file); streamPlayer.open(file);

Loading…
Cancel
Save