no message

This commit is contained in:
2024-10-09 22:21:57 +03:00
parent 54c80c516b
commit 6252af944e
699 changed files with 2634 additions and 1997 deletions

View File

@@ -0,0 +1,18 @@
package _VisualDVM.ProjectData.SapforData.Arrays;
import Common.Utils.CommonUtils;
import _VisualDVM.ProjectData.Files.DBProjectFile;
import _VisualDVM.ProjectData.SapforData.FileObjectWithMessages;
// это то что отображается в боковом графе файла. не путать с сапфоровским ProjectArray
public class ArrayDecl extends FileObjectWithMessages {
public String array_name;
public ArrayLocation array_loc;
public ArrayDecl(String array_name_in, ArrayLocation array_loc_in, DBProjectFile father_in, int lineNum_in) {
super(father_in, lineNum_in);
array_name = array_name_in;
array_loc = array_loc_in;
}
@Override
public String Description() {
return array_loc.getDescription() + " массив " + CommonUtils.Brackets(array_name);
}
}

View File

@@ -0,0 +1,40 @@
package _VisualDVM.ProjectData.SapforData.Arrays;
public enum ArrayLocation {
local, common, module, parameter, structure, local_save, unknown;
public static ArrayLocation fromInt(int i) {
switch (i) {
case 0:
return local;
case 1:
return common;
case 2:
return module;
case 3:
return parameter;
case 4:
return structure;
case 5:
return local_save;
default:
return unknown;
}
}
public String getDescription() {
switch (this) {
case local:
return "локальный";
case common:
return "глобальный";
case module:
return "модульный";
case parameter:
return "параметр";
case structure:
return "структура";
case local_save:
return "локальный сохраняемый";
default:
return this.toString();
}
}
}

View File

@@ -0,0 +1,24 @@
package _VisualDVM.ProjectData.SapforData.Arrays;
import javax.swing.*;
import java.net.URL;
public enum ArrayState {
Selected, None, SpfPrivate, IOPrivate, Unknown;
public static ArrayState fromInt(int i) {
switch (i) {
case 0:
return Selected;
case 1:
return None;
case 2:
return SpfPrivate;
case 3:
return IOPrivate;
default:
return Unknown;
}
}
public ImageIcon GetIcon() {
URL imageUrl = getClass().getResource("/icons/Arrays/" + this + ".png");
return new ImageIcon(imageUrl);
}
}

View File

@@ -0,0 +1,83 @@
package _VisualDVM.ProjectData.SapforData.Arrays;
import Common.Utils.CommonUtils;
import _VisualDVM.Current;
import Common.Database.Tables.DataSet;
import Common.Visual.DataSetControlForm;
import _VisualDVM.GlobalData.GlobalDatabase;
import _VisualDVM.GlobalData.Settings.SettingName;
import Visual_DVM_2021.Passes.PassCode_2021;
import Visual_DVM_2021.Passes.Pass_2021;
import java.util.Vector;
import static Common.Visual.Tables.TableEditors.EditorHyperlinks;
import static Common.Visual.Tables.TableRenderers.RendererHiddenList;
import static Common.Visual.Tables.TableRenderers.RendererHyperlinks;
public class ArraysSet extends DataSet<Long, ProjectArray> {
public ArraysSet() {
super(Long.class, ProjectArray.class);
}
@Override
public String getSingleDescription() {
return "массив";
}
@Override
public String getPluralDescription() {
return "объявленные массивы";
}
@Override
public Current CurrentName() {
return Current.ProjectArray;
}
@Override
protected DataSetControlForm createUI() {
return new DataSetControlForm(this) {
@Override
public boolean hasCheckBox() {
return true;
}
@Override
protected void AdditionalInitColumns() {
columns.get(0).setVisible(false);
if (((GlobalDatabase)CommonUtils.db).settings.get(SettingName.ShowFullArraysDeclarations).toBoolean()) {
columns.get(4).setRenderer(RendererHyperlinks);
columns.get(4).setEditor(EditorHyperlinks);
} else {
columns.get(4).setRenderer(RendererHiddenList);
columns.get(4).setMaxWidth(200);
}
}
};
}
@Override
public String[] getUIColumnNames() {
return new String[]{
"Имя", "Область описания", "Файлы объявления", "Размерность", "Размер элемента(байт)", "Область распараллеливания"
};
}
@Override
public Object getFieldAt(ProjectArray object, int columnIndex) {
switch (columnIndex) {
case 1:
return object.State;
case 2:
return object.GetShortNameWithDim();
case 3:
return object.locName + " : " + object.location;
case 4:
return object.GetDeclPlacesList();
case 5:
return object.dimSize;
case 6:
return object.typeSize;
case 7:
return object.GetRegionsText();
default:
return null;
}
}
@Override
public void CheckAll(boolean flag) {
Pass_2021.passes.get(PassCode_2021.MassSelectArrays).Do(flag,new Vector(Current.getProject().declaratedArrays.Data.values()));
}
}

View File

@@ -0,0 +1,145 @@
package _VisualDVM.ProjectData.SapforData.Arrays.Distribution;
import Common.Utils.Index;
import _VisualDVM.ProjectData.SapforData.Arrays.ProjectArray;
import _VisualDVM.ProjectData.SapforData.Regions.ParallelRegion;
import javafx.util.Pair;
import java.math.BigInteger;
import java.util.Vector;
public class AlignRule {
public BigInteger alignArray_address;
public BigInteger alignWith_address;
public ParallelRegion parent_region = null;
public Vector<Pair<Integer, Integer>> alignRule;
public Vector<Pair<Integer, Pair<Integer, Integer>>> alignRuleWith = new Vector<>();
public AlignRule(String[] splited, Index idx) {
alignArray_address = new BigInteger((splited[idx.Inc()]));
alignWith_address = new BigInteger(splited[idx.Inc()]);
int alignRule_size = Integer.parseInt((splited[idx.Inc()]));
alignRule = new Vector<>(alignRule_size);
for (int i = 0; i < alignRule_size; ++i) {
int first = Integer.parseInt(splited[idx.Inc()]);
int second = Integer.parseInt(splited[idx.Inc()]);
alignRule.add(new Pair<>(first, second));
}
int alignRuleWith_size = Integer.parseInt(splited[idx.Inc()]);
alignRuleWith = new Vector<>(alignRuleWith_size);
for (int i = 0; i < alignRuleWith_size; ++i) {
int first = Integer.parseInt(splited[idx.Inc()]);
int first_ = Integer.parseInt(splited[idx.Inc()]);
int second_ = Integer.parseInt(splited[idx.Inc()]);
alignRuleWith.add(new Pair<>(first, new Pair<>(first_, second_)));
}
}
private static Pair<String, String> convertDigitToPositive(int digit) {
String buf = "";
String sign = " + ";
if (digit < 0) {
sign = " - ";
int val = -digit;
buf += String.valueOf(val);
} else
buf += String.valueOf(digit);
return new Pair<>(sign, buf);
}
public ProjectArray getAlignArray() {
return parent_region.arrays.get(alignArray_address);
}
public ProjectArray getAlignWith() {
return parent_region.arrays.get(alignWith_address);
}
String genStringExpr(String letter, Pair<Integer, Integer> expr) {
String retVal = "";
if (expr.getKey() == 0 && expr.getValue() == 0)
retVal = "*";
else if (expr.getValue() == 0) {
if (expr.getKey() == 1)
retVal = letter;
else {
Pair<String, String> digit2 = convertDigitToPositive(expr.getKey());
if (digit2.getKey() == " - ")
retVal = "(-" + digit2.getValue() + ")" + " * " + letter;
else retVal = digit2.getValue() + " * " + letter;
}
} else {
Pair<String, String> digit1 = convertDigitToPositive(expr.getValue());
if (expr.getKey() == 1)
retVal = letter + digit1.getKey() + digit1.getValue();
else {
Pair<String, String> digit2 = convertDigitToPositive(expr.getKey());
if (digit2.getKey() == " - ")
retVal = "(-" + digit2.getValue() + ")" + " * " + letter + digit1.getKey() + digit1.getValue();
else
retVal = digit2.getValue() + " * " + letter + digit1.getKey() + digit1.getValue();
}
}
return retVal;
}
public int GetLenString() {
String val = "";
val += getAlignArray().shortName + "(";
for (int i = 0; i < alignRule.size(); ++i) {
val += genStringExpr(ProjectArray.alignNames[i], alignRule.get(i));
if (i != alignRule.size() - 1)
val += ",";
}
val += ") ";
return val.length();
}
public Pair<String, String> GenRule(int maxArrayStringLen) {
getAlignArray().ac_current.clear();
getAlignArray().ac_new.clear();
getAlignArray().spaces_shift = "";
//------------------------------------------------------------>>>
getAlignArray().align_template = getAlignWith();
getAlignArray().parent_region = parent_region;
//------------------------------------------------------------>>>
String retVal = "";
String arrayString = "";
retVal += getAlignArray().TypeString() + " ";
arrayString += getAlignArray().shortName + "(";
for (int i = 0; i < alignRule.size(); ++i) {
arrayString += genStringExpr(ProjectArray.alignNames[i], alignRule.get(i));
if (i != alignRule.size() - 1)
arrayString += ",";
}
arrayString += ") ";
for (int i = 0; i < maxArrayStringLen - arrayString.length(); ++i) {
getAlignArray().spaces_shift += " ";
}
retVal += getAlignArray().spaces_shift;
retVal += arrayString;
String bracket_open = "(";
String bracket_close = ")";
/*
if (getAlignWith().isTemplFlag > 0)
{
bracket_open = "[";
bracket_close = "]";
}
*/
retVal += "" + getAlignWith().shortName + bracket_open;
Vector<String> alignEachDim = new Vector<>(getAlignWith().dimSize);
for (int i = 0; i < alignEachDim.capacity(); ++i)
alignEachDim.add("*");
for (int i = 0; i < alignRuleWith.size(); ++i) {
if (alignRuleWith.get(i).getKey() != -1) {
alignEachDim.set(alignRuleWith.get(i).getKey(), genStringExpr(ProjectArray.alignNames[i], alignRuleWith.get(i).getValue()));
//коэццициенты находятся здесь!!------------------------------------------------------------------->>
getAlignArray().ac_current.put(i,
new Dimension(i,
alignRuleWith.get(i).getValue().getKey(),
alignRuleWith.get(i).getValue().getValue()
));
} else getAlignArray().ac_current.put(i, new Dimension(i));
}
for (int i = 0; i < alignEachDim.size(); ++i) {
retVal += alignEachDim.get(i);
if (i != getAlignWith().dimSize - 1)
retVal += ",";
}
retVal += bracket_close;// + String_.wands(alignArray.Id.ToString());
return new Pair<>(getAlignWith().shortName, retVal);
}
}

View File

@@ -0,0 +1,49 @@
package _VisualDVM.ProjectData.SapforData.Arrays.Distribution;
import _VisualDVM.ProjectData.SapforData.Arrays.ArrayLocation;
import _VisualDVM.ProjectData.SapforData.Arrays.ProjectArray;
import javafx.util.Pair;
import java.math.BigInteger;
import java.util.LinkedHashMap;
import java.util.Vector;
public class DataDirective extends Directive {
public Vector<AlignRule> alignRules;
public String rules_ = "";
public Vector<String> rules = new Vector<>();
public void genRules_(LinkedHashMap<Long, ProjectArray> Arrays) {
rules_ = "";
int maxLen = 0;
for (AlignRule a : alignRules)
maxLen = Math.max(maxLen, a.GetLenString());
LinkedHashMap<String, Vector<String>> toPrint = new LinkedHashMap<>();
for (AlignRule a : alignRules) {
if (Arrays.get(a.alignArray_address).location != ArrayLocation.parameter) {
Pair<String, String> result = a.GenRule(maxLen);
if (!toPrint.containsKey(result.getKey()))
toPrint.put(result.getKey(), new Vector<>());
toPrint.get(result.getKey()).add(result.getValue());
}
}
for (Vector<String> v : toPrint.values()) {
rules_ += String.join("\n", v);
}
}
public void genRules(LinkedHashMap<BigInteger, ProjectArray> Arrays) {
rules.clear();
int maxLen = 0;
for (AlignRule a : alignRules)
maxLen = Math.max(maxLen, a.GetLenString());
LinkedHashMap<String, Vector<String>> toPrint = new LinkedHashMap<>();
for (AlignRule a : alignRules) {
if (Arrays.get(a.alignArray_address).location != ArrayLocation.parameter) {
Pair<String, String> result = a.GenRule(maxLen);
if (!toPrint.containsKey(result.getKey()))
toPrint.put(result.getKey(), new Vector<>());
toPrint.get(result.getKey()).add(result.getValue());
}
}
for (Vector<String> v : toPrint.values())
for (String r : v)
rules.add(r);
}
}

View File

@@ -0,0 +1,37 @@
package _VisualDVM.ProjectData.SapforData.Arrays.Distribution;
import Common.Database.Objects.DBObject;
import _VisualDVM.ProjectData.SapforData.Arrays.ProjectArray;
public class Dimension extends DBObject {
//--------------------------------------
public int num; //номер измерения.
public int K = 0;
public int B = 0;
public boolean active = false;
//-------------------------------------
public Dimension(int num_in) {
num = num_in;
}
public Dimension(int num_in, int K_in, int B_in) {
num = num_in;
K = K_in;
B = B_in;
active = true;
}
public Dimension clone_() {
Dimension res = new Dimension(num);
res.active = active;
res.K = K;
res.B = B;
return res;
}
@Override
public Object getPK() {
return num;
}
public String getLetter() {
return ProjectArray.alignNames[num];
} //для отображения букв
public int getS() {
return active ? num : -1;
} //для триплета. шифр.
}

View File

@@ -0,0 +1,8 @@
package _VisualDVM.ProjectData.SapforData.Arrays.Distribution;
import _VisualDVM.ProjectData.LanguageName;
public class Directive {
public LanguageName langType = LanguageName.fortran;
public String file = "";
public int line = -1;
public int col = -1;
}

View File

@@ -0,0 +1,399 @@
package _VisualDVM.ProjectData.SapforData.Arrays;
import Common.Utils.CommonUtils;
import _VisualDVM.Current;
import Common.Database.Objects.DBObject;
import Common.Utils.Index;
import _VisualDVM.ProjectData.DBArray.DBArray;
import _VisualDVM.ProjectData.Files.DBProjectFile;
import _VisualDVM.ProjectData.SapforData.Arrays.Distribution.Dimension;
import _VisualDVM.ProjectData.SapforData.Arrays.Templates.TemplateDimension;
import _VisualDVM.ProjectData.SapforData.Arrays.Templates.TemplateDimensionState;
import _VisualDVM.ProjectData.SapforData.Arrays.Templates.TemplateLink;
import _VisualDVM.ProjectData.SapforData.Regions.ParallelRegion;
import _VisualDVM.ProjectData.SapforData.Regions.UI.ArrayAlignmentBar;
import Visual_DVM_2021.Passes.PassCode_2021;
import Visual_DVM_2021.Passes.Pass_2021;
import javafx.util.Pair;
import javax.swing.*;
import java.math.BigInteger;
import java.util.LinkedHashMap;
import java.util.Vector;
import java.util.stream.Collectors;
public class ProjectArray extends DBObject {
//----------------------------------------------------------------------
public static final String[] alignNames = {"i", "j", "k", "l", "m", "n", "q", "r", "s", "t", "u", "w", "x", "y", "z"};
//-
public static String filterName = "";
public static String filterLocation = "";
public static String filterLocationName = "";
public static String filterFile = "";
public static String filterRegion = "*";
public String UniqKey;
public ArrayState State;
//-----------------------------
public long id;
public String name;
public String shortName;
public int dimSize;
public int typeSize;
public ArrayLocation location;
public String locName;
//только для шаблонов. для ФИЛЬТРА управления распределением измерений.
public Vector<TemplateDimension> dimensions = new Vector<>();
public int isTemplFlag;
public int isLoopArrayFlag;
//----------------------------
public BigInteger address;
//----------------------------
public ParallelRegion parent_region = null; //родительяская область распараллеливания.
//связи->
public LinkedHashMap<Long, ProjectArray> links = new LinkedHashMap<>();
//------>
public ProjectArray align_template = null; //ссылка на шаблон на который идет выравнивание.
public String spaces_shift = ""; //смещение из пробелов
//ИЗМЕНЕНИЕ РАСПРЕДЕЛЕНИЯ
//------------------------------------------------------------------------------------------------------>
//текущие
public LinkedHashMap<Integer, Dimension> ac_current = new LinkedHashMap<>();
//кандидаты на замену.
public LinkedHashMap<Integer, Dimension> ac_new = new LinkedHashMap<>();
//https://stackoverflow.com/questions/4941372/how-to-insert-image-into-jtable-cell
public ArrayAlignmentBar bar = null;
//------------------------------------------------------------------------------------------------------>
//<editor-fold desc="Функционал шаблона">
public Vector<BigInteger> regIDs = new Vector<>();
Vector<Pair<Integer, Integer>> sizes = new Vector<>();
Vector<Integer> deprecateToDist = new Vector<>();
Vector<Integer> mappedDims = new Vector<>();
LinkedHashMap<BigInteger, TemplateLink> templateInfo = new LinkedHashMap<>();
Vector<ArrayDecl> declPlaces = new Vector<>();
Vector<String> regions = new Vector<>();
public ProjectArray(String[] infoF, Index idx, BigInteger address_in) {
id = Integer.parseInt(infoF[idx.Inc()]);
name = infoF[idx.Inc()];
shortName = infoF[idx.Inc()];
dimSize = Integer.parseInt(infoF[idx.Inc()]);
typeSize = Integer.parseInt(infoF[idx.Inc()]);
address = address_in;
State = ArrayState.fromInt(Integer.parseInt(infoF[idx.Inc()]));
location = ArrayLocation.fromInt(Integer.parseInt(infoF[idx.Inc()]));
locName = infoF[idx.Inc()];
int sizes_size = Integer.parseInt(infoF[idx.Inc()]);
for (int i = 0; i < sizes_size; ++i) {
int first = Integer.parseInt(infoF[idx.Inc()]);
int second = Integer.parseInt(infoF[idx.Inc()]);
sizes.add(new Pair<>(first, second));
}
sizes_size = Integer.parseInt(infoF[idx.Inc()]);
for (int i = 0; i < sizes_size; ++i)
deprecateToDist.add(Integer.parseInt(infoF[idx.Inc()]));
sizes_size = Integer.parseInt(infoF[idx.Inc()]);
for (int i = 0; i < sizes_size; ++i)
mappedDims.add(Integer.parseInt(infoF[idx.Inc()]));
int templateInfo_size = Integer.parseInt(infoF[idx.Inc()]);
for (int i = 0; i < templateInfo_size; ++i) {
BigInteger key = new BigInteger(infoF[idx.Inc()]);
TemplateLink templateLink = new TemplateLink(infoF, idx);
templateInfo.put(key, templateLink);
}
String[] localSplited = infoF[idx.Inc()].split("\\|");
isTemplFlag = Integer.parseInt(localSplited[0]);
isLoopArrayFlag = Integer.parseInt(localSplited[1]);
int numDeclPlaces = Integer.parseInt(localSplited[2]);
int idxPl = 3;
for (int i = 0; i < numDeclPlaces; ++i, idxPl += 2) {
String declFile = CommonUtils.toW(localSplited[idxPl]);
DBProjectFile file = Current.getProject().db.files.Data.get(declFile);
int declLine = Integer.parseInt(localSplited[idxPl + 1]);
//declPlaces.add(new Pair<>(declFile, declLine));
ArrayDecl decl = new ArrayDecl(shortName, location, file, declLine);
declPlaces.add(decl);
file.array_decls.add(decl); //--
}
int numRegs = Integer.parseInt(localSplited[idxPl++]);
for (int i = 0; i < numRegs; ++i)
regions.add(localSplited[idxPl++]);
UniqKey = shortName + locName + dimSize;
//короткое имя+ функция/модуль/комон+ размерность
}
public static String fill_binary(int d, String binary) {
int delta = Math.abs(binary.length() - d);
String res = binary;
for (int i = 0; i < delta; ++i) {
res = ("0" + res);
}
return res;
}
//длина должна быть равной, ищем есть ли совпадающие позиции с единицами
public static boolean mask(String banned, String variant) {
for (int i = 0; i < variant.length(); ++i)
if ((variant.toCharArray()[i] == '1') && (banned.toCharArray()[i] == '1')) //попался, масконосец!
return true;
return false;
}
public String printLinks() {
Vector<String> res = links.keySet().stream().map(Object::toString).collect(Collectors.toCollection(Vector::new));
return String.join(" ", res);
}
//----------------------------------------------------------------------
@Override
public Object getPK() {
return id;
}
public boolean has_decl_place(String bg_file) {
for (ArrayDecl decl : declPlaces)
if (decl.file.startsWith(bg_file)) return true;
return false;
}
public boolean has_region(String bg_region) {
if (bg_region.equals("*"))
return true;
for (String region : regions)
if (region.startsWith(bg_region)) return true;
return false;
}
public String TypeString() {
return (isLoopArrayFlag == 0) ? ((isTemplFlag == 0) ? "МАССИВ" : "ШАБЛОН") : "ЦИКЛ";
}
public String state_symbol() {
return State == ArrayState.Selected ? "" : "";
}
@Override
public String toString() {
return id + " " + state_symbol() + " " +
State + " " +
shortName + " " +
locName + " : " + location + " " + dimSize + " " + typeSize;
}
public String GetShortNameWithDim() {
String res = shortName + "( ";
if (sizes != null && sizes.size() != dimSize) {
for (int i = 0; i < dimSize; ++i) {
res += alignNames[i];
if (i < dimSize - 1)
res += ", ";
else res += ")";
}
} else {
for (int i = 0; i < dimSize; ++i) {
if (sizes.get(i).getKey() != sizes.get(i).getValue() && sizes.get(i).getKey() != -1)
res += sizes.get(i).getKey() + ":" + sizes.get(i).getValue();
else
res += alignNames[i];
if (i < dimSize - 1)
res += ", ";
else res += ")";
}
}
return res;
}
//-
//для таблицы вариантов, измерения (i,j,k,..)
public String GetShortNameWithDimLetters() {
String res = shortName + "(";
for (int i = 0; i < dimSize; ++i) {
res += alignNames[i];
if (i < dimSize - 1)
res += ",";
else res += ")";
}
return res;
}
//-
public Vector<String> GetDeclPlacesList() {
Vector<String> links = new Vector<>();
for (ArrayDecl d : declPlaces)
links.add(d.file + ":" + d.line);
return links;
}
public String GetRegionsText() {
String res = "";
for (int i = 0; i < regions.size(); ++i)
res += regions.get(i) + ((i != regions.size() - 1) ? "," : "");
return res;
}
public boolean DimDisabled(int dim) {
// не участвует в шаблонах. или явно запрещено
return (mappedDims.get(dim) == 0) || (deprecateToDist.get(dim) == 1);
}
public void CreateDimensions() {
for (BigInteger regID : regIDs) {
ParallelRegion region = Current.getProject().parallelRegions.get(regID);
for (int i = 0; i < Current.getProject().maxdim; ++i) {
dimensions.add(new TemplateDimension(
i, this, region
));
}
}
}
public Object[] CreateTemplateCells() {
Vector<Object> res = new Vector<>();
res.add(this.shortName);
for (int i = 0; i < dimensions.size(); ++i) {
res.add(dimensions.get(i));
}
return res.toArray();
}
//получить двоичное представление варианта распределения и дополнить его нулями.
public String get_binary(long varID) {
String binary = Long.toBinaryString(varID);
return fill_binary(dimSize, binary);
}
public Vector<Long> get_varIDs(boolean filter) {
long d = (long) Math.pow(2, dimSize);
Vector<Long> varIDs = new Vector<>();
Vector<String> DimsDep = new Vector<>();
for (int z = 0; z < mappedDims.size(); ++z)
DimsDep.add(
String.valueOf((DimDisabled(z) ? 1 : 0)));
String banned_dimensions = String.join("", DimsDep);
//------ Дляполностью размноженного нужен d-1 ?
for (long i = 0; i < d; ++i) {
String binary = get_binary(i);
if (!mask(banned_dimensions, binary)) {
if (filter) {
boolean valid = true;
if (Current.getProject().f_distributed())
valid = CheckFilterMask(i, true, binary);
if (valid && Current.getProject().f_multiplied())
valid = CheckFilterMask(i, false, binary);
if (valid)
varIDs.add(i);
} else varIDs.add(i);
}
}
return varIDs;
}
//проверка одиночного вар ида. нужна для минимального покрытия.
public boolean checkVarID(long i, boolean filter) {
Vector<String> DimsDep = new Vector<>();
for (int z = 0; z < mappedDims.size(); ++z)
DimsDep.add(String.valueOf((DimDisabled(z) ? 1 : 0)));
String banned_dimensions = String.join("", DimsDep);
String binary = get_binary(i);
if (!mask(banned_dimensions, binary)) {
if (filter) {
boolean valid = true;
if (Current.getProject().f_distributed())
valid = CheckFilterMask(i, true, binary);
if (valid && Current.getProject().f_multiplied())
valid = CheckFilterMask(i, false, binary);
return valid;
} else return true;
}
return false;
}
public Vector<Long> get_varIDs() {
return get_varIDs(true);
}
//для первичного заполнения рекурсии
public Vector<Vector<BigInteger>> get_triples(boolean filter) {
Vector<Vector<BigInteger>> res = new Vector<>();
Vector<Long> varIDs = get_varIDs(filter);
for (long varID : varIDs) {
for (BigInteger regID : regIDs) //для всех областей
{
Vector<BigInteger> tripple = new Vector<>();
tripple.add(address);
tripple.add(BigInteger.valueOf(varID));
tripple.add(regID);
res.add(tripple);
}
}
return res;
}
public String GetShortNameForVariant(long varID) {
String binary = get_binary(varID);
String res = shortName + "(";
for (int i = 0; i < dimSize; ++i) {
if (i < binary.length()) {
switch (binary.toCharArray()[i]) {
case '0':
res += TemplateDimensionState.multiplied.getDescription();
break;
case '1':
res += TemplateDimensionState.distributed.getDescription();
break;
default:
break;
}
res += CommonUtils.ending(i == binary.length() - 1);
}
}
return res;
}
//</editor-fold>
public String getFilterMask() {
String res = "";
for (int i = 0; i < dimensions.size(); ++i) {
res += (dimensions.get(i).state.ordinal());
}
return res;
}
public boolean CheckFilterMask(long varID, boolean distributed, String binary_in) {
char s = distributed ? '1' : '0';
String filterMask = getFilterMask();
String variant = binary_in.isEmpty() ? get_binary(varID) : binary_in;
for (int i = 0; i < variant.length(); ++i) {
if ((filterMask.toCharArray()[i] == s) && (variant.toCharArray()[i] != s)) return false;
}
return true;
}
public boolean CheckFilterMask(long varID, boolean distributed) {
return CheckFilterMask(varID, distributed, "");
}
public void SaveUserState() throws Exception {
if (Current.getProject().db.savedArrays.Data.containsKey(UniqKey)) {
DBArray sa = Current.getProject().db.savedArrays.Data.get(UniqKey);
sa.State = State;
Current.getProject().db.Update(sa);
} else
Current.getProject().db.Insert(new DBArray(this));
}
//-----------------------------------------------------------------------
@Override
public boolean isSelectionEnabled() {
return (State == ArrayState.Selected) || (State == ArrayState.None);
}
@Override
public ImageIcon GetDisabledIcon() {
return CommonUtils.getIcon("/icons/Arrays/" + State.toString() + ".png");
}
@Override
public void select(boolean flag) {
Pass_2021.passes.get(PassCode_2021.MassSelectArrays).Do(flag, this);
}
@Override
public boolean isSelected() {
return (State == ArrayState.Selected);
}
//-
@Override
public boolean isVisible() {
if (isTemplFlag > 0) return true;
return shortName.startsWith(filterName) &&
location.toString().startsWith(filterLocation) &&
locName.startsWith(filterLocationName) &&
has_decl_place(filterFile) &&
has_region(filterRegion);
}
public void init_new_ac() {
ac_new.clear();
for (int dim : ac_current.keySet())
ac_new.put(dim, ac_current.get(dim).clone_());
}
public boolean ac_need_change() {
for (int dim : ac_current.keySet()) {
Dimension old_ = ac_current.get(dim);
Dimension new_ = ac_new.get(dim);
if ((old_.K != new_.K) || (old_.B != new_.B))
return true;
}
return false;
}
public boolean canBeDistributed() {
return (isLoopArrayFlag == 0) && (isTemplFlag == 0);
}
//----
}

View File

@@ -0,0 +1,34 @@
package _VisualDVM.ProjectData.SapforData.Arrays.Templates;
import Common.Database.Objects.DBObject;
import _VisualDVM.ProjectData.SapforData.Arrays.ProjectArray;
import _VisualDVM.ProjectData.SapforData.Regions.ParallelRegion;
//для генерации вариантов и для управления распределением измерений.
public class TemplateDimension extends DBObject {
public int num = -1;
public ProjectArray template = null;
public ParallelRegion region = null;
public TemplateDimensionState state;
public TemplateDimension(int num_in, ProjectArray template_in, ParallelRegion region_in) {
num = num_in;
template = template_in;
region = region_in;
state = isBlocked() ? TemplateDimensionState.multiplied : TemplateDimensionState.distributed;
}
public boolean isBlocked() {
return (num >= template.dimSize) || template.DimDisabled(num);
}
public void SwitchState() {
switch (state) {
case distributed:
state = TemplateDimensionState.multiplied;
break;
case multiplied:
state = TemplateDimensionState.distributed;
break;
}
}
@Override
public Object getPK() {
return num;
}
}

View File

@@ -0,0 +1,36 @@
package _VisualDVM.ProjectData.SapforData.Arrays.Templates;
import _VisualDVM.Current;
public enum TemplateDimensionState {
multiplied, //0
distributed; //1
public String getMaskDescription() {
switch (this) {
case distributed:
if (Current.getProject().f_distributed()) {
return "BLOCK";
} else {
if (Current.getProject().f_multiplied())
return " X ";
else return "BLOCK";
}
case multiplied:
if (Current.getProject().f_multiplied()) {
return " * ";
} else {
if (Current.getProject().f_distributed())
return " X ";
else return " * ";
}
}
return "?";
}
public String getDescription() {
switch (this) {
case distributed:
return "BLOCK";
case multiplied:
return " * ";
}
return "??";
}
}

View File

@@ -0,0 +1,24 @@
package _VisualDVM.ProjectData.SapforData.Arrays.Templates;
import Common.Utils.Index;
import javafx.util.Pair;
import java.util.Vector;
public class TemplateLink {
Vector<Integer> linkWithTemplate = new Vector<>();
Vector<Pair<Integer, Integer>> alignRuleWithTemplate = new Vector<>();
long templateArray;
public TemplateLink(String[] splited, Index idx) {
int linkWithTemplate_size = Integer.parseInt(splited[idx.Inc()]);
for (int i = 0; i < linkWithTemplate_size; ++i) {
int link_ = Integer.parseInt(splited[idx.Inc()]);
linkWithTemplate.add(link_);
}
int alignRuleWithTemplate_size = Integer.parseInt(splited[idx.Inc()]);
for (int i = 0; i < alignRuleWithTemplate_size; ++i) {
int f = Integer.parseInt(splited[idx.Inc()]);
int s = Integer.parseInt(splited[idx.Inc()]);
alignRuleWithTemplate.add(new Pair<>(f, s));
}
templateArray = Long.parseLong(splited[idx.Inc()]);
}
}

View File

@@ -0,0 +1,20 @@
package _VisualDVM.ProjectData.SapforData.Arrays.UI;
import Common.Visual.CommonUI;
import Common.Visual.Tables.RendererCell;
import Common.Visual.Fonts.VisualiserFonts;
import _VisualDVM.ProjectData.SapforData.Arrays.Templates.TemplateDimension;
import javax.swing.*;
public class DimensionRenderer extends RendererCell<TemplateDimension> {
@Override
public TemplateDimension Init(JTable table, Object value_in, int row, int column) {
return (TemplateDimension) value_in;
}
@Override
public void Display() {
if (value != null) {
setText(value.state.getMaskDescription());
setFont(value.isBlocked() ? CommonUI.getTheme().Fonts.get(VisualiserFonts.Disabled) : CommonUI.getTheme().Fonts.get(VisualiserFonts.Hyperlink));
}
}
}

View File

@@ -0,0 +1,25 @@
package _VisualDVM.ProjectData.SapforData.Arrays.UI;
import Common.Visual.CommonUI;
import Common.Visual.Tables.DBObjectEditor;
import Common.Visual.Fonts.VisualiserFonts;
import _VisualDVM.Visual.UI;
import _VisualDVM.ProjectData.SapforData.Arrays.Templates.TemplateDimension;
import javax.swing.*;
public class DimensionStateChanger extends DBObjectEditor<TemplateDimension> {
@Override
public Object getCellEditorValue() {
return value;
}
@Override
public void InitValue(JTable table, Object value_in, int row, int column) {
value = (TemplateDimension) value_in;
}
@Override
public void Action() {
setFont(CommonUI.getTheme().Fonts.get(VisualiserFonts.Hyperlink));
value.SwitchState();
setText(value.state.getMaskDescription());
UI.getVersionsWindow().getVariantsWindow().ShowFilteredVariantsCount();
}
}

View File

@@ -0,0 +1,56 @@
package _VisualDVM.ProjectData.SapforData.Arrays.UI;
import Common.Visual.CommonUI;
import _VisualDVM.Current;
import Common.Visual.ControlForm;
import Common.Visual.Tables.Grid.GridAnchestor;
import Common.Visual.Tables.StyledTable;
import _VisualDVM.Visual.UI;
import _VisualDVM.ProjectData.SapforData.Arrays.ProjectArray;
import _VisualDVM.ProjectData.SapforData.Arrays.Templates.TemplateDimension;
import java.awt.*;
import java.util.Vector;
import static Common.Visual.Tables.TableEditors.EditorDimension;
import static Common.Visual.Tables.TableRenderers.RendererDimension;
public class DimensionsTableForm extends ControlForm<StyledTable> {
public DimensionsTableForm() {
super(StyledTable.class);
}
@Override
public void Show() {
super.Show();
content.add(scroll, BorderLayout.CENTER);
content.updateUI();
}
@Override
public void Clear() {
super.Clear();
CommonUI.Clear(content);
}
@Override
public void CreateControl() {
Vector<String> columns = new Vector<>();
columns.add("шаблон");
for (int i = 0; i < Current.getProject().maxdim; ++i)
columns.add(ProjectArray.alignNames[i]);
Vector<Object> dimensions = new Vector<>();
Current.getProject().templates.forEach(t -> dimensions.add(t.CreateTemplateCells()));
control = new StyledTable(new GridAnchestor(columns, dimensions) {
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return ((Object[]) data.get(rowIndex))[columnIndex];
}
@Override
public boolean isCellEditable(int row, int col) {
return (col > 0) && !((TemplateDimension) getValueAt(row, col)).isBlocked();
}
}) {
@Override
public void Init() {
setDefaultRenderer(TemplateDimension.class, UI.TableRenderers.get(RendererDimension));
setDefaultEditor(TemplateDimension.class, UI.TableEditors.get(EditorDimension));
}
};
}
}

View File

@@ -0,0 +1,20 @@
package _VisualDVM.ProjectData.SapforData.Arrays.UI;
import _VisualDVM.Visual.Menus.GraphMenu;
import Common.Visual.Trees.StyledTree;
import Visual_DVM_2021.Passes.PassCode_2021;
import Visual_DVM_2021.Passes.Pass_2021;
import javax.swing.*;
public class DistributionMenu extends GraphMenu {
JMenuItem mChangeDistribution;
public DistributionMenu(StyledTree tree) {
super(tree, "области распараллеливания");
mChangeDistribution = Pass_2021.passes.get(PassCode_2021.SPF_ModifyArrayDistribution).createMenuItem();
add(mChangeDistribution);
}
@Override
public void CheckElementsVisibility() {
super.CheckElementsVisibility();
mChangeDistribution.setVisible(Pass_2021.passes.get(PassCode_2021.SPF_GetArrayDistribution).isDone());
}
}

View File

@@ -0,0 +1,12 @@
package _VisualDVM.ProjectData.SapforData.Arrays.UI;
import _VisualDVM.Current;
import _VisualDVM.ProjectData.Files.UI.FileGraphTree;
public class FileArraysTree extends FileGraphTree {
public FileArraysTree() {
super(Current.getFile().getArraysTree());
}
@Override
public String getBranchesName() {
return "объявления массивов";
}
}

View File

@@ -0,0 +1,44 @@
package _VisualDVM.ProjectData.SapforData.Arrays.UI;
import Common.CurrentAnchestor;
import _VisualDVM.Current;
import _VisualDVM.Visual.Menus.GraphMenu;
import Common.Visual.Trees.StyledTree;
import Common.Visual.Trees.TreeRenderers;
import _VisualDVM.ProjectData.SapforData.Regions.ParallelRegion;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import static Common.Visual.Trees.TreeRenderers.RendererRule;
public class RulesTree extends StyledTree {
public RulesTree() {
super(Current.getProject().align_rules_root);
setRootVisible(false);
expandRow(0);
ExpandAll();
CurrentAnchestor.set(Current.ParallelRegion, null);
}
@Override
protected GraphMenu createMenu() {
return new DistributionMenu(this);
}
@Override
public TreeRenderers getRenderer() {
return RendererRule;
}
@Override
public void SelectionAction(TreePath e) {
ParallelRegion region = null;
if (e != null) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getLastPathComponent();
Object o = node.getUserObject();
if (o instanceof String) {
region = (ParallelRegion) ((DefaultMutableTreeNode) node.getParent()).getUserObject();
}
if (o instanceof ParallelRegion) {
region = (ParallelRegion) o;
}
}
CurrentAnchestor.set(Current.ParallelRegion, region);
}
}

View File

@@ -0,0 +1,23 @@
package _VisualDVM.ProjectData.SapforData.Arrays.UI;
import Common.Visual.CommonUI;
import Common.Visual.Fonts.VisualiserFonts;
import Common.Visual.Trees.StyledTreeCellRenderer;
import _VisualDVM.ProjectData.SapforData.Regions.ParallelRegion;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class RulesTreeCellRenderer extends StyledTreeCellRenderer {
public java.awt.Component getTreeCellRendererComponent(
JTree tree, Object value,
boolean selected, boolean expanded,
boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
Object o = ((DefaultMutableTreeNode) value).getUserObject();
if (o instanceof String) {
setFont(CommonUI.getTheme().Fonts.get(VisualiserFonts.Distribution));
} else if (o instanceof ParallelRegion)
setFont(CommonUI.getTheme().Fonts.get(VisualiserFonts.TreeItalic));
setForeground(tree.getForeground());
return this;
}
}

View File

@@ -0,0 +1,29 @@
package _VisualDVM.ProjectData.SapforData;
import Common.Utils.CommonUtils;
import _VisualDVM.Current;
import Common.Database.Objects.iDBObject;
import _VisualDVM.Visual.UI;
import _VisualDVM.ProjectData.Files.DBProjectFile;
import com.sun.org.glassfish.gmbal.Description;
//объект принадлежащий файлу и относящийся к его строке.
public abstract class FileObject extends iDBObject {
@Description("DEFAULT ''")
public String file = "";
@Description("DEFAULT 1")
public int line = 1;
public FileObject() {
}
public FileObject(String file_in) {
file = file_in;
}
@Override
public String getSelectionText() {
return "файл " + CommonUtils.Brackets(file) + " строка: " + line;
}
public DBProjectFile getFather() {
return Current.getProject().db.files.Data.get(file);
}
public void Show(boolean focus) {
UI.getMainWindow().getProjectWindow().GotoFile(file, line, focus);
}
}

View File

@@ -0,0 +1,58 @@
package _VisualDVM.ProjectData.SapforData;
import Common.Visual.Fonts.VisualiserFonts;
import _VisualDVM.ProjectData.Files.DBProjectFile;
import _VisualDVM.ProjectData.Messages.Errors.MessageError;
import _VisualDVM.ProjectData.Messages.Message;
import _VisualDVM.ProjectData.Messages.Notes.MessageNote;
import _VisualDVM.ProjectData.Messages.Warnings.MessageWarning;
public abstract class FileObjectWithMessages extends FileObject {
public String messages_presence = "OK";
public FileObjectWithMessages() {
}
//использовать только если хотим проверять сообщения.
public FileObjectWithMessages(DBProjectFile father_in, int line_in) {
file = father_in.name;
line = line_in;
CheckMessagesPresence();
}
public boolean HasMessage(Message message) {
return message.line == line;
}
public void CheckMessagesPresence() {
messages_presence = "OK";
DBProjectFile father = getFather();
for (MessageError message : father.father.db.errors.Data.values()) {
if (message.file.equals(father.name) && message.line == line) {
messages_presence = "HasErrors";
return;
}
}
for (MessageWarning message : father.father.db.warnings.Data.values()) {
if (message.file.equals(father.name) && message.line == line) {
messages_presence = "HasWarnings";
return;
}
}
for (MessageNote message : father.father.db.notes.Data.values()) {
if (message.file.equals(father.name) && message.line == line) {
messages_presence = "HasNotes";
return;
}
}
}
public String TypeKey() {
return getClass().getSimpleName();
}
public String ImageKey() {
return "/icons/loops/" + messages_presence + TypeKey() + ".png";
}
public VisualiserFonts getFont() {
return VisualiserFonts.TreePlain;
}
//-
public abstract String Description();
@Override
public String toString() {
return Description() + " в строке " + line;
}
}

View File

@@ -0,0 +1,38 @@
package _VisualDVM.ProjectData.SapforData.Functions;
import Common.Utils.CommonUtils;
import Common.Visual.CommonUI;
import _VisualDVM.ProjectData.Files.DBProjectFile;
import _VisualDVM.ProjectData.SapforData.FileObjectWithMessages;
import Visual_DVM_2021.Passes.PassCode_2021;
import Visual_DVM_2021.Passes.Pass_2021;
public class FuncCall extends FileObjectWithMessages {
public String funcName = ""; //не нужны дополнительные поля.имя функции это уже ключ.
public boolean canBeInlined = false;
public int parent_offset = 0;
public FuncCall(DBProjectFile father_in, String funcName_in, int line_in) {
super(father_in, line_in);
funcName = funcName_in;
}
public FuncCall() {
}
@Override
public String getSelectionText() {
return "вызов в строке " + line;
}
@Override
public boolean isSelectionEnabled() {
return canBeInlined;
}
@Override
public String Description() {
return "вызов " + CommonUtils.Brackets(funcName);
}
@Override
public void Select(boolean flag) {
if (Pass_2021.passes.get(PassCode_2021.SPF_GetGraphFunctions).isDone()) {
super.Select(flag);
} else {
CommonUI.Info("Для подстановки функций требуется выполнить проход " + CommonUtils.DQuotes(PassCode_2021.SPF_GetGraphFunctions.getDescription()));
}
}
}

View File

@@ -0,0 +1,47 @@
package _VisualDVM.ProjectData.SapforData.Functions;
import Common.Utils.CommonUtils;
import Common.Visual.CommonUI;
import Visual_DVM_2021.Passes.PassCode_2021;
import Visual_DVM_2021.Passes.Pass_2021;
import java.util.Vector;
public class FuncCallH extends FuncCall {
//--
public Vector<FuncCallH> calls = new Vector<>();
//--
//сообщения не проверяем.
public FuncCallH(FuncCall funcCall_in) {
file = funcCall_in.file;
line = funcCall_in.line;
funcName = funcCall_in.funcName;
canBeInlined = funcCall_in.canBeInlined;
parent_offset = funcCall_in.parent_offset;
}
//особый случай. только для мейна
//его объявление - его же и вызов.
//сообщения не проверяем.
public FuncCallH(FuncInfo funcInfo) {
file = funcInfo.file;
line = funcInfo.line;
funcName = funcInfo.funcName;
canBeInlined = true;
parent_offset = 0;
}
@Override
public String getSelectionText() {
return "вызов " + CommonUtils.Brackets(funcName) + " в строке " + line;
}
@Override
public void SelectAllChildren(boolean select) {
for (FuncCallH callH : calls)
callH.Select(select);
}
@Override
public void Select(boolean flag) {
if (Pass_2021.passes.get(PassCode_2021.SPF_GetGraphFunctions).isDone()) {
super.Select(flag);
} else {
CommonUI.Info("Для подстановки функций требуется выполнить проход " + CommonUtils.DQuotes(PassCode_2021.SPF_GetGraphFunctions.getDescription()));
}
}
}

View File

@@ -0,0 +1,4 @@
package _VisualDVM.ProjectData.SapforData.Functions;
public enum FuncCallState {
Normal, Standard, NotFound
}

View File

@@ -0,0 +1,15 @@
package _VisualDVM.ProjectData.SapforData.Functions;
import Common.Database.Objects.DBObject;
import com.sun.org.glassfish.gmbal.Description;
public class FuncCoordinates extends DBObject {
@Description("PRIMARY KEY, UNIQUE")
public String name = "";
@Description("DEFAULT 0.0")
public Double X = 0.0;
@Description("DEFAULT 0.0")
public Double Y = 0.0;
@Override
public Object getPK() {
return name;
}
}

View File

@@ -0,0 +1,7 @@
package _VisualDVM.ProjectData.SapforData.Functions;
import Common.Database.Tables.DBTable;
public class FuncCoordinatesDBTable extends DBTable<String, FuncCoordinates> {
public FuncCoordinatesDBTable() {
super(String.class, FuncCoordinates.class);
}
}

View File

@@ -0,0 +1,82 @@
package _VisualDVM.ProjectData.SapforData.Functions;
import Common.Utils.CommonUtils;
import Common.Utils.Index;
import _VisualDVM.ProjectData.Files.DBProjectFile;
import _VisualDVM.ProjectData.SapforData.FileObjectWithMessages;
import com.mxgraph.model.mxCell;
import javax.swing.*;
import java.util.LinkedHashMap;
import java.util.Vector;
public class FuncInfo extends FileObjectWithMessages {
//----------------------------------------------------------
public int lineEnd;
public String funcName;
public FunctionType type;
public boolean doNotInline;
public boolean doNotAnalyze;
public boolean needToInline;
public FuncParam parameters;
//вызовы функций в теле этой функции
public Vector<FuncCall> calls = new Vector<>();
//вызовы этой самой функции, рассортированные по файлам.
public LinkedHashMap<String, Vector<FuncCall>> own_calls = new LinkedHashMap<>();
//Узел фуннкции при отрисовке графа процедур.
//Нужен для сохранения всех позиций графа.
public mxCell functionsGraphCell = null;
//это конструктор при пофайловой распаковке. в него попадают только объявленные в проекте функции.
public FuncInfo(String f_name, DBProjectFile father_in, String[] splited, Index calls_number) {
super(father_in, Integer.parseInt(splited[0]));
funcName = f_name;
lineEnd = Integer.parseInt(splited[1]);
calls_number.Set(Integer.parseInt(splited[2]));
needToInline = (Integer.parseInt(splited[3])) != 0;
doNotInline = (Integer.parseInt(splited[4])) != 0;
doNotAnalyze = (Integer.parseInt(splited[5])) != 0;
//в си это поле isMain
type = ((Integer.parseInt(splited[6])) != 0) ? FunctionType.Main : FunctionType.Default;
parameters = new FuncParam();
if (splited.length > 6) {
int countP = Integer.parseInt(splited[7]);
parameters.Init(countP);
for (int z = 0; z < countP * 3; z += 3)
parameters.FillParam(z / 3, splited[8 + z + 2], splited[8 + z], Integer.parseInt(splited[8 + z + 1]));
}
}
//функция без объявления. у нее есть только имя и тип.
public FuncInfo(String f_name, FunctionType type_in) {
funcName = f_name;
type = type_in;
doNotInline = true;
}
//--
@Override
public String getSelectionText() {
return type.getDescription() + " " + CommonUtils.Brackets(funcName);
}
public boolean isMain() {
return type.equals(FunctionType.Main);
}
//------------------------------------------------
@Override
public boolean isSelectionEnabled() {
return false;
}
@Override
public ImageIcon GetDisabledIcon() {
return CommonUtils.getIcon("/icons/Function.png");
}
@Override
public void SelectAllChildren(boolean select) {
for (String file_name : own_calls.keySet())
for (FuncCall fc : own_calls.get(file_name))
fc.Select(select);
}
public boolean isDeclared() {
return type.equals(FunctionType.Main) || type.equals(FunctionType.Default);
}
@Override
public String Description() {
return type.getDescription() + " " + CommonUtils.Brackets(funcName);
}
}

View File

@@ -0,0 +1,60 @@
package _VisualDVM.ProjectData.SapforData.Functions;
import java.util.Vector;
public class FuncParam {
static final int IN_BIT = 16;
static final int OUT_BIT = 256;
Vector<Integer> inout_types;
Vector<String> identificators;
Vector<String> parametersT;
int countOfPars;
public FuncParam() {
countOfPars = 0;
}
public void Init(int numPar) {
countOfPars = numPar;
if (numPar != 0) {
parametersT = new Vector<>(numPar);
inout_types = new Vector<>(numPar);
identificators = new Vector<>(numPar);
for (int z = 0; z < numPar; ++z) {
parametersT.add("NONE_T");
inout_types.add(0);
identificators.add("");
}
}
}
boolean IsArgIn(int num) {
if (num >= countOfPars)
return false;
else
return (inout_types.get(num) & IN_BIT) != 0;
}
boolean IsArgOut(int num) {
if (num >= countOfPars)
return false;
else
return (inout_types.get(num) & OUT_BIT) != 0;
}
boolean IsArgInOut(int num) {
if (num >= countOfPars)
return false;
else
return IsArgIn(num) && IsArgOut(num);
}
public void FillParam(int num, String type, String ident, int inout) {
parametersT.set(num, type);
inout_types.set(num, inout);
identificators.set(num, ident);
}
@Override
public String toString() {
Vector<String> res = new Vector<>();
for (int i = 0; i < countOfPars; ++i) {
String ps = IsArgInOut(i) ? "inout" :
(IsArgOut(i) ? "out" : (IsArgIn(i) ? "in" : "?!"));
ps += " " + inout_types.get(i) + " " + identificators.get(i) + " " + parametersT.get(i);
res.add(ps);
}
return String.join(",", res);
}
}

View File

@@ -0,0 +1,23 @@
package _VisualDVM.ProjectData.SapforData.Functions;
public enum FunctionType {
Default, //обычное объявление
Main, //ГПЕ
//для графа функций
Standard, //стандартная функция
NotFound; //функция не найдена в проекте
//-
public String getDescription() {
switch (this) {
case Default:
return "объявление";
case Main:
return "главная программная единица";
case NotFound:
return "не найдена";
case Standard:
return "стандартная";
default:
return toString();
}
}
}

View File

@@ -0,0 +1,12 @@
package _VisualDVM.ProjectData.SapforData.Functions.UI;
import _VisualDVM.Current;
import _VisualDVM.ProjectData.Files.UI.FileGraphTree;
public class FileFunctionsTree extends FileGraphTree {
public FileFunctionsTree() {
super(Current.getFile().getFunctionsTree());
}
@Override
public String getBranchesName() {
return "объявления процедур";
}
}

View File

@@ -0,0 +1,27 @@
package _VisualDVM.ProjectData.SapforData.Functions.UI.Graph;
import Common.Visual.CommonUI;
import _VisualDVM.Current;
import Common.Visual.ControlForm;
import com.mxgraph.swing.mxGraphComponent;
import java.awt.*;
public class FunctionsGraphForm extends ControlForm<mxGraphComponent> {
public FunctionsGraphForm() {
super(mxGraphComponent.class);
}
@Override
public void CreateControl() {
control = Current.getProject().DrawFunctionsGraph();
}
@Override
public void Show() {
super.Show();
content.add(scroll, BorderLayout.CENTER);
content.updateUI();
}
@Override
public void Clear() {
super.Clear();
CommonUI.Clear(content);
}
}

View File

@@ -0,0 +1,43 @@
package _VisualDVM.ProjectData.SapforData.Functions.UI.Graph;
import Common.CurrentAnchestor;
import Common.Utils.CommonUtils;
import _VisualDVM.Current;
import Common.Visual.Menus.VisualiserMenuItem;
import Common.Visual.Menus.StyledPopupMenu;
import _VisualDVM.Visual.UI;
import Visual_DVM_2021.Passes.All.SPF_GetGraphFunctionPositions;
import Visual_DVM_2021.Passes.PassCode_2021;
import Visual_DVM_2021.Passes.Pass_2021;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class FunctionsGraphMenu extends StyledPopupMenu {
JMenuItem changeCurrent;
public FunctionsGraphMenu() {
changeCurrent = new VisualiserMenuItem("Назначить выбранный узел текущей функцией");
changeCurrent.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (Current.HasSelectedFunction()) {
CurrentAnchestor.set(Current.Function, Current.getSelectionFunction());
UI.getMainWindow().getProjectWindow().getFunctionsWindow().ShowCurrentFunction();
if (SPF_GetGraphFunctionPositions.showByCurrentFunction) {
Pass_2021.passes.get(PassCode_2021.SPF_GetGraphFunctionPositions).Do();
}
}
}
});
add(changeCurrent);
}
@Override
public void CheckElementsVisibility() {
if (Current.HasSelectedFunction()) {
changeCurrent.setText("Назначить процедуру " + CommonUtils.DQuotes(Current.getSelectionFunction().funcName) + " текущей.");
changeCurrent.setEnabled(true);
} else {
changeCurrent.setText("Невозможно назначить текущую процедуру: узел графа не выбран");
changeCurrent.setEnabled(false);
}
}
}

View File

@@ -0,0 +1,264 @@
package _VisualDVM.ProjectData.SapforData.Functions.UI.Graph;
import Common.CurrentAnchestor;
import Common.Utils.CommonUtils;
import Common.Visual.CommonUI;
import _VisualDVM.Current;
import _VisualDVM.ProjectData.SapforData.Functions.FuncCoordinates;
import _VisualDVM.ProjectData.SapforData.Functions.FuncInfo;
import _VisualDVM.ProjectData.SapforData.Functions.FunctionType;
import Visual_DVM_2021.Passes.All.SPF_GetGraphFunctionPositions;
import Visual_DVM_2021.Passes.PassCode_2021;
import Visual_DVM_2021.Passes.Pass_2021;
import com.mxgraph.model.mxCell;
import com.mxgraph.model.mxGeometry;
import com.mxgraph.swing.mxGraphComponent;
import com.mxgraph.util.mxConstants;
import com.mxgraph.util.mxEvent;
import com.mxgraph.util.mxEventObject;
import com.mxgraph.util.mxRectangle;
import com.mxgraph.view.mxGraph;
import com.mxgraph.view.mxStylesheet;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import static com.mxgraph.util.mxConstants.SHAPE_DOUBLE_ELLIPSE;
import static com.mxgraph.util.mxConstants.SHAPE_ELLIPSE;
public class FunctionsGraphUI extends mxGraph {
//--
public final static Timer ffTimer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Pass_2021.passes.get(PassCode_2021.SPF_GetGraphFunctionPositions).Do();
}
});
//---
private static final int default_width = 80;
private static final int default_height = 30;
//форма узлов?
// https://progi.pro/kak-sdelat-parallelogrammnuyu-vershinu-v-jgraphx-13032580
//мануал
//https://jgraph.github.io/mxgraph/docs/manual_javavis.html
//https://jgraph.github.io/mxgraph/java/docs/com/mxgraph/swing/mxGraphComponent.html
//общий манул
//https://jgraph.github.io/mxgraph/docs/manual_javavis.html#1.3
//манул п кликам?
//https://github.com/jgraph/mxgraph/blob/master/java/examples/com/mxgraph/examples/swing/ClickHandler.java
//все образцы
//https://github.com/jgraph/mxgraph/tree/master/java/examples/com/mxgraph/examples/swing
//https://github.com/jgraph/jgraphx/blob/master/src/com/mxgraph/util/mxConstants.java
//про размеры
//https://stackoverflow.com/questions/51619879/mxgraph-how-to-automatically-resize-mxcell-to-content-width-if-it-exceeds-the
//---------------------
//координаты вершин графа
// public LinkedHashMap<String, Pair<Double, Double>> vertexCoordinates = new LinkedHashMap<>();
protected GraphInfo graph = null; //инфа о вершинах и ребрах.
public FunctionsGraphUI(GraphInfo graph_in) {
graph = graph_in;
//настройки графа
setGridEnabled(true);
//setAllowNegativeCoordinates(false);
setAllowDanglingEdges(false); //запрет на висячие ребра.
setCellsEditable(false); //запрет на редактирование клеток
setCellsResizable(false); //запрет изменения размера клеток
setKeepEdgesInBackground(true); // ребра на задний план. очень важно.
setDropEnabled(false);
setAutoSizeCells(true);
setConnectableEdges(false);
setCellsCloneable(false);
//--------------------
mxStylesheet stylesheet = getStylesheet();
Hashtable<String, Object> style = new Hashtable<String, Object>();
style.put(mxConstants.STYLE_SHAPE, SHAPE_ELLIPSE);
style.put(mxConstants.STYLE_FONTCOLOR, "black");
style.put(mxConstants.STYLE_FILLCOLOR, "yellow");
style.put(mxConstants.STYLE_FONTSIZE, "16");
style.put(mxConstants.STYLE_FONTSTYLE, mxConstants.FONT_BOLD);
stylesheet.putCellStyle(FunctionType.Default.toString(), style);
//------------------------------------------
style = new Hashtable<String, Object>();
style.put(mxConstants.STYLE_SHAPE, SHAPE_ELLIPSE);
style.put(mxConstants.STYLE_FONTCOLOR, "black");
style.put(mxConstants.STYLE_FILLCOLOR, "lightgreen");
style.put(mxConstants.STYLE_FONTSIZE, "16");
style.put(mxConstants.STYLE_FONTSTYLE, mxConstants.FONT_BOLD);
stylesheet.putCellStyle(FunctionType.Main.toString(), style);
//------------------------------------------
style = new Hashtable<String, Object>();
style.put(mxConstants.STYLE_SHAPE, SHAPE_ELLIPSE);
style.put(mxConstants.STYLE_FONTCOLOR, "black");
style.put(mxConstants.STYLE_FILLCOLOR, "lightgray");
style.put(mxConstants.STYLE_FONTSIZE, "16");
style.put(mxConstants.STYLE_FONTSTYLE, mxConstants.FONT_BOLD);
// style.put(mxConstants.STYLE_STROKECOLOR, "lawngreen"); это и есть границы.
// style.put(mxConstants.STYLE_STROKEWIDTH, 5);
stylesheet.putCellStyle(FunctionType.Standard.toString(), style);
//------------------------------------------
style = new Hashtable<String, Object>();
style.put(mxConstants.STYLE_SHAPE, SHAPE_ELLIPSE);
style.put(mxConstants.STYLE_FONTCOLOR, "white");
style.put(mxConstants.STYLE_FILLCOLOR, "darkred");
style.put(mxConstants.STYLE_FONTSIZE, "16");
style.put(mxConstants.STYLE_FONTSTYLE, mxConstants.FONT_BOLD);
stylesheet.putCellStyle(FunctionType.NotFound.toString(), style);
//------------------------------------------
style = new Hashtable<String, Object>();
style.put(mxConstants.STYLE_SHAPE, SHAPE_DOUBLE_ELLIPSE);
style.put(mxConstants.STYLE_FONTCOLOR, "black");
style.put(mxConstants.STYLE_FILLCOLOR, "lightblue");
style.put(mxConstants.STYLE_FONTSIZE, "16");
style.put(mxConstants.STYLE_FONTSTYLE, mxConstants.FONT_BOLD);
// style.put(mxConstants.STYLE_STROKECOLOR, "lawngreen"); это и есть границы.
// style.put(mxConstants.STYLE_STROKEWIDTH, 5);
stylesheet.putCellStyle("current", style);
}
//---
// еще один туториал?
// https://www.47.gbmse.ru/resources/utility/mxgraph/docs/tutorial.html
//
//https://github.com/jgraph/mxgraph/tree/master/java/examples/com/mxgraph/examples/swing
//https://jgraph.github.io/mxgraph/java/docs/com/mxgraph/swing/mxGraphComponent.html
//https://www.47.gbmse.ru/resources/utility/mxgraph/docs/tutorial.html#3.2
public mxGraphComponent Draw() {
FuncInfo funcInfo = null;
//установить координаты вершин.
SetCoordinates(); //пустышка.
Object parent = getDefaultParent();
getModel().beginUpdate();
//непосредственное добавление графики
//------------------------------------
//размеры
//https://stackoverflow.com/questions/51619879/mxgraph-how-to-automatically-resize-mxcell-to-content-width-if-it-exceeds-the
// UI.Info("++");
LinkedHashMap<String, Object> mxVertexes = new LinkedHashMap<>();
for (String name : graph.vertexCoordinates.keySet()) {
funcInfo = Current.getProject().allFunctions.get(name);
String vertexType = funcInfo.type.toString();
if (SPF_GetGraphFunctionPositions.showByCurrentFunction) {
FuncInfo current_fi = (FuncInfo) CurrentAnchestor.get(Current.Function);
if ((current_fi != null) && (funcInfo.funcName.equals(current_fi.funcName))) {
vertexType = "current";
}
}
mxVertexes.put(name,
insertVertex(parent,
name, //идентификатор вершины. должен быть уникальным.
name, //объект не стоит делать. какие то мутки при перетаскивании объектов.
//строки-ключа уже достаточно
//координаты вершины
graph.vertexCoordinates.get(name).getKey(),
graph.vertexCoordinates.get(name).getValue(),
default_width, default_height,
vertexType
));
}
for (String name : graph.vertexMap.keySet()) {
mxCell cell = (mxCell) mxVertexes.get(name);
mxRectangle preferred = getPreferredSizeForCell(cell);
mxGeometry current = cell.getGeometry();
current.setWidth((preferred.getWidth() > default_width) ? preferred.getWidth() : default_width);
//updateCellSize(cell, true); это если просто везде выставить авторазмер.
//тут же нам нужно применить его только в случае если ширина меньше чем надо.
for (String neigbor : graph.vertexMap.get(name)) {
insertEdge(parent, null,
//надпись над ребром.
"",
//вершина 1
mxVertexes.get(name),
//вершина 2
mxVertexes.get(neigbor));
}
}
//------------------------------------
//https://java.hotexamples.com/examples/com.mxgraph.view/mxGraph/setAutoSizeCells/java-mxgraph-setautosizecells-method-examples.html
groupCells();
getModel().endUpdate();
//------------------------------------
//обертка графа контролом
mxGraphComponent graphComponent = new mxGraphComponent(this);
graphComponent.setZoomFactor(1.10);
//--
// https://programtalk.com/java-more-examples/com.mxgraph.util.mxEvent.UP/
addListener(mxEvent.CELLS_MOVED, new mxIEventListener() {
@Override
public void invoke(Object o, mxEventObject mxEventObject) {
//Сохранение координат графа при сдвиге узла
if (mxEventObject.getProperties().containsKey("cells")) {
Object[] cells = (Object[]) mxEventObject.getProperties().get("cells");
for (Object cell_ : cells) {
if (cell_ instanceof mxCell) {
mxCell cell = (mxCell) cell_;
if (cell.isVertex()) {
String funcName = (String) cell.getValue();
FuncCoordinates coords = null;
// UI.Info(cell.getGeometry().getPoint().toString());
Point point = cell.getGeometry().getPoint();
try {
if (Current.getProject().db.funcCoordinates.containsKey(funcName)) {
coords = Current.getProject().db.funcCoordinates.get(funcName);
coords.name = funcName;
coords.X = point.getX();
coords.Y = point.getY();
Current.getProject().db.Update(coords);
} else {
coords = new FuncCoordinates();
coords.name = funcName;
coords.X = point.getX();
coords.Y = point.getY();
Current.getProject().db.Insert(coords);
}
} catch (Exception ignored) {
}
}
}
}
}
}
});
graphComponent.getGraphControl().setComponentPopupMenu(new FunctionsGraphMenu());
//обработка клика мышом.
graphComponent.getGraphControl().addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
Object cell = graphComponent.getCellAt(e.getX(), e.getY());
if (cell != null) {
mxCell mx_cell = (mxCell) cell;
if (mx_cell.isVertex()) {
String func_name = (String) mx_cell.getValue();
FuncInfo fi = Current.getProject().allFunctions.get(func_name);
switch (e.getClickCount()) {
case 1:
CurrentAnchestor.set(Current.SelectedFunction, fi);
break;
case 2:
switch (fi.type) {
case Default:
case Main:
fi.Show(true);
break;
case Standard:
case NotFound:
CommonUI.Info("процедура " + CommonUtils.Brackets(func_name) + " " + fi.type.getDescription());
break;
}
break;
}
}
}
}
});
graphComponent.getViewport().setBackground(Color.WHITE);
return graphComponent;
}
//по умолчанию ничего не меняем.
public void SetCoordinates() {
}
public void SaveCoords() {
}
}

View File

@@ -0,0 +1,80 @@
package _VisualDVM.ProjectData.SapforData.Functions.UI.Graph;
import javafx.util.Pair;
import java.util.LinkedHashMap;
import java.util.Vector;
public class FunctionsGraphUIGreed extends FunctionsGraphUI {
//веса вершин.
protected LinkedHashMap<String, Integer> weights = new LinkedHashMap<>();
//группы вершин по весам.в порядке убывания весов.
protected LinkedHashMap<Integer, Vector<String>> groups = new LinkedHashMap<>();
public FunctionsGraphUIGreed(GraphInfo graph_in) {
super(graph_in);
}
@Override
public void SetCoordinates() {
//получить веса вершин.
for (String name : graph.vertexMap.keySet()) {
Vector<String> edges = graph.vertexMap.get(name);
//как минимум, вес вершины - это все исходящие из нее ребра.
if (!weights.containsKey(name)) weights.put(name, edges.size());
else weights.replace(name, weights.get(name) + edges.size());
for (String dst : edges) {
//есть ребро, значит уже вес 1
if (!weights.containsKey(dst)) weights.put(dst, 1);
else weights.replace(dst, weights.get(dst) + 1);
}
}
//сортировка по весу вершин.
//1 определить максимальный вес.
int max = 0;
for (String name : weights.keySet())
if (weights.get(name) > max) max = weights.get(name);
for (int i = max; i >= 0; --i) {
Vector<String> current_group = new Vector<>();
for (String name : weights.keySet()) {
if (weights.get(name) == i) current_group.add(name);
}
if (current_group.size() > 0) {
groups.put(i, current_group);
}
}
//linked hash map - сохраняет порядок. поэтому они уже по убыванию.
//теперь координаты. берем самую тыжелую группу, правильный многоугольник по центру
//поток следующая, вокруг первого, и т д.
int R = 150;
int i = 0;
double x_offet = 0;
double y_ofset = 0;
double rot = 0.0; //чтобы не было линеечки с каждой группой вращаем многоугольники.
for (int w : groups.keySet()) {
//первая вершина - особый случай. если она одна - ее в центр и надо
if ((i == 0) && (groups.get(w).size() == 1)) {
graph.vertexCoordinates.put(groups.get(w).get(0), new Pair<>(0.0, 0.0));
} else {
double phi0 = rot;
double phi = 2 * Math.PI / groups.get(w).size();
for (String name : groups.get(w)) {
double x = R * Math.cos(phi0);
double y = R * Math.sin(phi0);
if (x < x_offet) x_offet = x;
if (y < y_ofset) y_ofset = y;
//todo добавить в рассчет прямоугольник и самой вершины.
graph.vertexCoordinates.put(name, new Pair<>(x, y));
phi0 += phi;
}
R += 100;
}
++i;
rot += 10;
if (rot > 360.0) rot = 0.0;
}
x_offet *= -1;
y_ofset *= -1;
//теперь надо применить смещение. смещение. чтобы не было отрицательных координат.
for (String name : graph.vertexCoordinates.keySet()) {
Pair<Double, Double> old = graph.vertexCoordinates.get(name);
graph.vertexCoordinates.replace(name, new Pair<>(old.getKey() + x_offet + 50, old.getValue() + y_ofset + 50));
}
}
}

View File

@@ -0,0 +1,68 @@
package _VisualDVM.ProjectData.SapforData.Functions.UI.Graph;
import Common.Utils.CommonUtils;
import com.mxgraph.swing.mxGraphComponent;
import javafx.util.Pair;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Vector;
//только инфа о вершинах и ребрах. без отрисовки.
public class GraphInfo {
//вершины графа и ребра
public LinkedHashMap<String, Vector<String>> vertexMap = new LinkedHashMap<>();
//координаты для отрисовки. раз это теперь полноценная инфа, которая передается извне.
public LinkedHashMap<String, Pair<Double, Double>> vertexCoordinates = new LinkedHashMap<>();
//----------------
public void addVertex(String vertexName) {
if (!hasVertex(vertexName)) {
vertexMap.put(vertexName, new Vector<>());
}
}
public boolean hasVertex(String vertexName) {
return vertexMap.containsKey(vertexName);
}
//-----------------
public boolean hasEdge(String vertexName1, String vertexName2) {
if (!hasVertex(vertexName1)) return false;
Vector<String> edges = vertexMap.get(vertexName1);
for (String end : edges)
if (end.equals(vertexName2)) return true;
return false;
}
public void addEdge(String vertexName1, String vertexName2) {
if (!hasVertex(vertexName1)) addVertex(vertexName1);
if (!hasVertex(vertexName2)) addVertex(vertexName2);
if (!hasEdge(vertexName1, vertexName2)) {
//находим список смежности, и добавляем новую вершину.
Vector<String> edges1 = vertexMap.get(vertexName1);
edges1.add(vertexName2);
Collections.sort(edges1);
}
}
//-
public void Print() {
Vector<String> edges = new Vector<>();
for (String name : vertexMap.keySet()) {
for (String neighbor : vertexMap.get(name)) {
edges.add(CommonUtils.Brackets(name + "," + neighbor));
}
}
}
public boolean isEmpty() {
return vertexMap.isEmpty();
}
public void Clear() {
vertexMap.clear();
vertexCoordinates.clear();
}
/*
public void ClearCoords() {
vertexCoordinates.clear();
}
*/
public mxGraphComponent Draw() {
// return new FunctionsGraphUIGreed(this).Draw();
return new FunctionsGraphUI(this).Draw();
}
}

View File

@@ -0,0 +1,19 @@
package _VisualDVM.ProjectData.SapforData.Functions.UI;
import _VisualDVM.Current;
import _VisualDVM.Visual.Menus.SelectionTreeMenu;
import Common.Visual.Trees.SelectableTree;
import _VisualDVM.ProjectData.SapforData.Functions.FuncInfo;
public class InlineMenu extends SelectionTreeMenu {
public InlineMenu(SelectableTree tree_in) {
super(tree_in);
}
@Override
public Class getTargetClass() {
return FuncInfo.class;
}
@Override
public void SelectAll(boolean select) {
for (FuncInfo fi : Current.getProject().allFunctions.values())
fi.SelectAllChildren(select);
}
}

View File

@@ -0,0 +1,27 @@
package _VisualDVM.ProjectData.SapforData.Functions.UI;
import _VisualDVM.Visual.Menus.SelectionTreeMenu;
import Common.Visual.Trees.SelectableTree;
import _VisualDVM.ProjectData.SapforData.Functions.FuncCallH;
import javax.swing.tree.DefaultMutableTreeNode;
public class InlineMenu2 extends SelectionTreeMenu {
public InlineMenu2(SelectableTree tree_in) {
super(tree_in);
}
@Override
public Class getTargetClass() {
return FuncCallH.class;
}
@Override
public void SelectAll(boolean select) {
if (tree.root.getChildCount() == 1)
SelectR(
(FuncCallH) ((DefaultMutableTreeNode) (tree.root.getChildAt(0))).getUserObject(),
select);
}
public void SelectR(FuncCallH callH, boolean select) {
callH.Select(select);
for (FuncCallH child : callH.calls)
SelectR(child, select);
}
}

View File

@@ -0,0 +1,35 @@
package _VisualDVM.ProjectData.SapforData.Functions.UI;
import Common.CurrentAnchestor;
import _VisualDVM.Current;
import _VisualDVM.Visual.Menus.GraphMenu;
import Common.Visual.Trees.SelectableTree;
import Common.Visual.Trees.TreeRenderers;
import _VisualDVM.ProjectData.SapforData.FileObject;
public class InlineTree extends SelectableTree {
public InlineTree() {
super(Current.getProject().inline_root);
}
@Override
public TreeRenderers getRenderer() {
return TreeRenderers.RendererSelection;
}
@Override
public Current getCurrent() {
return Current.InlineGraphElement;
}
@Override
public void ShowCurrentObject() {
Object o = CurrentAnchestor.get(getCurrent());
if (o instanceof FileObject) {
((FileObject) o).Show(false);
}
}
@Override
protected GraphMenu createMenu() {
return new InlineMenu(this);
}
@Override
protected int getStartLine() {
return 1;
}
}

View File

@@ -0,0 +1,35 @@
package _VisualDVM.ProjectData.SapforData.Functions.UI;
import Common.CurrentAnchestor;
import _VisualDVM.Current;
import _VisualDVM.Visual.Menus.GraphMenu;
import Common.Visual.Trees.SelectableTree;
import Common.Visual.Trees.TreeRenderers;
import _VisualDVM.ProjectData.SapforData.FileObject;
public class InlineTree2 extends SelectableTree {
public InlineTree2() {
super(Current.getProject().inline_root2);
}
@Override
public TreeRenderers getRenderer() {
return TreeRenderers.RendererSelection;
}
@Override
public Current getCurrent() {
return Current.InlineGraphElement2;
}
@Override
protected GraphMenu createMenu() {
return new InlineMenu2(this);
}
@Override
public void ShowCurrentObject() {
Object o = CurrentAnchestor.get(getCurrent());
if (o instanceof FileObject) {
((FileObject) o).Show(false);
}
}
@Override
protected int getStartLine() {
return 1;
}
}

View File

@@ -0,0 +1,14 @@
package _VisualDVM.ProjectData.SapforData.Includes;
import Common.Utils.CommonUtils;
import _VisualDVM.ProjectData.SapforData.FileObject;
public class DependencyInfo extends FileObject {
public DependencyInfo(String file_in) {
super(file_in);
}
@Override
public String getSelectionText() {
return "включение: " + CommonUtils.Brackets(file);
}
//мб на будущее расширить, в какой строке находится команда икнлудить файл.
// но это уже к Сапфору
}

View File

@@ -0,0 +1,29 @@
package _VisualDVM.ProjectData.SapforData.Includes;
import Common.Utils.CommonUtils;
import _VisualDVM.ProjectData.SapforData.FileObject;
import javax.swing.*;
import java.util.Vector;
public class FileInfo extends FileObject {
public Vector<DependencyInfo> dependencies = new Vector<>();
public FileInfo(String file_in) {
super(file_in);
}
@Override
public String getSelectionText() {
return file;
}
@Override
public boolean isSelectionEnabled() {
return false;
}
@Override
public ImageIcon GetDisabledIcon() {
return CommonUtils.getIcon("/icons/File.png");
}
@Override
public void SelectAllChildren(boolean select) {
for (DependencyInfo di : dependencies)
di.Select(select);
}
}

View File

@@ -0,0 +1,19 @@
package _VisualDVM.ProjectData.SapforData.Includes.UI;
import _VisualDVM.Current;
import _VisualDVM.Visual.Menus.SelectionTreeMenu;
import Common.Visual.Trees.SelectableTree;
import _VisualDVM.ProjectData.SapforData.Includes.FileInfo;
public class IncludesMenu extends SelectionTreeMenu {
public IncludesMenu(SelectableTree tree_in) {
super(tree_in);
}
@Override
public Class getTargetClass() {
return FileInfo.class;
}
@Override
public void SelectAll(boolean select) {
for (FileInfo fi : Current.getProject().addictedFiles.values())
fi.SelectAllChildren(select);
}
}

View File

@@ -0,0 +1,22 @@
package _VisualDVM.ProjectData.SapforData.Includes.UI;
import _VisualDVM.Current;
import _VisualDVM.Visual.Menus.GraphMenu;
import Common.Visual.Trees.SelectableTree;
import Common.Visual.Trees.TreeRenderers;
public class IncludesTree extends SelectableTree {
public IncludesTree() {
super(Current.getProject().includes_root);
}
@Override
public Current getCurrent() {
return Current.IncludeGraphElement;
}
@Override
public TreeRenderers getRenderer() {
return TreeRenderers.RendererSelection;
}
@Override
protected GraphMenu createMenu() {
return new IncludesMenu(this);
}
}

View File

@@ -0,0 +1,17 @@
package _VisualDVM.ProjectData.SapforData.Loops;
import Common.Visual.Fonts.VisualiserFonts;
import _VisualDVM.ProjectData.Files.DBProjectFile;
import _VisualDVM.ProjectData.SapforData.FileObjectWithMessages;
public class EGoto extends FileObjectWithMessages {
public EGoto(DBProjectFile father_in, int lineNum_in) {
super(father_in, lineNum_in);
}
@Override
public String Description() {
return "вход внутрь цикла";
}
@Override
public VisualiserFonts getFont() {
return VisualiserFonts.BadState;
}
}

View File

@@ -0,0 +1,17 @@
package _VisualDVM.ProjectData.SapforData.Loops;
import Common.Visual.Fonts.VisualiserFonts;
import _VisualDVM.ProjectData.Files.DBProjectFile;
import _VisualDVM.ProjectData.SapforData.FileObjectWithMessages;
public class IGoto extends FileObjectWithMessages {
public IGoto(DBProjectFile father_in, int lineNum_in) {
super(father_in, lineNum_in);
}
@Override
public String Description() {
return "выход за пределы цикла";
}
@Override
public VisualiserFonts getFont() {
return VisualiserFonts.BadState;
}
}

View File

@@ -0,0 +1,17 @@
package _VisualDVM.ProjectData.SapforData.Loops;
import Common.Visual.Fonts.VisualiserFonts;
import _VisualDVM.ProjectData.Files.DBProjectFile;
import _VisualDVM.ProjectData.SapforData.FileObjectWithMessages;
public class IO extends FileObjectWithMessages {
public IO(DBProjectFile father_in, int lineNum_in) {
super(father_in, lineNum_in);
}
@Override
public String Description() {
return "оператор ввода-вывода";
}
@Override
public VisualiserFonts getFont() {
return VisualiserFonts.BadState;
}
}

View File

@@ -0,0 +1,103 @@
package _VisualDVM.ProjectData.SapforData.Loops;
import Common.Visual.Fonts.VisualiserFonts;
import Common.Utils.Index;
import _VisualDVM.ProjectData.Files.DBProjectFile;
import _VisualDVM.ProjectData.Messages.Message;
import _VisualDVM.ProjectData.SapforData.FileObjectWithMessages;
import _VisualDVM.ProjectData.SapforData.Functions.FuncCall;
import java.util.Vector;
public class Loop extends FileObjectWithMessages {
private final int lineNumAfterLoop;
private final int perfectLoop;
private final boolean hasOutGoto;
private final boolean hasPrints;
private final boolean hasNonRectIters;
//
private final int childCount;
public LoopState loopState;
public Vector<FileObjectWithMessages> children = new Vector<>();
public Loop(String[] packedLoopInfo, Index idx, DBProjectFile father_in) {
file = father_in.name;
int calls = Integer.parseInt(packedLoopInfo[idx.Inc()]);
for (int k = 0; k < calls; ++k) {
String c_name = packedLoopInfo[idx.Inc()];
int c_line = Integer.parseInt(packedLoopInfo[idx.Inc()]);
children.add(new FuncCall(father_in, c_name, c_line));
}
line = Integer.parseInt(packedLoopInfo[idx.Inc()]);
lineNumAfterLoop = Integer.parseInt(packedLoopInfo[idx.Inc()]);
perfectLoop = Integer.parseInt(packedLoopInfo[idx.Inc()]);
hasOutGoto = (Integer.parseInt(packedLoopInfo[idx.Inc()]) == 1);
hasPrints = (Integer.parseInt(packedLoopInfo[idx.Inc()]) == 1);
childCount = Integer.parseInt(packedLoopInfo[idx.Inc()]);
int state = Integer.parseInt(packedLoopInfo[idx.Inc()]);
switch (state) {
case 1:
loopState = LoopState.GoodLoop;
break;
case 2:
loopState = LoopState.BadLoop;
break;
default:
loopState = LoopState.Loop;
break;
}
hasNonRectIters = (Integer.parseInt(packedLoopInfo[idx.Inc()]) == 1);
if (hasNonRectIters)
children.add(new NonRectIter(father_in, line));
////-------------------------------------------------------------------------------
// число внешних переходов
int e_gotos = Integer.parseInt(packedLoopInfo[idx.Inc()]);
for (int k = 0; k < e_gotos; ++k) {
int c_line = Integer.parseInt(packedLoopInfo[idx.Inc()]);
children.add(new EGoto(father_in, c_line));
}
//число внутренних переходов
int i_gotos = Integer.parseInt(packedLoopInfo[idx.Inc()]);
for (int k = 0; k < i_gotos; ++k) {
int c_line = Integer.parseInt(packedLoopInfo[idx.Inc()]);
children.add(new IGoto(father_in, c_line));
}
//число операторов печати
int IO = Integer.parseInt(packedLoopInfo[idx.Inc()]);
for (int k = 0; k < IO; ++k) {
int c_line = Integer.parseInt(packedLoopInfo[idx.Inc()]);
children.add(new IO(father_in, c_line));
}
//число операторов останова (STOPб PAUSE)
int stop = Integer.parseInt(packedLoopInfo[idx.Inc()]);
for (int k = 0; k < stop; ++k) {
int c_line = Integer.parseInt(packedLoopInfo[idx.Inc()]);
children.add(new Stop(father_in, c_line));
}
//--------------------------------------------------------------------------------
for (int i = 0; i < childCount; ++i) {
Loop nextChild = new Loop(packedLoopInfo, idx, father_in);
children.add(nextChild);
}
father_in.AllLoops.put(line, this);
//нельзя использовать конструктор с параметрами из за особеностей распаковки.
CheckMessagesPresence();
}
@Override
public String TypeKey() {
return loopState.toString();
}
@Override
public String Description() {
return "цикл";
}
@Override
public boolean HasMessage(Message message) {
return (message.line >= line) && (message.line < lineNumAfterLoop);
}
@Override
public String toString() {
return super.toString() + ((perfectLoop > 1) ? (" тесная вложенность " + perfectLoop) : "");
}
@Override
public VisualiserFonts getFont() {
return loopState.getFont();
}
}

View File

@@ -0,0 +1,39 @@
package _VisualDVM.ProjectData.SapforData.Loops;
import Common.Visual.Fonts.VisualiserFonts;
import _VisualDVM.Visual.UI;
import javax.swing.text.Highlighter;
public enum LoopState {
Loop, GoodLoop, BadLoop;
public String getDescription() {
switch (this) {
case GoodLoop:
return "цикл поддается распарллеливанию";
case BadLoop:
return "в цикле обнаружены проблемы";
case Loop:
return "нет данных по циклу";
}
return "";
}
public VisualiserFonts getFont() {
switch (this) {
case GoodLoop:
return VisualiserFonts.GoodState;
case BadLoop:
return VisualiserFonts.BadState;
default:
return VisualiserFonts.UnknownState;
}
}
public Highlighter.HighlightPainter getPainter() {
switch (this) {
case GoodLoop:
return UI.GoodLoopPainter;
case BadLoop:
return UI.BadLoopPainter;
default:
return null;
}
}
}

View File

@@ -0,0 +1,17 @@
package _VisualDVM.ProjectData.SapforData.Loops;
import Common.Visual.Fonts.VisualiserFonts;
import _VisualDVM.ProjectData.Files.DBProjectFile;
import _VisualDVM.ProjectData.SapforData.FileObjectWithMessages;
public class NonRectIter extends FileObjectWithMessages {
public NonRectIter(DBProjectFile father_in, int lineNum_in) {
super(father_in, lineNum_in);
}
@Override
public String Description() {
return "непрямоугольное пространство итераций";
}
@Override
public VisualiserFonts getFont() {
return VisualiserFonts.BadState;
}
}

View File

@@ -0,0 +1,17 @@
package _VisualDVM.ProjectData.SapforData.Loops;
import Common.Visual.Fonts.VisualiserFonts;
import _VisualDVM.ProjectData.Files.DBProjectFile;
import _VisualDVM.ProjectData.SapforData.FileObjectWithMessages;
public class Stop extends FileObjectWithMessages {
public Stop(DBProjectFile father_in, int lineNum_in) {
super(father_in, lineNum_in);
}
@Override
public String Description() {
return "оператор останова";
}
@Override
public VisualiserFonts getFont() {
return VisualiserFonts.BadState;
}
}

View File

@@ -0,0 +1,12 @@
package _VisualDVM.ProjectData.SapforData.Loops.UI;
import _VisualDVM.Current;
import _VisualDVM.ProjectData.Files.UI.FileGraphTree;
public class FileLoopsTree extends FileGraphTree {
public FileLoopsTree() {
super(Current.getFile().getLoopsTree());
}
@Override
public String getBranchesName() {
return "гнёзда циклов";
}
}

View File

@@ -0,0 +1,146 @@
package _VisualDVM.ProjectData.SapforData.Regions;
import Common.Utils.CommonUtils;
import _VisualDVM.Current;
import Common.Database.Objects.DBObject;
import Common.Utils.Index;
import _VisualDVM.ProjectData.Files.DBProjectFile;
import _VisualDVM.ProjectData.SapforData.Arrays.Distribution.AlignRule;
import _VisualDVM.ProjectData.SapforData.Arrays.Distribution.DataDirective;
import _VisualDVM.ProjectData.SapforData.Arrays.ProjectArray;
import javafx.util.Pair;
import java.math.BigInteger;
import java.util.LinkedHashMap;
import java.util.Vector;
public class ParallelRegion extends DBObject {
public BigInteger regionId;
//name in program
public String originalName;
// file -> <start, end> lines
public LinkedHashMap<String, Vector<Pair<Integer, Integer>>> lines;
//ключ - адрес. меняем
public LinkedHashMap<BigInteger, ProjectArray> arrays;
//for directive creating
public DataDirective dataDirectives;
public int maxdim = 0;
public Vector<String> fragments = new Vector<>();
public int lines_count = 0;
public int loops_count = 0;
public int arrays_count = 0;
public int fd_count = 0;
public int fc_count = 0;
public ParallelRegion(String[] splited, Index idx) {
// regionId = Long.parseLong(splited[idx.Inc()]);
regionId = new BigInteger(splited[idx.Inc()]);
originalName = splited[idx.Inc()];
String[] localSplited = splited[idx.Inc()].split("\\|");
int lines_size = Integer.parseInt(localSplited[0]);
lines = new LinkedHashMap<>(lines_size);
//распаковка Lines -----------------------------------------------
//---------------------------------------------------------------
for (int i = 0; i < lines_size; ++i) {
String line_file = CommonUtils.toW(localSplited[1]);
int line_list_size = Integer.parseInt(localSplited[2]);
Vector<Pair<Integer, Integer>> current_lines = new Vector<>(line_list_size);
for (int k = 0; k < line_list_size; ++k) {
int first = Integer.parseInt(splited[idx.Inc()]);
if (first == 0) first++;
localSplited = splited[idx.Inc()].split("\\|");
int second = Integer.parseInt((localSplited[0]));
current_lines.add(new Pair<>(first, second));
fragments.add(line_file + ": " + first + "-" + second);
}
lines.put(line_file, current_lines);
}
maxdim = 0;
int arrays_size = Integer.parseInt(splited[idx.Inc()]);
arrays = new LinkedHashMap<>(arrays_size);
for (int i = 0; i < arrays_size; ++i) {
//long array_address = Long.parseLong((splited[idx.Inc()]));
BigInteger array_address = new BigInteger((splited[idx.Inc()]));
ProjectArray new_array = new ProjectArray(splited, idx, array_address);
arrays.put(array_address, new_array);
//-------------------------------------------------------
if (new_array.isTemplFlag == 1) {
maxdim = Math.max(maxdim, new_array.dimSize);
Current.getProject().templates.add(new_array);
new_array.regIDs.add(regionId);
} else if (new_array.isLoopArrayFlag != 1) arrays_count++;
}
int dataDirectives_alignRules_size = Integer.parseInt(splited[idx.Inc()]);
dataDirectives = new DataDirective();
dataDirectives.alignRules = new Vector<>(dataDirectives_alignRules_size);
for (int i = 0; i < dataDirectives_alignRules_size; ++i)
dataDirectives.alignRules.add(new AlignRule(splited, idx));
for (int i = 0; i < dataDirectives.alignRules.size(); ++i)
dataDirectives.alignRules.get(i).parent_region = this;
//--------------------------------------------------------------
lines_count = 0;
loops_count = 0;
fd_count = 0;
fc_count = 0;
for (String FKey : lines.keySet()) {
for (Pair<Integer, Integer> L : lines.get(FKey)) {
lines_count += (L.getValue() - L.getKey());
DBProjectFile f = Current.getProject().db.files.Data.get(FKey);
loops_count += f.FragmentLoopCount(L.getKey(), L.getValue());
fc_count += f.FragmentFunctionCallsCount(L.getKey(), L.getValue());
fd_count += f.FragmentFunctionDeclsCount(L.getKey(), L.getValue());
}
}
//--------------------------------------------------
}
public boolean ArrayBelongsToRegion(long id) {
return arrays.values().stream().anyMatch(array -> array.id == id);
}
public ProjectArray getArrayById(long id) {
for (ProjectArray array : arrays.values()) {
if (array.id == id) return array;
}
return null;
}
@Override
public String toString() {
return "Область распараллеливания: " + originalName;
}
@Override
public Object getPK() {
return regionId;
}
public void UpdateLoopsCount() {
loops_count = 0;
for (String FKey : lines.keySet()) {
for (Pair<Integer, Integer> L : lines.get(FKey)) {
DBProjectFile f = Current.getProject().db.files.Data.get(FKey);
loops_count += f.FragmentLoopCount(L.getKey(), L.getValue());
}
}
}
public void UpdateFunctionsCount() {
fd_count = 0;
fc_count = 0;
for (String FKey : lines.keySet()) {
for (Pair<Integer, Integer> L : lines.get(FKey)) {
DBProjectFile f = Current.getProject().db.files.Data.get(FKey);
fc_count += f.FragmentFunctionCallsCount(L.getKey(), L.getValue());
fd_count += f.FragmentFunctionDeclsCount(L.getKey(), L.getValue());
}
}
}
public void UpdateArraysCount() {
arrays_count=0;
for (String FKey : lines.keySet()) {
for (Pair<Integer, Integer> L : lines.get(FKey)) {
DBProjectFile f = Current.getProject().db.files.Data.get(FKey);
arrays_count += f.FragmentArraysCount(L.getKey(), L.getValue());
}
}
/*
if (new_array.isTemplFlag == 1) {
maxdim = Math.max(maxdim, new_array.dimSize);
Current.getProject().templates.put(new_array.address, new_array);
new_array.regIDs.add(regionId);
} else if (new_array.isLoopArrayFlag != 1) arrays_count++;
*/
}
}

View File

@@ -0,0 +1,64 @@
package _VisualDVM.ProjectData.SapforData.Regions;
import _VisualDVM.Current;
import Common.Database.Tables.DataSet;
import Common.Visual.DataSetControlForm;
import java.math.BigInteger;
import static Common.Visual.Tables.TableRenderers.RendererMultiline;
import static Common.Visual.Tables.TableRenderers.RendererTopLeft;
public class RegionsSet extends DataSet<BigInteger, ParallelRegion> {
//суррогат. нужен только для сохры столбцов. во всяком случае пока.
public RegionsSet() {
super(BigInteger.class, ParallelRegion.class);
}
@Override
public Current CurrentName() {
return Current.ParallelRegionInfo;
}
@Override
public String getSingleDescription() {
return "область распараллеливания";
}
@Override
public String getPluralDescription() {
return "области распараллеливания";
}
@Override
protected DataSetControlForm createUI() {
return new DataSetControlForm(this) {
@Override
protected void AdditionalInitColumns() {
columns.get(0).setVisible(false);
for (int i = 1; i < 7; ++i)
columns.get(i).setRenderer(RendererTopLeft);
columns.get(7).setRenderer(RendererMultiline);
}
};
}
@Override
public Object getFieldAt(ParallelRegion object, int columnIndex) {
switch (columnIndex) {
case 1:
return object.originalName;
case 2:
return object.lines_count;
case 3:
return object.arrays_count;
case 4:
return object.loops_count;
case 5:
return object.fd_count;
case 6:
return object.fc_count;
case 7:
return object.fragments;
default:
return null;
}
}
@Override
public String[] getUIColumnNames() {
return new String[]{"Имя", "Строк кода", "Массивов", "Циклов", "Объявлений процедур", "Вызовов процедур", "Фрагменты"};
}
}

View File

@@ -0,0 +1,70 @@
package _VisualDVM.ProjectData.SapforData.Regions.UI;
import _VisualDVM.Current;
import Common.Visual.Tables.StyledCellLabel;
import _VisualDVM.ProjectData.SapforData.Arrays.ProjectArray;
import javafx.util.Pair;
import javax.swing.*;
import javax.swing.event.ChangeListener;
import java.util.LinkedHashMap;
public class ArrayAlignmentBar extends JToolBar {
public ProjectArray array;
public LinkedHashMap<Integer, Pair<JSpinner, JSpinner>> dimensions = new LinkedHashMap<>();
public ArrayAlignmentBar(ProjectArray array_in) {
array = array_in;
array.bar = this;
array.init_new_ac(); //набор коефициентов.
this.setFloatable(false);
//-
StyledCellLabel label = new StyledCellLabel();
label.setOpaque(false);
label.setText(array.GetShortNameWithDimLetters() + "" + array.align_template.shortName + " [ ");
add(label);
//---
int i = 0;
for (int dim : array.ac_current.keySet()) {
if (array.ac_current.get(dim).active) {
//просто идут подряд. четные - K, нечетные B
JSpinner K = new DimensionSpinner(array.ac_current.get(dim).K);
JSpinner B = new DimensionSpinner(array.ac_current.get(dim).B);
dimensions.put(dim, new Pair<>(K, B));
add(K);
label = new StyledCellLabel();
label.setOpaque(false);
label.setText(" * " + array.ac_current.get(dim).getLetter() + " + ");
add(label);
add(B);
label = new StyledCellLabel();
label.setOpaque(false);
label.setText((i < array.ac_current.keySet().size() - 1) ? " , " : " ]");
add(label);
ChangeListener changeListener = e -> {
//инфа о связях. из списка всех объявленных массивов.
ProjectArray d_array = Current.getProject().declaratedArrays.get(array.id);
//опять же, берем инфу из объявлений!
for (ProjectArray d_link : d_array.links.values()) {
//это массивы из объявлений. прежде чем их трогать проверим а есть ли они в текущей области.
// по адресам принадлежность смотреть нельзя.
// на момент поиска массивов у них их еще нет. а вот ид совпадают.
if (Current.getParallelRegion().ArrayBelongsToRegion(d_link.id)) {
//инфа о массиве уже из области. имеющая адрес и бар.
ProjectArray r_link = Current.getParallelRegion().getArrayById(d_link.id);
Pair<JSpinner, JSpinner> pair = r_link.bar.dimensions.get(dim);
pair.getKey().setValue(K.getValue());
pair.getValue().setValue(B.getValue());
}
}
};
K.addChangeListener(changeListener);
B.addChangeListener(changeListener);
}
++i;
}
}
public void apply_changes() {
for (int dim : dimensions.keySet()) {
array.ac_new.get(dim).K = (int) dimensions.get(dim).getKey().getValue();
array.ac_new.get(dim).B = (int) dimensions.get(dim).getValue().getValue();
}
}
}

View File

@@ -0,0 +1,14 @@
package _VisualDVM.ProjectData.SapforData.Regions.UI;
import javax.swing.*;
import java.awt.*;
public class DimensionSpinner extends JSpinner {
public DimensionSpinner(int value_in) {
java.awt.Dimension p = new Dimension(40, 26);
setMinimumSize(p);
setMaximumSize(p);
setPreferredSize(p);
setModel(new SpinnerNumberModel(
value_in,
-65535, 65535, 1));
}
}

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="_VisualDVM.ProjectData.SapforData.Regions.UI.ParallelRegionFields">
<grid id="27dc6" binding="Content" layout-manager="BorderLayout" hgap="0" vgap="0">
<constraints>
<xy x="20" y="20" width="500" height="400"/>
</constraints>
<properties/>
<border type="none"/>
<children/>
</grid>
</form>

View File

@@ -0,0 +1,13 @@
package _VisualDVM.ProjectData.SapforData.Regions.UI;
import Common.Visual.Windows.Dialog.DialogFields;
import javax.swing.*;
import java.awt.*;
public class ParallelRegionFields implements DialogFields {
public JPanel Content;
// public JToolBar arraysBar;
@Override
public Component getContent() {
return Content;
}
}

View File

@@ -0,0 +1,94 @@
package _VisualDVM.ProjectData.SapforData.Variants;
import Common.Database.Objects.DBObject;
import _VisualDVM.Visual.UI;
import _VisualDVM.ProjectData.PredictorStatistic.PredictorStatistics_2021;
import _VisualDVM.ProjectData.Project.db_project_info;
import _VisualDVM.ProjectData.SapforData.Arrays.ProjectArray;
import _VisualDVM.ProjectData.SapforData.Regions.ParallelRegion;
import javafx.util.Pair;
import java.io.File;
import java.math.BigInteger;
import java.nio.file.Paths;
import java.util.LinkedHashMap;
import java.util.Vector;
public class ParallelVariant extends DBObject {
public static final long statNaN = -1;
public static final long rankNaN = 1;
public String UniqKey = "";
public int dc = 0;
public db_project_info father = null;
public PredictorStatistics_2021 stats = null;
public Vector<String> templates_description = new Vector<>();
public LinkedHashMap<Pair<BigInteger, BigInteger>, Long> key = new LinkedHashMap<>();
public ParallelVariant(db_project_info father_in, Vector<BigInteger> vector) {
father = father_in;
UniqKey = "";
dc = 0;
for (int i = 0; i < vector.size(); i += 3) {
ProjectArray template = father.getTemplateByAddress(vector.get(i));
long varID = vector.get(i + 1).longValue(); //тут вар ид. он обычный лонг.
ParallelRegion region = father.parallelRegions.get(vector.get(i + 2));
if (varID != 0)
dc++;
templates_description.add(template.GetShortNameForVariant(varID));
UniqKey += template.name + "_" + varID + "_" + region.originalName;
key.put(new Pair<>(template.address, region.regionId), varID);
}
load_stats();
}
public void load_stats() {
stats = father.db.predictorStatistics.Data.containsKey(UniqKey) ?
father.db.predictorStatistics.Data.get(UniqKey) : new PredictorStatistics_2021(UniqKey);
}
public void UpdateStats(String packed, String last_version) throws Exception {
stats.Unpack(packed);
stats.last_version = last_version;
if (stats.loaded) {
father.db.Update(stats);
} else {
father.db.Insert(stats);
stats.loaded = true;
}
}
public boolean Match(boolean distributed) {
for (Pair<BigInteger, BigInteger> p : key.keySet()) {
ProjectArray template = father.getTemplateByAddress(p.getKey());
if (!template.CheckFilterMask(key.get(p), distributed)) return false;
}
return true;
}
public String getVector() {
String res = "";
int i = 0;
for (Pair<BigInteger, BigInteger> p : key.keySet()) {
res += p.getKey() + "|" + key.get(p) + "|" + p.getValue() + ((i < key.size() - 1) ? "|" : "");
++i;
}
res = i + "|" + res;
return res;
}
public String getDescription() {
return String.join(";", templates_description);
}
@Override
public Object getPK() {
return UniqKey;
}
@Override
public void Select(boolean flag) {
super.Select(flag);
UI.getVersionsWindow().getVariantsWindow().ShowCheckedVariantsCount();
}
public File project = null;
public File restoreProject() {
project=null;
if (stats != null) {
if (stats.last_version.isEmpty()) return null;
project = Paths.get(father.Home.getAbsolutePath(), stats.last_version).toFile();
return project.exists() ? project : null;
}
return project;
}
}

View File

@@ -0,0 +1,8 @@
package _VisualDVM.ProjectData.SapforData.Variants.UI;
import Common.Visual.Tables.MaskedIntegerValueRenderer;
public class VariantRankRenderer extends MaskedIntegerValueRenderer {
@Override
public long getMask() {
return 1;
}
}

View File

@@ -0,0 +1,74 @@
package _VisualDVM.ProjectData.SapforData.Variants;
import _VisualDVM.Current;
import Common.Database.Tables.DataSet;
import Common.Visual.DataSetControlForm;
import static Common.Visual.Tables.TableRenderers.*;
public class VariantsSet extends DataSet<String, ParallelVariant> {
public VariantsSet() {
super(String.class, ParallelVariant.class);
}
@Override
public String getPluralDescription() {
return "варианты";
}
@Override
protected DataSetControlForm createUI() {
return new DataSetControlForm(this) {
@Override
public boolean hasCheckBox() {
return true;
}
@Override
protected void AdditionalInitColumns() {
columns.get(0).setVisible(false);
columns.get(2).setRenderer(RendererMultiline);
for (int i = 3; i < columns.size() - 3; ++i)
columns.get(i).setRenderer(RendererMaskedInt);
columns.get(columns.size() - 3).setRenderer(RendererVariantRank);
columns.get(columns.size() - 2).setRenderer(RendererDate);
}
};
}
@Override
public String[] getUIColumnNames() {
return new String[]{"Распределение", "PARALLEL", "REMOTE", "REDISTRIBUTE", "INTERVALS",
"PS.REMOTE", "PS.SHADOW", "PS.REDUCTION", "PS.ACROSS", "Оценка", "Дата оценки", "Версия"};
}
@Override
public Object getFieldAt(ParallelVariant object, int columnIndex) {
switch (columnIndex) {
case 2:
return object.templates_description;
case 3:
return object.stats.ParallelCount;
case 4:
return object.stats.RemoteCount;
case 5:
return object.stats.RedistributeCount;
case 6:
return object.stats.IntervalCount;
case 7:
return object.stats.PS_RemoteCount;
case 8:
return object.stats.PS_ShadowCount;
case 9:
return object.stats.PS_ReductionCount;
case 10:
return object.stats.PS_AcrossCount;
case 11:
return object.stats.Rank;
case 12:
return object.stats.getPredictionDate();
case 13:
return object.stats.last_version;
default:
return null;
}
}
@Override
public Current CurrentName() {
return Current.ParallelVariant;
}
}