app_Main.py 471 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # Modified by Marius Stanciu (2019) #
  8. # ###########################################################
  9. import urllib.request
  10. import urllib.parse
  11. import urllib.error
  12. import getopt
  13. import random
  14. import simplejson as json
  15. import shutil
  16. import lzma
  17. from datetime import datetime
  18. import time
  19. import ctypes
  20. import traceback
  21. from shapely.geometry import Point, MultiPolygon
  22. from shapely.ops import unary_union
  23. from io import StringIO
  24. from reportlab.graphics import renderPDF
  25. from reportlab.pdfgen import canvas
  26. from reportlab.lib.units import inch, mm
  27. from reportlab.lib.pagesizes import landscape, portrait
  28. from svglib.svglib import svg2rlg
  29. import gc
  30. from xml.dom.minidom import parseString as parse_xml_string
  31. from multiprocessing.connection import Listener, Client
  32. from multiprocessing import Pool
  33. import socket
  34. # ####################################################################################################################
  35. # ################################### Imports part of FlatCAM #############################################
  36. # ####################################################################################################################
  37. # Various
  38. from Common import LoudDict
  39. from Common import color_variant
  40. from Common import ExclusionAreas
  41. from Bookmark import BookmarkManager
  42. from appDatabase import ToolsDB2
  43. from vispy.gloo.util import _screenshot
  44. from vispy.io import write_png
  45. # FlatCAM defaults (preferences)
  46. from defaults import FlatCAMDefaults
  47. # FlatCAM Objects
  48. from appGUI.preferences.OptionsGroupUI import OptionsGroupUI
  49. from appGUI.preferences.PreferencesUIManager import PreferencesUIManager
  50. from appObjects.ObjectCollection import *
  51. from appObjects.FlatCAMObj import FlatCAMObj
  52. from appObjects.AppObject import AppObject
  53. # FlatCAM Parsing files
  54. from appParsers.ParseExcellon import Excellon
  55. from appParsers.ParseGerber import Gerber
  56. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  57. # FlatCAM appGUI
  58. from appGUI.PlotCanvas import *
  59. from appGUI.PlotCanvasLegacy import *
  60. from appGUI.MainGUI import *
  61. from appGUI.GUIElements import FCFileSaveDialog, message_dialog, FlatCAMSystemTray
  62. # FlatCAM Pre-processors
  63. from appPreProcessor import load_preprocessors
  64. # FlatCAM appEditors
  65. from appEditors.AppGeoEditor import AppGeoEditor
  66. from appEditors.AppExcEditor import AppExcEditor
  67. from appEditors.AppGerberEditor import AppGerberEditor
  68. from appEditors.AppTextEditor import AppTextEditor
  69. from appEditors.appGCodeEditor import AppGCodeEditor
  70. from appParsers.ParseHPGL2 import HPGL2
  71. # FlatCAM Workers
  72. from appProcess import *
  73. from appWorkerStack import WorkerStack
  74. # FlatCAM Tools
  75. from appTools import *
  76. # FlatCAM Translation
  77. import gettext
  78. import appTranslation as fcTranslate
  79. import builtins
  80. if sys.platform == 'win32':
  81. import winreg
  82. from win32comext.shell import shell, shellcon
  83. fcTranslate.apply_language('strings')
  84. if '_' not in builtins.__dict__:
  85. _ = gettext.gettext
  86. class App(QtCore.QObject):
  87. """
  88. The main application class. The constructor starts the GUI and all other classes used by the program.
  89. """
  90. # ###############################################################################################################
  91. # ########################################## App ################################################################
  92. # ###############################################################################################################
  93. # ###############################################################################################################
  94. # ######################################### LOGGING #############################################################
  95. # ###############################################################################################################
  96. log = logging.getLogger('base')
  97. log.setLevel(logging.DEBUG)
  98. # log.setLevel(logging.WARNING)
  99. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  100. handler = logging.StreamHandler()
  101. handler.setFormatter(formatter)
  102. log.addHandler(handler)
  103. # ###############################################################################################################
  104. # #################################### Get Cmd Line Options #####################################################
  105. # ###############################################################################################################
  106. cmd_line_shellfile = ''
  107. cmd_line_shellvar = ''
  108. cmd_line_headless = None
  109. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  110. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  111. "FlatCam.py --headless=1"
  112. try:
  113. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  114. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  115. "shellvar=",
  116. "headless=",
  117. "multiprocessing-fork="])
  118. except getopt.GetoptError:
  119. print(cmd_line_help)
  120. sys.exit(2)
  121. for opt, arg in cmd_line_options:
  122. if opt == '-h':
  123. print(cmd_line_help)
  124. sys.exit()
  125. elif opt == '--shellfile':
  126. cmd_line_shellfile = arg
  127. elif opt == '--shellvar':
  128. cmd_line_shellvar = arg
  129. elif opt == '--headless':
  130. try:
  131. cmd_line_headless = eval(arg)
  132. except NameError:
  133. pass
  134. # ###############################################################################################################
  135. # ################################### Version and VERSION DATE ##################################################
  136. # ###############################################################################################################
  137. version = "Unstable Version"
  138. # version = 8.994
  139. version_date = "2020/07/05"
  140. beta = True
  141. engine = '3D'
  142. # current date now
  143. date = str(datetime.today()).rpartition('.')[0]
  144. date = ''.join(c for c in date if c not in ':-')
  145. date = date.replace(' ', '_')
  146. # ###############################################################################################################
  147. # ############################################ URLS's ###########################################################
  148. # ###############################################################################################################
  149. # URL for update checks and statistics
  150. version_url = "http://flatcam.org/version"
  151. # App URL
  152. app_url = "http://flatcam.org"
  153. # Manual URL
  154. manual_url = "http://flatcam.org/manual/index.html"
  155. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  156. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  157. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  158. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  159. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  160. # this variable will hold the project status
  161. # if True it will mean that the project was modified and not saved
  162. should_we_save = False
  163. # flag is True if saving action has been triggered
  164. save_in_progress = False
  165. # ###############################################################################################################
  166. # ####################################### APP Signals ######################################################
  167. # ###############################################################################################################
  168. # Inform the user
  169. # Handled by: App.info() --> Print on the status bar
  170. inform = QtCore.pyqtSignal([str], [str, bool])
  171. # Handled by: App.info_shell() --> Print on the shell
  172. inform_shell = QtCore.pyqtSignal(str)
  173. app_quit = QtCore.pyqtSignal()
  174. # General purpose background task
  175. worker_task = QtCore.pyqtSignal(dict)
  176. # File opened
  177. # Handled by:
  178. # * register_folder()
  179. # * register_recent()
  180. # Note: Setting the parameters to unicode does not seem
  181. # to have an effect. Then are received as Qstring
  182. # anyway.
  183. # File type and filename
  184. file_opened = QtCore.pyqtSignal(str, str)
  185. # File type and filename
  186. file_saved = QtCore.pyqtSignal(str, str)
  187. # Percentage of progress
  188. progress = QtCore.pyqtSignal(int)
  189. # Emitted when a new object has been added or deleted from/to the collection
  190. object_status_changed = QtCore.pyqtSignal(object, str, str)
  191. message = QtCore.pyqtSignal(str, str, str)
  192. # Emmited when shell command is finished(one command only)
  193. shell_command_finished = QtCore.pyqtSignal(object)
  194. # Emitted when multiprocess pool has been recreated
  195. pool_recreated = QtCore.pyqtSignal(object)
  196. # Emitted when an unhandled exception happens
  197. # in the worker task.
  198. thread_exception = QtCore.pyqtSignal(object)
  199. # used to signal that there are arguments for the app
  200. args_at_startup = QtCore.pyqtSignal(list)
  201. # a reusable signal to replot a list of objects
  202. # should be disconnected after use so it can be reused
  203. replot_signal = pyqtSignal(list)
  204. # signal emitted when jumping
  205. jump_signal = pyqtSignal(tuple)
  206. # signal emitted when jumping
  207. locate_signal = pyqtSignal(tuple, str)
  208. # close app signal
  209. close_app_signal = pyqtSignal()
  210. # will perform the cleanup operation after a Graceful Exit
  211. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  212. # graphic residues behind
  213. cleanup = pyqtSignal()
  214. def __init__(self, user_defaults=True):
  215. """
  216. Starts the application.
  217. :return: app
  218. :rtype: App
  219. """
  220. super().__init__()
  221. App.log.info("FlatCAM Starting...")
  222. # ############################################################################################################
  223. # ################# Setup the listening thread for another instance launching with args ######################
  224. # ############################################################################################################
  225. if sys.platform == 'win32' or sys.platform == 'linux':
  226. # make sure the thread is stored by using a self. otherwise it's garbage collected
  227. self.listen_th = QtCore.QThread()
  228. self.listen_th.start(priority=QtCore.QThread.LowestPriority)
  229. self.new_launch = ArgsThread()
  230. self.new_launch.open_signal[list].connect(self.on_startup_args)
  231. self.new_launch.moveToThread(self.listen_th)
  232. self.new_launch.start.emit()
  233. # ############################################################################################################
  234. # ########################################## OS-specific #####################################################
  235. # ############################################################################################################
  236. portable = False
  237. # Folder for user settings.
  238. if sys.platform == 'win32':
  239. if platform.architecture()[0] == '32bit':
  240. App.log.debug("Win32!")
  241. else:
  242. App.log.debug("Win64!")
  243. # #######################################################################################################
  244. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  245. # #######################################################################################################
  246. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  247. try:
  248. with open(config_file, 'r'):
  249. pass
  250. except FileNotFoundError:
  251. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  252. try:
  253. with open(config_file, 'r') as f:
  254. try:
  255. for line in f:
  256. param = str(line).replace('\n', '').rpartition('=')
  257. if param[0] == 'portable':
  258. try:
  259. portable = eval(param[2])
  260. except NameError:
  261. portable = False
  262. if param[0] == 'headless':
  263. if param[2].lower() == 'true':
  264. self.cmd_line_headless = 1
  265. else:
  266. self.cmd_line_headless = None
  267. except Exception as e:
  268. log.debug('App.__init__() -->%s' % str(e))
  269. return
  270. except FileNotFoundError as e:
  271. log.debug(str(e))
  272. pass
  273. if portable is False:
  274. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  275. else:
  276. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  277. self.os = 'windows'
  278. else: # Linux/Unix/MacOS
  279. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  280. self.os = 'unix'
  281. # ############################################################################################################
  282. # ################################# Setup folders and files ##################################################
  283. # ############################################################################################################
  284. if not os.path.exists(self.data_path):
  285. os.makedirs(self.data_path)
  286. App.log.debug('Created data folder: ' + self.data_path)
  287. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  288. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  289. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  290. if not os.path.exists(self.preprocessorpaths):
  291. os.makedirs(self.preprocessorpaths)
  292. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  293. # create tools_db.FlatDB file if there is none
  294. try:
  295. f = open(self.data_path + '/tools_db.FlatDB')
  296. f.close()
  297. except IOError:
  298. App.log.debug('Creating empty tools_db.FlatDB')
  299. f = open(self.data_path + '/tools_db.FlatDB', 'w')
  300. json.dump({}, f)
  301. f.close()
  302. # create current_defaults.FlatConfig file if there is none
  303. try:
  304. f = open(self.data_path + '/current_defaults.FlatConfig')
  305. f.close()
  306. except IOError:
  307. App.log.debug('Creating empty current_defaults.FlatConfig')
  308. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  309. json.dump({}, f)
  310. f.close()
  311. # the factory defaults are written only once at the first launch of the application after installation
  312. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"), self.version)
  313. # create a recent files json file if there is none
  314. try:
  315. f = open(self.data_path + '/recent.json')
  316. f.close()
  317. except IOError:
  318. App.log.debug('Creating empty recent.json')
  319. f = open(self.data_path + '/recent.json', 'w')
  320. json.dump([], f)
  321. f.close()
  322. # create a recent projects json file if there is none
  323. try:
  324. fp = open(self.data_path + '/recent_projects.json')
  325. fp.close()
  326. except IOError:
  327. App.log.debug('Creating empty recent_projects.json')
  328. fp = open(self.data_path + '/recent_projects.json', 'w')
  329. json.dump([], fp)
  330. fp.close()
  331. # Application directory. CHDIR to it. Otherwise, trying to load GUI icons will fail as their path is relative.
  332. # This will fail under cx_freeze ...
  333. self.app_home = os.path.dirname(os.path.realpath(__file__))
  334. log.debug("Application path is " + self.app_home)
  335. log.debug("Started in " + os.getcwd())
  336. # cx_freeze workaround
  337. if os.path.isfile(self.app_home):
  338. self.app_home = os.path.dirname(self.app_home)
  339. os.chdir(self.app_home)
  340. # ############################################################################################################
  341. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  342. # ############################################################################################################
  343. self.defaults = FlatCAMDefaults(beta=self.beta, version=self.version)
  344. self.defaults["root_folder_path"] = self.app_home
  345. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  346. if user_defaults:
  347. self.defaults.load(filename=current_defaults_path)
  348. if self.defaults['units'] == 'MM':
  349. self.decimals = int(self.defaults['decimals_metric'])
  350. else:
  351. self.decimals = int(self.defaults['decimals_inch'])
  352. if self.defaults["global_gray_icons"] is False:
  353. self.resource_location = 'assets/resources'
  354. else:
  355. self.resource_location = 'assets/resources/dark_resources'
  356. self.current_units = self.defaults['units']
  357. # ###########################################################################################################
  358. # #################################### SETUP OBJECT CLASSES #################################################
  359. # ###########################################################################################################
  360. self.setup_obj_classes()
  361. # ###########################################################################################################
  362. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  363. # ###########################################################################################################
  364. self.pool = Pool()
  365. # ###########################################################################################################
  366. # ###################################### Clear GUI Settings - once at first start ###########################
  367. # ###########################################################################################################
  368. if self.defaults["first_run"] is True:
  369. # on first run clear the previous QSettings, therefore clearing the GUI settings
  370. qsettings = QSettings("Open Source", "FlatCAM")
  371. for key in qsettings.allKeys():
  372. qsettings.remove(key)
  373. # This will write the setting to the platform specific storage.
  374. del qsettings
  375. # ###########################################################################################################
  376. # ###################################### Setting the Splash Screen ##########################################
  377. # ###########################################################################################################
  378. splash_settings = QSettings("Open Source", "FlatCAM")
  379. if splash_settings.contains("splash_screen"):
  380. show_splash = splash_settings.value("splash_screen")
  381. else:
  382. splash_settings.setValue('splash_screen', 1)
  383. # This will write the setting to the platform specific storage.
  384. del splash_settings
  385. show_splash = 1
  386. if show_splash and self.cmd_line_headless != 1:
  387. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  388. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  389. # self.splash.setMask(splash_pix.mask())
  390. # move splashscreen to the current monitor
  391. desktop = QtWidgets.QApplication.desktop()
  392. screen = desktop.screenNumber(QtGui.QCursor.pos())
  393. current_screen_center = desktop.availableGeometry(screen).center()
  394. self.splash.move(current_screen_center - self.splash.rect().center())
  395. self.splash.show()
  396. self.splash.showMessage(_("FlatCAM is initializing ..."),
  397. alignment=Qt.AlignBottom | Qt.AlignLeft,
  398. color=QtGui.QColor("gray"))
  399. else:
  400. show_splash = 0
  401. # ###########################################################################################################
  402. # ######################################### Initialize GUI ##################################################
  403. # ###########################################################################################################
  404. # FlatCAM colors used in plotting
  405. self.FC_light_green = '#BBF268BF'
  406. self.FC_dark_green = '#006E20BF'
  407. self.FC_light_blue = '#a5a5ffbf'
  408. self.FC_dark_blue = '#0000ffbf'
  409. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  410. if theme_settings.contains("theme"):
  411. theme = theme_settings.value('theme', type=str)
  412. else:
  413. theme = 'white'
  414. if self.defaults["global_cursor_color_enabled"]:
  415. self.cursor_color_3D = self.defaults["global_cursor_color"]
  416. else:
  417. if theme == 'white':
  418. self.cursor_color_3D = 'black'
  419. else:
  420. self.cursor_color_3D = 'gray'
  421. # update the defaults dict with the setting in QSetting
  422. self.defaults['global_theme'] = theme
  423. self.ui = MainGUI(self)
  424. # set FlatCAM units in the Status bar
  425. self.set_screen_units(self.defaults['units'])
  426. # ###########################################################################################################
  427. # ########################################### AUTOSAVE SETUP ################################################
  428. # ###########################################################################################################
  429. self.block_autosave = False
  430. self.autosave_timer = QtCore.QTimer(self)
  431. self.save_project_auto_update()
  432. self.autosave_timer.timeout.connect(self.save_project_auto)
  433. # ###########################################################################################################
  434. # #################################### LOAD PREPROCESSORS ###################################################
  435. # ###########################################################################################################
  436. # ----------------------------------------- WARNING --------------------------------------------------------
  437. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  438. # That's because the number of preprocessors can vary and here the comboboxes are populated
  439. # -----------------------------------------------------------------------------------------------------------
  440. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  441. # the preprocessor file
  442. self.preprocessors = load_preprocessors(self)
  443. # make sure that always the 'default' preprocessor is the first item in the dictionary
  444. if 'default' in self.preprocessors.keys():
  445. new_ppp_dict = {}
  446. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  447. default_pp = self.preprocessors.pop('default')
  448. new_ppp_dict['default'] = default_pp
  449. # then add the rest of the keys
  450. for name, val_class in self.preprocessors.items():
  451. new_ppp_dict[name] = val_class
  452. # and now put back the ordered dict with 'default' key first
  453. self.preprocessors = new_ppp_dict
  454. # populate the Preprocessor ComboBoxes in the PREFERENCES
  455. for name in list(self.preprocessors.keys()):
  456. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  457. if name.partition('_')[0] == 'Paste':
  458. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  459. continue
  460. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  461. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  462. if name == 'hpgl':
  463. continue
  464. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.addItem(name)
  465. # add ToolTips for the Preprocessor ComboBoxes in Preferences
  466. for it in range(self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.count()):
  467. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.setItemData(
  468. it, self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.itemText(it), QtCore.Qt.ToolTipRole)
  469. for it in range(self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.count()):
  470. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.setItemData(
  471. it, self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.itemText(it),
  472. QtCore.Qt.ToolTipRole)
  473. for it in range(self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.count()):
  474. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.setItemData(
  475. it, self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.itemText(it),
  476. QtCore.Qt.ToolTipRole)
  477. # ###########################################################################################################
  478. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  479. # ###########################################################################################################
  480. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  481. inform=self.inform)
  482. self.preferencesUiManager.defaults_write_form()
  483. # When the self.defaults dictionary changes will update the Preferences GUI forms
  484. self.defaults.set_change_callback(self.on_defaults_dict_change)
  485. # ###########################################################################################################
  486. # ##################################### FIRST RUN SECTION ###################################################
  487. # ################################ It's done only once after install #####################################
  488. # ###########################################################################################################
  489. if self.defaults["first_run"] is True:
  490. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'minimal'
  491. initial_lay = 'minimal'
  492. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  493. # Set the combobox in Preferences to the current layout
  494. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  495. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  496. # after the first run, this object should be False
  497. self.defaults["first_run"] = False
  498. self.preferencesUiManager.save_defaults(silent=True)
  499. # ###########################################################################################################
  500. # ############################################ Data #########################################################
  501. # ###########################################################################################################
  502. self.recent = []
  503. self.recent_projects = []
  504. self.clipboard = QtWidgets.QApplication.clipboard()
  505. self.project_filename = None
  506. self.toggle_units_ignore = False
  507. self.main_thread = QtWidgets.QApplication.instance().thread()
  508. # ###########################################################################################################
  509. # ########################################## LOAD LANGUAGES ################################################
  510. # ###########################################################################################################
  511. self.languages = fcTranslate.load_languages()
  512. for name in sorted(self.languages.values()):
  513. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  514. # ###########################################################################################################
  515. # ####################################### APPLY APP LANGUAGE ################################################
  516. # ###########################################################################################################
  517. ret_val = fcTranslate.apply_language('strings')
  518. if ret_val == "no language":
  519. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  520. log.debug("Could not find the Language files. The App strings are missing.")
  521. else:
  522. # make the current language the current selection on the language combobox
  523. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  524. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  525. # ###########################################################################################################
  526. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  527. # ###########################################################################################################
  528. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  529. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  530. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  531. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  532. self.defaults.propagate_defaults()
  533. # ###########################################################################################################
  534. # ######################################## UPDATE THE OPTIONS ###############################################
  535. # ###########################################################################################################
  536. self.options = LoudDict()
  537. # -----------------------------------------------------------------------------------------------------------
  538. # Update the self.options from the self.defaults
  539. # The self.defaults holds the application defaults while the self.options holds the object defaults
  540. # -----------------------------------------------------------------------------------------------------------
  541. # Copy app defaults to project options
  542. for def_key, def_val in self.defaults.items():
  543. self.options[def_key] = deepcopy(def_val)
  544. self.preferencesUiManager.show_preferences_gui()
  545. # ### End of Data ####
  546. # ###########################################################################################################
  547. # #################################### SETUP OBJECT COLLECTION ##############################################
  548. # ###########################################################################################################
  549. self.collection = ObjectCollection(app=self)
  550. self.ui.project_tab_layout.addWidget(self.collection.view)
  551. self.app_obj = AppObject(app=self)
  552. # ### Adjust tabs width ## ##
  553. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  554. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  555. self.collection.view.setMinimumWidth(290)
  556. self.log.debug("Finished creating Object Collection.")
  557. # ###########################################################################################################
  558. # ######################################## SETUP Plot Area ##################################################
  559. # ###########################################################################################################
  560. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  561. if self.defaults["global_graphic_engine"] == '3D':
  562. self.is_legacy = False
  563. else:
  564. self.is_legacy = True
  565. # Event signals disconnect id holders
  566. self.mp = None
  567. self.mm = None
  568. self.mr = None
  569. self.mdc = None
  570. self.mp_zc = None
  571. self.kp = None
  572. # Matplotlib axis
  573. self.axes = None
  574. if show_splash:
  575. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  576. "Canvas initialization started."),
  577. alignment=Qt.AlignBottom | Qt.AlignLeft,
  578. color=QtGui.QColor("gray"))
  579. start_plot_time = time.time() # debug
  580. self.plotcanvas = None
  581. self.app_cursor = None
  582. self.hover_shapes = None
  583. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  584. # setup the PlotCanvas
  585. self.on_plotcanvas_setup()
  586. end_plot_time = time.time()
  587. self.used_time = end_plot_time - start_plot_time
  588. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  589. if show_splash:
  590. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  591. "Canvas initialization started.\n"
  592. "Canvas initialization finished in"), '%.2f' % self.used_time),
  593. alignment=Qt.AlignBottom | Qt.AlignLeft,
  594. color=QtGui.QColor("gray"))
  595. self.ui.splitter.setStretchFactor(1, 2)
  596. # ###########################################################################################################
  597. # ############################################### SYS TRAY ##################################################
  598. # ###########################################################################################################
  599. if self.defaults["global_systray_icon"]:
  600. self.parent_w = QtWidgets.QWidget()
  601. if self.cmd_line_headless == 1:
  602. self.trayIcon = FlatCAMSystemTray(app=self,
  603. icon=QtGui.QIcon(self.resource_location +
  604. '/flatcam_icon32_green.png'),
  605. headless=True,
  606. parent=self.parent_w)
  607. else:
  608. self.trayIcon = FlatCAMSystemTray(app=self,
  609. icon=QtGui.QIcon(self.resource_location +
  610. '/flatcam_icon32_green.png'),
  611. parent=self.parent_w)
  612. # ###########################################################################################################
  613. # ############################################### Worker SETUP ##############################################
  614. # ###########################################################################################################
  615. if self.defaults["global_worker_number"]:
  616. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  617. else:
  618. self.workers = WorkerStack(workers_number=2)
  619. self.worker_task.connect(self.workers.add_task)
  620. self.log.debug("Finished creating Workers crew.")
  621. # ###########################################################################################################
  622. # ############################################# Activity Monitor ###########################################
  623. # ###########################################################################################################
  624. # self.activity_view = FlatCAMActivityView(app=self)
  625. # self.ui.infobar.addWidget(self.activity_view)
  626. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  627. # ###########################################################################################################
  628. # ############################################# Signal handling #############################################
  629. # ###########################################################################################################
  630. # ########################################## Custom signals ################################################
  631. # signal for displaying messages in status bar
  632. self.inform[str].connect(self.info)
  633. self.inform[str, bool].connect(self.info)
  634. # signal for displaying messages in the shell
  635. self.inform_shell.connect(self.info_shell)
  636. # signal to be called when the app is quiting
  637. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  638. self.message.connect(lambda: message_dialog(parent=self.ui))
  639. # self.progress.connect(self.set_progress_bar)
  640. # signals emitted when file state change
  641. self.file_opened.connect(self.register_recent)
  642. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  643. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  644. # ########################################## Standard signals ###############################################
  645. # ### Menu
  646. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  647. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  648. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  649. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  650. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  651. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  652. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  653. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  654. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  655. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  656. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  657. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  658. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  659. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  660. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  661. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  662. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  663. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  664. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  665. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  666. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  667. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  668. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  669. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  670. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  671. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  672. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  673. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  674. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  675. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  676. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  677. self.ui.menufile_exit.triggered.connect(self.final_save)
  678. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  679. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  680. self.ui.menuedit_join2geo.triggered.connect(self.on_edit_join)
  681. self.ui.menuedit_join_exc2exc.triggered.connect(self.on_edit_join_exc)
  682. self.ui.menuedit_join_grb2grb.triggered.connect(self.on_edit_join_grb)
  683. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  684. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  685. self.ui.menueditdelete.triggered.connect(self.on_delete)
  686. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  687. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  688. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  689. self.ui.menueditconvert_any2excellon.triggered.connect(self.convert_any2excellon)
  690. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  691. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  692. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  693. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  694. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  695. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  696. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  697. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  698. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  699. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  700. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  701. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  702. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  703. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  704. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  705. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  706. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  707. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  708. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  709. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  710. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  711. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  712. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  713. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  714. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  715. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  716. self.ui.menuview_replot.triggered.connect(self.plot_all)
  717. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  718. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  719. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  720. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  721. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  722. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  723. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  724. self.ui.menuview_toggle_grid_lines.triggered.connect(self.plotcanvas.on_toggle_grid_lines)
  725. self.ui.menuview_toggle_axis.triggered.connect(self.plotcanvas.on_toggle_axis)
  726. self.ui.menuview_toggle_hud.triggered.connect(self.plotcanvas.on_toggle_hud)
  727. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  728. self.ui.menuhelp_about.triggered.connect(self.on_about)
  729. self.ui.menuhelp_readme.triggered.connect(self.on_readme)
  730. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  731. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  732. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  733. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  734. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  735. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  736. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  737. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  738. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  739. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  740. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  741. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  742. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  743. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  744. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  745. # ToolBar signals
  746. self.connect_toolbar_signals(ui=self.ui)
  747. # Context Menu
  748. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  749. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  750. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  751. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  752. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  753. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  754. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  755. self.ui.clearplot.triggered.connect(self.clear_plots)
  756. self.ui.replot.triggered.connect(self.plot_all)
  757. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  758. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  759. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  760. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  761. self.ui.popmenu_move.triggered.connect(self.obj_move)
  762. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  763. # Project Context Menu -> Color Setting
  764. for act in self.ui.menuprojectcolor.actions():
  765. act.triggered.connect(self.on_set_color_action_triggered)
  766. # ###########################################################################################################
  767. # #################################### GUI PREFERENCES SIGNALS ##############################################
  768. # ###########################################################################################################
  769. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  770. lambda: self.on_toggle_units(no_pref=False))
  771. # ##################################### Workspace Setting Signals ###########################################
  772. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  773. self.on_workspace_modified)
  774. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  775. self.on_workspace_modified
  776. )
  777. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  778. # ###########################################################################################################
  779. # ######################################## GUI SETTINGS SIGNALS #############################################
  780. # ###########################################################################################################
  781. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  782. # ######################################## Tools related signals ############################################
  783. # portability changed signal
  784. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  785. # Object list
  786. self.object_status_changed.connect(self.collection.on_collection_updated)
  787. # when there are arguments at application startup this get launched
  788. self.args_at_startup[list].connect(self.on_startup_args)
  789. # ###########################################################################################################
  790. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  791. # ###########################################################################################################
  792. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  793. lambda: self.restore_extensions(ext_type='excellon'))
  794. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  795. lambda: self.restore_extensions(ext_type='gcode'))
  796. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  797. lambda: self.restore_extensions(ext_type='gerber'))
  798. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  799. lambda: self.delete_all_extensions(ext_type='excellon'))
  800. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  801. lambda: self.delete_all_extensions(ext_type='gcode'))
  802. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  803. lambda: self.delete_all_extensions(ext_type='gerber'))
  804. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  805. lambda: self.add_extension(ext_type='excellon'))
  806. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  807. lambda: self.add_extension(ext_type='gcode'))
  808. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  809. lambda: self.add_extension(ext_type='gerber'))
  810. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  811. lambda: self.del_extension(ext_type='excellon'))
  812. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  813. lambda: self.del_extension(ext_type='gcode'))
  814. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  815. lambda: self.del_extension(ext_type='gerber'))
  816. # connect the 'Apply' buttons from the Preferences/File Associations
  817. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  818. lambda: self.on_register_files(obj_type='excellon'))
  819. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  820. lambda: self.on_register_files(obj_type='gcode'))
  821. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  822. lambda: self.on_register_files(obj_type='gerber'))
  823. # ###########################################################################################################
  824. # ########################################### KEYWORDS SIGNALS ##############################################
  825. # ###########################################################################################################
  826. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  827. lambda: self.restore_extensions(ext_type='keyword'))
  828. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  829. lambda: self.delete_all_extensions(ext_type='keyword'))
  830. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  831. lambda: self.add_extension(ext_type='keyword'))
  832. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  833. lambda: self.del_extension(ext_type='keyword'))
  834. # ###########################################################################################################
  835. # ########################################### GUI SIGNALS ###################################################
  836. # ###########################################################################################################
  837. self.ui.hud_label.clicked.connect(self.plotcanvas.on_toggle_hud)
  838. self.ui.axis_status_label.clicked.connect(self.plotcanvas.on_toggle_axis)
  839. self.ui.pref_status_label.clicked.connect(self.on_toggle_preferences)
  840. # ###########################################################################################################
  841. # ####################################### VARIOUS SIGNALS ###################################################
  842. # ###########################################################################################################
  843. # connect the abort_all_tasks related slots to the related signals
  844. self.proc_container.idle_flag.connect(self.app_is_idle)
  845. # signal emitted when a tab is closed in the Plot Area
  846. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  847. # signal to close the application
  848. self.close_app_signal.connect(self.kill_app)
  849. # ################################# FINISHED CONNECTING SIGNALS #############################################
  850. # ###########################################################################################################
  851. # ###########################################################################################################
  852. # ###########################################################################################################
  853. self.log.debug("Finished connecting Signals.")
  854. # ###########################################################################################################
  855. # ########################################## Other setups ###################################################
  856. # ###########################################################################################################
  857. # to use for tools like Distance tool who depends on the event sources who are changed inside the appEditors
  858. # depending on from where those tools are called different actions can be done
  859. self.call_source = 'app'
  860. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  861. self.tool_tab_locked = False
  862. # decide if to show or hide the Notebook side of the screen at startup
  863. if self.defaults["global_project_at_startup"] is True:
  864. self.ui.splitter.setSizes([1, 1])
  865. else:
  866. self.ui.splitter.setSizes([0, 1])
  867. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  868. self.setup_component_editor()
  869. # ###########################################################################################################
  870. # ####################################### Auto-complete KEYWORDS ############################################
  871. # ###########################################################################################################
  872. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  873. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  874. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  875. 'export_exc',
  876. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  877. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  878. 'interiors', 'isolate', 'join_excellon',
  879. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  880. 'mirror', 'ncc',
  881. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  882. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  883. 'options', 'origin',
  884. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  885. 'save', 'save_project',
  886. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  887. 'skew', 'subtract_poly', 'subtract_rectangle',
  888. 'version', 'write_gcode'
  889. ]
  890. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  891. 'Paste_1',
  892. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  893. 'Toolchange_manual', 'True', 'Users',
  894. 'all', 'auto', 'axis',
  895. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  896. 'contour', 'default',
  897. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  898. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  899. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  900. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  901. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  902. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  903. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  904. 'spacing_columns',
  905. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  906. 'toolchange_xy', 'toolchangez', 'travelz',
  907. 'tooldia', 'use_threads', 'value',
  908. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  909. ]
  910. self.tcl_keywords = [
  911. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  912. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  913. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  914. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  915. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  916. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  917. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  918. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  919. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  920. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  921. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  922. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  923. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  924. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  925. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  926. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  927. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  928. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  929. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  930. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  931. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  932. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  933. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  934. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  935. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  936. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  937. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  938. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  939. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  940. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  941. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  942. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  943. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  944. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  945. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  946. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  947. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  948. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  949. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  950. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  951. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  952. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  953. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  954. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  955. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  956. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  957. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  958. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  959. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  960. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  961. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  962. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  963. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  964. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  965. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  966. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  967. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  968. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  969. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  970. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  971. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  972. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  973. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  974. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  975. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  976. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  977. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  978. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  979. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  980. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  981. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  982. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  983. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  984. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  985. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  986. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  987. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  988. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  989. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  990. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  991. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  992. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  993. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  994. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  995. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  996. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  997. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  998. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  999. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1000. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1001. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1002. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1003. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1004. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1005. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1006. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1007. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1008. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1009. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1010. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1011. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1012. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1013. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1014. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1015. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1016. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1017. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1018. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1019. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1020. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1021. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1022. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1023. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1024. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1025. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1026. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1027. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1028. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1029. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1030. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1031. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1032. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1033. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1034. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1035. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1036. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1037. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1038. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1039. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1040. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1041. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1042. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1043. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1044. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1045. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1046. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1047. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1048. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1049. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1050. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1051. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1052. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1053. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1054. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1055. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1056. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1057. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1058. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1059. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1060. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1061. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1062. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1063. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1064. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1065. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1066. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1067. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1068. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1069. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1070. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1071. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1072. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1073. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1074. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1075. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1076. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1077. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1078. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1079. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1080. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1081. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1082. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1083. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1084. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1085. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1086. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1087. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1088. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1089. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1090. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1091. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1092. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1093. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1094. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1095. ]
  1096. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1097. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1098. # ###########################################################################################################
  1099. # ########################################## Tools and Plugins ##############################################
  1100. # ###########################################################################################################
  1101. self.shell = None
  1102. self.dblsidedtool = None
  1103. self.distance_tool = None
  1104. self.distance_min_tool = None
  1105. self.panelize_tool = None
  1106. self.film_tool = None
  1107. self.paste_tool = None
  1108. self.calculator_tool = None
  1109. self.rules_tool = None
  1110. self.sub_tool = None
  1111. self.move_tool = None
  1112. self.cutout_tool = None
  1113. self.ncclear_tool = None
  1114. self.paint_tool = None
  1115. self.isolation_tool = None
  1116. self.drilling_tool = None
  1117. self.optimal_tool = None
  1118. self.transform_tool = None
  1119. self.properties_tool = None
  1120. self.pdf_tool = None
  1121. self.image_tool = None
  1122. self.pcb_wizard_tool = None
  1123. self.cal_exc_tool = None
  1124. self.qrcode_tool = None
  1125. self.copper_thieving_tool = None
  1126. self.fiducial_tool = None
  1127. self.edrills_tool = None
  1128. self.align_objects_tool = None
  1129. self.punch_tool = None
  1130. self.invert_tool = None
  1131. self.corners_tool = None
  1132. self.etch_tool = None
  1133. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1134. try:
  1135. self.install_tools()
  1136. except AttributeError as e:
  1137. log.debug("App.__init__() install_tools() --> %s" % str(e))
  1138. # ###########################################################################################################
  1139. # ############################################ SETUP RECENT ITEMS ###########################################
  1140. # ###########################################################################################################
  1141. self.setup_recent_items()
  1142. # ###########################################################################################################
  1143. # ######################################### BookMarks Manager ###############################################
  1144. # ###########################################################################################################
  1145. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1146. self.install_bookmarks()
  1147. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1148. # ###########################################################################################################
  1149. # ########################################### Tools Database ################################################
  1150. # ###########################################################################################################
  1151. self.tools_db_tab = None
  1152. # ### System Font Parsing ###
  1153. # self.f_parse = ParseFont(self)
  1154. # self.parse_system_fonts()
  1155. # ###########################################################################################################
  1156. # ############################################## Shell SETUP ################################################
  1157. # ###########################################################################################################
  1158. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1159. if self.defaults["global_shell_at_startup"]:
  1160. self.ui.shell_dock.show()
  1161. else:
  1162. self.ui.shell_dock.hide()
  1163. # ###########################################################################################################
  1164. # ######################################### Check for updates ###############################################
  1165. # ###########################################################################################################
  1166. # Separate thread (Not worker)
  1167. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1168. if (self.beta is False or self.beta is None) and \
  1169. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1170. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1171. # self.thr2 = QtCore.QThread()
  1172. self.worker_task.emit({'fcn': self.version_check,
  1173. 'params': []})
  1174. # self.thr2.start(QtCore.QThread.LowPriority)
  1175. # ###########################################################################################################
  1176. # ##################################### Register files with FlatCAM; #######################################
  1177. # ################################### It works only for Windows for now ####################################
  1178. # ###########################################################################################################
  1179. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1180. self.on_register_files()
  1181. # ###########################################################################################################
  1182. # ######################################## Variables for global usage #######################################
  1183. # ###########################################################################################################
  1184. # hold the App units
  1185. self.units = 'MM'
  1186. # coordinates for relative position display
  1187. self.rel_point1 = (0, 0)
  1188. self.rel_point2 = (0, 0)
  1189. # variable to store coordinates
  1190. self.pos = (0, 0)
  1191. self.pos_canvas = (0, 0)
  1192. self.pos_jump = (0, 0)
  1193. # variable to store mouse coordinates
  1194. self.mouse = [0, 0]
  1195. # variable to store the delta positions on cavnas
  1196. self.dx = 0
  1197. self.dy = 0
  1198. # decide if we have a double click or single click
  1199. self.doubleclick = False
  1200. # store here the is_dragging value
  1201. self.event_is_dragging = False
  1202. # variable to store if a command is active (then the var is not None) and which one it is
  1203. self.command_active = None
  1204. # variable to store the status of moving selection action
  1205. # None value means that it's not an selection action
  1206. # True value = a selection from left to right
  1207. # False value = a selection from right to left
  1208. self.selection_type = None
  1209. # List to store the objects that are currently loaded in FlatCAM
  1210. # This list is updated on each object creation or object delete
  1211. self.all_objects_list = []
  1212. self.objects_under_the_click_list = []
  1213. # List to store the objects that are selected
  1214. self.sel_objects_list = []
  1215. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1216. self.key_modifiers = None
  1217. # Variable to store the status of the code editor
  1218. self.toggle_codeeditor = False
  1219. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1220. self.click_noproject = False
  1221. self.cursor = None
  1222. # Variable to store the GCODE that was edited
  1223. self.gcode_edited = ""
  1224. self.text_editor_tab = None
  1225. # reference for the self.ui.code_editor
  1226. self.reference_code_editor = None
  1227. self.script_code = ''
  1228. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1229. self.tools_db_changed_flag = False
  1230. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1231. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1232. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1233. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1234. 'tsm']
  1235. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1236. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1237. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1238. 'sbp', 'tap', 'xpi']
  1239. self.svg_list = ['svg']
  1240. self.dxf_list = ['dxf']
  1241. self.pdf_list = ['pdf']
  1242. self.prj_list = ['flatprj']
  1243. self.conf_list = ['flatconfig']
  1244. # last used filters
  1245. self.last_op_gerber_filter = None
  1246. self.last_op_excellon_filter = None
  1247. self.last_op_gcode_filter = None
  1248. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1249. # flag for polygons not cleared
  1250. self.poly_not_cleared = False
  1251. # VisPy visuals
  1252. self.isHovering = False
  1253. self.notHovering = True
  1254. # Window geometry
  1255. self.x_pos = None
  1256. self.y_pos = None
  1257. self.width = None
  1258. self.height = None
  1259. # when True, the app has to return from any thread
  1260. self.abort_flag = False
  1261. # set the value used in the Windows Title
  1262. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1263. # this holds a widget that is installed in the Plot Area when View Source option is used
  1264. self.source_editor_tab = None
  1265. self.pagesize = {}
  1266. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1267. # VisPy visuals
  1268. if self.is_legacy is False:
  1269. try:
  1270. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1271. except AttributeError:
  1272. self.tool_shapes = None
  1273. else:
  1274. from appGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1275. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1276. # used in the delayed shutdown self.start_delayed_quit() method
  1277. self.save_timer = None
  1278. # ###########################################################################################################
  1279. # ################################## ADDING FlatCAM EDITORS section #########################################
  1280. # ###########################################################################################################
  1281. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1282. # at the first launch of the App , the editors will not be functional.
  1283. try:
  1284. self.geo_editor = AppGeoEditor(self)
  1285. except Exception as es:
  1286. log.debug("app_Main.__init__() --> Geo Editor Error: %s" % str(es))
  1287. try:
  1288. self.exc_editor = AppExcEditor(self)
  1289. except Exception as es:
  1290. log.debug("app_Main.__init__() --> Excellon Editor Error: %s" % str(es))
  1291. try:
  1292. self.grb_editor = AppGerberEditor(self)
  1293. except Exception as es:
  1294. log.debug("app_Main.__init__() --> Gerber Editor Error: %s" % str(es))
  1295. try:
  1296. self.gcode_editor = AppGCodeEditor(self)
  1297. except Exception as es:
  1298. log.debug("app_Main.__init__() --> GCode Editor Error: %s" % str(es))
  1299. self.log.debug("Finished adding FlatCAM Editor's.")
  1300. self.set_ui_title(name=_("New Project - Not saved"))
  1301. current_platform = platform.architecture()[0]
  1302. if current_platform != '64bit':
  1303. # set Excellon path optimizations algorithm to TSA if the app is run on a 32bit platform
  1304. # modes 'M' or 'B' are not allowed when the app is running in 32bit platform
  1305. if self.defaults['excellon_optimization_type'] in ['M', 'B']:
  1306. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1307. # set Geometry path optimizations algorithm to Rtree if the app is run on a 32bit platform
  1308. # modes 'M' or 'B' are not allowed when the app is running in 32bit platform
  1309. if self.defaults['geometry_optimization_type'] in ['M', 'B']:
  1310. self.ui.geometry_defaults_form.geometry_gen_group.opt_algorithm_radio.set_value('R')
  1311. # ###########################################################################################################
  1312. # ########################################### EXCLUSION AREAS ###############################################
  1313. # ###########################################################################################################
  1314. self.exc_areas = ExclusionAreas(app=self)
  1315. # ###########################################################################################################
  1316. # ##################################### Finished the CONSTRUCTOR ############################################
  1317. # ###########################################################################################################
  1318. App.log.debug("END of constructor. Releasing control.")
  1319. # ###########################################################################################################
  1320. # ########################################## SHOW GUI #######################################################
  1321. # ###########################################################################################################
  1322. # if the app is not started as headless, show it
  1323. if self.cmd_line_headless != 1:
  1324. if show_splash:
  1325. # finish the splash
  1326. self.splash.finish(self.ui)
  1327. mgui_settings = QSettings("Open Source", "FlatCAM")
  1328. if mgui_settings.contains("maximized_gui"):
  1329. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1330. if maximized_ui is True:
  1331. self.ui.showMaximized()
  1332. else:
  1333. self.ui.show()
  1334. else:
  1335. self.ui.show()
  1336. if self.defaults["global_systray_icon"]:
  1337. self.trayIcon.show()
  1338. else:
  1339. log.warning("******************* RUNNING HEADLESS *******************")
  1340. # ###########################################################################################################
  1341. # ######################################## START-UP ARGUMENTS ###############################################
  1342. # ###########################################################################################################
  1343. # test if the program was started with a script as parameter
  1344. if self.cmd_line_shellvar:
  1345. try:
  1346. cnt = 0
  1347. command_tcl = 0
  1348. for i in self.cmd_line_shellvar.split(','):
  1349. if i is not None:
  1350. # noinspection PyBroadException
  1351. try:
  1352. command_tcl = eval(i)
  1353. except Exception:
  1354. command_tcl = i
  1355. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1356. cnt += 1
  1357. # if there are Windows paths then replace the path separator with a Unix like one
  1358. if sys.platform == 'win32':
  1359. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1360. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1361. except Exception as ext:
  1362. print("ERROR: ", ext)
  1363. sys.exit(2)
  1364. if self.cmd_line_shellfile:
  1365. if self.cmd_line_headless != 1:
  1366. if self.ui.shell_dock.isHidden():
  1367. self.ui.shell_dock.show()
  1368. try:
  1369. with open(self.cmd_line_shellfile, "r") as myfile:
  1370. # if show_splash:
  1371. # self.splash.showMessage('%s: %ssec\n%s' % (
  1372. # _("Canvas initialization started.\n"
  1373. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1374. # _("Executing Tcl Script ...")),
  1375. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1376. # color=QtGui.QColor("gray"))
  1377. cmd_line_shellfile_text = myfile.read()
  1378. if self.cmd_line_headless != 1:
  1379. self.shell.exec_command(cmd_line_shellfile_text)
  1380. else:
  1381. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1382. except Exception as ext:
  1383. print("ERROR: ", ext)
  1384. sys.exit(2)
  1385. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1386. # the path/file_name must be enclosed in quotes if it contain spaces
  1387. if App.args:
  1388. self.args_at_startup.emit(App.args)
  1389. if self.defaults.old_defaults_found is True:
  1390. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1391. "Please reboot the application to update."))
  1392. self.defaults.old_defaults_found = False
  1393. # ######################################### INIT FINISHED #######################################################
  1394. # #################################################################################################################
  1395. # #################################################################################################################
  1396. # #################################################################################################################
  1397. # #################################################################################################################
  1398. # #################################################################################################################
  1399. @staticmethod
  1400. def copy_and_overwrite(from_path, to_path):
  1401. """
  1402. From here:
  1403. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1404. :param from_path: source path
  1405. :param to_path: destination path
  1406. :return: None
  1407. """
  1408. if os.path.exists(to_path):
  1409. shutil.rmtree(to_path)
  1410. try:
  1411. shutil.copytree(from_path, to_path)
  1412. except FileNotFoundError:
  1413. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\appGUI\\VisPyData\\data'
  1414. shutil.copytree(from_new_path, to_path)
  1415. def on_startup_args(self, args, silent=False):
  1416. """
  1417. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1418. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1419. :param args: a list containing the application args at startup
  1420. :return: None
  1421. """
  1422. if args is not None:
  1423. args_to_process = args
  1424. else:
  1425. args_to_process = App.args
  1426. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1427. for argument in args_to_process:
  1428. if '.FlatPrj'.lower() in argument.lower():
  1429. try:
  1430. project_name = str(argument)
  1431. if project_name == "":
  1432. if silent is False:
  1433. self.inform.emit(_("Cancelled."))
  1434. else:
  1435. # self.open_project(project_name)
  1436. run_from_arg = True
  1437. # self.worker_task.emit({'fcn': self.open_project,
  1438. # 'params': [project_name, run_from_arg]})
  1439. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1440. except Exception as e:
  1441. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1442. elif '.FlatConfig'.lower() in argument.lower():
  1443. try:
  1444. file_name = str(argument)
  1445. if file_name == "":
  1446. if silent is False:
  1447. self.inform.emit(_("Open Config file failed."))
  1448. else:
  1449. run_from_arg = True
  1450. # self.worker_task.emit({'fcn': self.open_config_file,
  1451. # 'params': [file_name, run_from_arg]})
  1452. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1453. except Exception as e:
  1454. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1455. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1456. try:
  1457. file_name = str(argument)
  1458. if file_name == "":
  1459. if silent is False:
  1460. self.inform.emit(_("Open Script file failed."))
  1461. else:
  1462. if silent is False:
  1463. self.on_fileopenscript(name=file_name)
  1464. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1465. self.on_filerunscript(name=file_name)
  1466. except Exception as e:
  1467. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1468. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1469. log.debug("App.on_startup_args() --> Quit event.")
  1470. sys.exit()
  1471. elif 'save'.lower() in argument.lower():
  1472. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1473. self.preferencesUiManager.save_defaults()
  1474. else:
  1475. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1476. proc_arg = argument.lower()
  1477. for ext in exc_list:
  1478. proc_ext = ext.replace(' ', '')
  1479. proc_ext = '.%s' % proc_ext
  1480. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1481. file_name = str(argument)
  1482. if file_name == "":
  1483. if silent is False:
  1484. self.inform.emit(_("Open Excellon file failed."))
  1485. else:
  1486. self.on_fileopenexcellon(name=file_name, signal=None)
  1487. return
  1488. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1489. for ext in gco_list:
  1490. proc_ext = ext.replace(' ', '')
  1491. proc_ext = '.%s' % proc_ext
  1492. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1493. file_name = str(argument)
  1494. if file_name == "":
  1495. if silent is False:
  1496. self.inform.emit(_("Open GCode file failed."))
  1497. else:
  1498. self.on_fileopengcode(name=file_name, signal=None)
  1499. return
  1500. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1501. for ext in grb_list:
  1502. proc_ext = ext.replace(' ', '')
  1503. proc_ext = '.%s' % proc_ext
  1504. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1505. file_name = str(argument)
  1506. if file_name == "":
  1507. if silent is False:
  1508. self.inform.emit(_("Open Gerber file failed."))
  1509. else:
  1510. self.on_fileopengerber(name=file_name, signal=None)
  1511. return
  1512. # if it reached here without already returning then the app was registered with a file that it does not
  1513. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1514. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1515. # for arg in args_to_process:
  1516. # if 'FlatCAM.exe' in arg:
  1517. # continue
  1518. # else:
  1519. # sys.exit(2)
  1520. def set_ui_title(self, name):
  1521. """
  1522. Sets the title of the main window.
  1523. :param name: String that store the project path and project name
  1524. :return: None
  1525. """
  1526. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1527. (self.version,
  1528. ('BETA' if self.beta else ''),
  1529. platform.architecture()[0],
  1530. self.engine,
  1531. name)
  1532. )
  1533. def on_app_restart(self):
  1534. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1535. # be left in the SySTray
  1536. try:
  1537. self.trayIcon.hide()
  1538. except Exception:
  1539. pass
  1540. fcTranslate.restart_program(app=self)
  1541. def clear_pool(self):
  1542. """
  1543. Clear the multiprocessing pool and calls garbage collector.
  1544. :return: None
  1545. """
  1546. self.pool.close()
  1547. self.pool = Pool()
  1548. self.pool_recreated.emit(self.pool)
  1549. gc.collect()
  1550. def install_tools(self):
  1551. """
  1552. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1553. Instantiation of the Tools classes.
  1554. The order that the tools are installed is important as they can depend on each other install position.
  1555. :return: None
  1556. """
  1557. # shell tool has t obe initialized always first because other tools print messages in the Shell Dock
  1558. self.shell = FCShell(app=self, version=self.version)
  1559. self.distance_tool = Distance(self)
  1560. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1561. before=self.ui.menueditorigin,
  1562. separator=False)
  1563. self.distance_min_tool = DistanceMin(self)
  1564. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1565. pos=self.ui.menuedit,
  1566. before=self.ui.menueditorigin,
  1567. separator=True)
  1568. self.dblsidedtool = DblSidedTool(self)
  1569. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1570. self.cal_exc_tool = ToolCalibration(self)
  1571. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1572. before=self.dblsidedtool.menuAction,
  1573. separator=False)
  1574. self.align_objects_tool = AlignObjects(self)
  1575. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1576. self.edrills_tool = ToolExtractDrills(self)
  1577. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1578. self.panelize_tool = Panelize(self)
  1579. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1580. self.film_tool = Film(self)
  1581. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1582. self.paste_tool = SolderPaste(self)
  1583. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1584. self.calculator_tool = ToolCalculator(self)
  1585. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1586. self.sub_tool = ToolSub(self)
  1587. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1588. pos=self.ui.menutool, separator=True)
  1589. self.rules_tool = RulesCheck(self)
  1590. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1591. pos=self.ui.menutool, separator=False)
  1592. self.optimal_tool = ToolOptimal(self)
  1593. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1594. pos=self.ui.menutool, separator=True)
  1595. self.move_tool = ToolMove(self)
  1596. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1597. before=self.ui.menueditorigin, separator=True)
  1598. self.cutout_tool = CutOut(self)
  1599. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1600. before=self.sub_tool.menuAction)
  1601. self.ncclear_tool = NonCopperClear(self)
  1602. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1603. before=self.sub_tool.menuAction, separator=True)
  1604. self.paint_tool = ToolPaint(self)
  1605. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1606. before=self.sub_tool.menuAction, separator=True)
  1607. self.isolation_tool = ToolIsolation(self)
  1608. self.isolation_tool.install(icon=QtGui.QIcon(self.resource_location + '/iso_16.png'), pos=self.ui.menutool,
  1609. before=self.sub_tool.menuAction, separator=True)
  1610. self.drilling_tool = ToolDrilling(self)
  1611. self.drilling_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), pos=self.ui.menutool,
  1612. before=self.sub_tool.menuAction, separator=True)
  1613. self.copper_thieving_tool = ToolCopperThieving(self)
  1614. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1615. pos=self.ui.menutool)
  1616. self.fiducial_tool = ToolFiducials(self)
  1617. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1618. pos=self.ui.menutool)
  1619. self.qrcode_tool = QRCode(self)
  1620. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1621. pos=self.ui.menutool)
  1622. self.punch_tool = ToolPunchGerber(self)
  1623. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1624. self.invert_tool = ToolInvertGerber(self)
  1625. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1626. self.corners_tool = ToolCorners(self)
  1627. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1628. self.etch_tool = ToolEtchCompensation(self)
  1629. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etch_32.png'), pos=self.ui.menutool)
  1630. self.transform_tool = ToolTransform(self)
  1631. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1632. pos=self.ui.menuoptions, separator=True)
  1633. self.properties_tool = Properties(self)
  1634. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1635. pos=self.ui.menuoptions)
  1636. self.pdf_tool = ToolPDF(self)
  1637. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1638. pos=self.ui.menufileimport,
  1639. separator=True)
  1640. self.image_tool = ToolImage(self)
  1641. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1642. pos=self.ui.menufileimport,
  1643. separator=True)
  1644. self.pcb_wizard_tool = PcbWizard(self)
  1645. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1646. pos=self.ui.menufileimport)
  1647. self.log.debug("Tools are installed.")
  1648. def remove_tools(self):
  1649. """
  1650. Will remove all the actions in the Tool menu.
  1651. :return: None
  1652. """
  1653. for act in self.ui.menutool.actions():
  1654. self.ui.menutool.removeAction(act)
  1655. def init_tools(self):
  1656. """
  1657. Initialize the Tool tab in the notebook side of the central widget.
  1658. Remove the actions in the Tools menu.
  1659. Instantiate again the FlatCAM tools (plugins).
  1660. All this is required when changing the layout: standard, compact etc.
  1661. :return: None
  1662. """
  1663. log.debug("init_tools()")
  1664. # delete the data currently in the Tools Tab and the Tab itself
  1665. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1666. if widget is not None:
  1667. widget.deleteLater()
  1668. self.ui.notebook.removeTab(2)
  1669. # rebuild the Tools Tab
  1670. self.ui.tool_tab = QtWidgets.QWidget()
  1671. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1672. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1673. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1674. self.ui.tool_scroll_area = VerticalScrollArea()
  1675. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1676. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1677. # first remove all of them
  1678. self.remove_tools()
  1679. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1680. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1681. '&Command Line\tS')
  1682. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1683. # third install all of them
  1684. try:
  1685. self.install_tools()
  1686. except AttributeError:
  1687. pass
  1688. self.log.debug("Tools are initialized.")
  1689. # def parse_system_fonts(self):
  1690. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1691. # 'params': []})
  1692. def connect_tools_signals_to_toolbar(self, ui):
  1693. ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1694. ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1695. ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1696. ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1697. ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1698. ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1699. ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1700. ui.isolation_btn.triggered.connect(lambda: self.isolation_tool.run(toggle=True))
  1701. ui.drill_btn.triggered.connect(lambda: self.drilling_tool.run(toggle=True))
  1702. ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1703. ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1704. ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1705. ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1706. ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1707. ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1708. ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1709. ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1710. ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1711. ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1712. ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1713. ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1714. ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1715. ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1716. ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1717. def connect_toolbar_signals(self, ui):
  1718. """
  1719. Reconnect the signals to the actions in the toolbar.
  1720. This has to be done each time after the FlatCAM tools are removed/installed.
  1721. :return: None
  1722. """
  1723. # Toolbar
  1724. # File Toolbar Signals
  1725. # ui.file_new_btn.triggered.connect(self.on_file_new)
  1726. ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1727. ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1728. ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1729. ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1730. # View Toolbar Signals
  1731. ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1732. ui.replot_btn.triggered.connect(self.plot_all)
  1733. ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1734. ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1735. ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1736. # Edit Toolbar Signals
  1737. ui.editgeo_btn.triggered.connect(self.object2editor)
  1738. ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1739. ui.copy_btn.triggered.connect(self.on_copy_command)
  1740. ui.delete_btn.triggered.connect(self.on_delete)
  1741. ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1742. ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1743. ui.origin_btn.triggered.connect(self.on_set_origin)
  1744. ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1745. ui.jmp_btn.triggered.connect(self.on_jump_to)
  1746. ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1747. # Scripting Toolbar Signals
  1748. ui.shell_btn.triggered.connect(ui.toggle_shell_ui)
  1749. ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1750. ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1751. ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1752. # Tools Toolbar Signals
  1753. try:
  1754. self.connect_tools_signals_to_toolbar(ui=ui)
  1755. except Exception as err:
  1756. log.debug("App.connect_toolbar_signals() tools signals -> %s" % str(err))
  1757. def object2editor(self):
  1758. """
  1759. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1760. :return: None
  1761. """
  1762. self.defaults.report_usage("object2editor()")
  1763. # disable the objects menu as it may interfere with the appEditors
  1764. self.ui.menuobjects.setDisabled(True)
  1765. edited_object = self.collection.get_active()
  1766. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1767. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1768. pass
  1769. else:
  1770. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1771. return
  1772. if isinstance(edited_object, GeometryObject):
  1773. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1774. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1775. # we set the notebook to hidden
  1776. # self.ui.splitter.setSizes([0, 1])
  1777. if edited_object.multigeo is True:
  1778. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1779. if len(sel_rows) > 1:
  1780. self.inform.emit('[WARNING_NOTCL] %s' %
  1781. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1782. "is not possible.\n"
  1783. "Edit only one geometry at a time."))
  1784. if not sel_rows:
  1785. self.inform.emit('[WARNING_NOTCL] %s.' % _("No Tool Selected"))
  1786. return
  1787. # determine the tool dia of the selected tool
  1788. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1789. # now find the key in the edited_object.tools that has this tooldia
  1790. multi_tool = 1
  1791. for tool in edited_object.tools:
  1792. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1793. multi_tool = tool
  1794. break
  1795. log.debug("Editing MultiGeo Geometry with tool diameter: %s" % str(multi_tool))
  1796. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1797. else:
  1798. log.debug("Editing SingleGeo Geometry with tool diameter.")
  1799. self.geo_editor.edit_fcgeometry(edited_object)
  1800. # set call source to the Editor we go into
  1801. self.call_source = 'geo_editor'
  1802. elif isinstance(edited_object, ExcellonObject):
  1803. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1804. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1805. if self.ui.splitter.sizes()[0] == 0:
  1806. self.ui.splitter.setSizes([1, 1])
  1807. self.exc_editor.edit_fcexcellon(edited_object)
  1808. # set call source to the Editor we go into
  1809. self.call_source = 'exc_editor'
  1810. elif isinstance(edited_object, GerberObject):
  1811. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1812. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1813. if self.ui.splitter.sizes()[0] == 0:
  1814. self.ui.splitter.setSizes([1, 1])
  1815. self.grb_editor.edit_fcgerber(edited_object)
  1816. # set call source to the Editor we go into
  1817. self.call_source = 'grb_editor'
  1818. # reset the following variables so the UI is built again after edit
  1819. edited_object.ui_build = False
  1820. elif isinstance(edited_object, CNCJobObject):
  1821. if self.ui.splitter.sizes()[0] == 0:
  1822. self.ui.splitter.setSizes([1, 1])
  1823. # set call source to the Editor we go into
  1824. self.call_source = 'gcode_editor'
  1825. self.gcode_editor.edit_fcgcode(edited_object)
  1826. # make sure that we can't select another object while in Editor Mode:
  1827. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1828. self.ui.project_frame.setDisabled(True)
  1829. # delete any selection shape that might be active as they are not relevant in Editor
  1830. self.delete_selection_shape()
  1831. # hide the Tools Toolbar
  1832. tools_tb = self.ui.toolbartools
  1833. if tools_tb.isVisible():
  1834. tools_tb.hide()
  1835. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1836. self.ui.plot_tab_area.protectTab(0)
  1837. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1838. self.should_we_save = True
  1839. def editor2object(self, cleanup=None):
  1840. """
  1841. Transfers the Geometry or Excellon from it's editor to the current object.
  1842. :return: None
  1843. """
  1844. self.defaults.report_usage("editor2object()")
  1845. # re-enable the objects menu that was disabled on entry in Editor mode
  1846. self.ui.menuobjects.setDisabled(False)
  1847. # do not update a geometry or excellon object unless it comes out of an editor
  1848. if self.call_source != 'app':
  1849. edited_obj = self.collection.get_active()
  1850. if cleanup is None:
  1851. msgbox = QtWidgets.QMessageBox()
  1852. msgbox.setText(_("Do you want to save the edited object?"))
  1853. msgbox.setWindowTitle(_("Close Editor"))
  1854. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1855. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  1856. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1857. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1858. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1859. msgbox.setDefaultButton(bt_yes)
  1860. msgbox.exec_()
  1861. response = msgbox.clickedButton()
  1862. if response == bt_yes:
  1863. # show the Tools Toolbar
  1864. tools_tb = self.ui.toolbartools
  1865. tools_tb.show()
  1866. # clean the Tools Tab
  1867. self.ui.tool_scroll_area.takeWidget()
  1868. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1869. self.ui.notebook.setTabText(2, "Tool")
  1870. if edited_obj.kind == 'geometry':
  1871. obj_type = "Geometry"
  1872. self.geo_editor.update_fcgeometry(edited_obj)
  1873. # self.geo_editor.update_options(edited_obj)
  1874. # restore GUI to the Selected TAB
  1875. # Remove anything else in the appGUI
  1876. self.ui.tool_scroll_area.takeWidget()
  1877. # update the geo object options so it is including the bounding box values
  1878. try:
  1879. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1880. edited_obj.options['xmin'] = xmin
  1881. edited_obj.options['ymin'] = ymin
  1882. edited_obj.options['xmax'] = xmax
  1883. edited_obj.options['ymax'] = ymax
  1884. except AttributeError as e:
  1885. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1886. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1887. edited_obj.build_ui()
  1888. edited_obj.plot()
  1889. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1890. elif edited_obj.kind == 'gerber':
  1891. obj_type = "Gerber"
  1892. self.grb_editor.update_fcgerber()
  1893. # self.grb_editor.update_options(edited_obj)
  1894. # delete the old object (the source object) if it was an empty one
  1895. try:
  1896. if len(edited_obj.solid_geometry) == 0:
  1897. old_name = edited_obj.options['name']
  1898. self.collection.delete_by_name(old_name)
  1899. except TypeError:
  1900. # if the solid_geometry is a single Polygon the len() will not work
  1901. # in any case, falling here means that we have something in the solid_geometry, even if only
  1902. # a single Polygon, therefore we pass this
  1903. pass
  1904. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1905. # restore GUI to the Selected TAB
  1906. # Remove anything else in the GUI
  1907. self.ui.selected_scroll_area.takeWidget()
  1908. elif edited_obj.kind == 'excellon':
  1909. obj_type = "Excellon"
  1910. self.exc_editor.update_fcexcellon(edited_obj)
  1911. # self.exc_editor.update_options(edited_obj)
  1912. # restore GUI to the Selected TAB
  1913. # Remove anything else in the GUI
  1914. self.ui.tool_scroll_area.takeWidget()
  1915. # delete the old object (the source object) if it was an empty one
  1916. # find if we have drills:
  1917. has_drills = None
  1918. for tt in edited_obj.tools:
  1919. if 'drills' in edited_obj.tools[tt] and edited_obj.tools[tt]['drills']:
  1920. has_drills = True
  1921. break
  1922. # find if we have slots:
  1923. has_slots = None
  1924. for tt in edited_obj.tools:
  1925. if 'slots' in edited_obj.tools[tt] and edited_obj.tools[tt]['slots']:
  1926. has_slots = True
  1927. break
  1928. if has_drills is None and has_slots is None:
  1929. old_name = edited_obj.options['name']
  1930. self.collection.delete_by_name(name=old_name)
  1931. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1932. elif edited_obj.kind == 'cncjob':
  1933. obj_type = "CNCJob"
  1934. self.gcode_editor.update_fcgcode(edited_obj)
  1935. # self.exc_editor.update_options(edited_obj)
  1936. # restore GUI to the Selected TAB
  1937. # Remove anything else in the GUI
  1938. self.ui.tool_scroll_area.takeWidget()
  1939. edited_obj.build_ui()
  1940. # close the open tab
  1941. for idx in range(self.ui.plot_tab_area.count()):
  1942. if self.ui.plot_tab_area.widget(idx).objectName() == 'gcode_editor_tab':
  1943. self.ui.plot_tab_area.closeTab(idx)
  1944. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1945. else:
  1946. self.inform.emit('[WARNING_NOTCL] %s' %
  1947. _("Select a Gerber, Geometry, Excellon or CNCJobObject to update."))
  1948. return
  1949. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1950. elif response == bt_no:
  1951. # show the Tools Toolbar
  1952. tools_tb = self.ui.toolbartools
  1953. tools_tb.show()
  1954. # clean the Tools Tab
  1955. self.ui.tool_scroll_area.takeWidget()
  1956. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1957. self.ui.notebook.setTabText(2, "Tool")
  1958. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1959. if edited_obj.kind == 'geometry':
  1960. self.geo_editor.deactivate()
  1961. edited_obj.build_ui()
  1962. edited_obj.plot()
  1963. elif edited_obj.kind == 'gerber':
  1964. self.grb_editor.deactivate_grb_editor()
  1965. edited_obj.build_ui()
  1966. elif edited_obj.kind == 'excellon':
  1967. self.exc_editor.deactivate()
  1968. edited_obj.build_ui()
  1969. elif edited_obj.kind == 'cncjob':
  1970. self.gcode_editor.deactivate()
  1971. edited_obj.build_ui()
  1972. # close the open tab
  1973. for idx in range(self.ui.plot_tab_area.count()):
  1974. if self.ui.plot_tab_area.widget(idx).objectName() == 'gcode_editor_tab':
  1975. self.ui.plot_tab_area.closeTab(idx)
  1976. else:
  1977. self.inform.emit('[WARNING_NOTCL] %s' %
  1978. _("Select a Gerber, Geometry, Excellon or CNCJobObject to update."))
  1979. return
  1980. elif response == bt_cancel:
  1981. return
  1982. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1983. # edited_obj.build_ui()
  1984. # Switch notebook to Selected page
  1985. # self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1986. else:
  1987. # show the Tools Toolbar
  1988. tools_tb = self.ui.toolbartools
  1989. tools_tb.show()
  1990. if isinstance(edited_obj, GeometryObject):
  1991. self.geo_editor.deactivate()
  1992. elif isinstance(edited_obj, GerberObject):
  1993. self.grb_editor.deactivate_grb_editor()
  1994. elif isinstance(edited_obj, ExcellonObject):
  1995. self.exc_editor.deactivate()
  1996. else:
  1997. self.inform.emit('[WARNING_NOTCL] %s' %
  1998. _("Select a Gerber, Geometry or Excellon Object to update."))
  1999. return
  2000. # if notebook is hidden we show it
  2001. if self.ui.splitter.sizes()[0] == 0:
  2002. self.ui.splitter.setSizes([1, 1])
  2003. # restore the call_source to app
  2004. self.call_source = 'app'
  2005. # edited_obj.plot()
  2006. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2007. self.ui.plot_tab_area.protectTab(0)
  2008. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2009. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2010. self.ui.project_frame.setDisabled(False)
  2011. def get_last_folder(self):
  2012. """
  2013. Get the folder path from where the last file was opened.
  2014. :return: String, last opened folder path
  2015. """
  2016. return self.defaults["global_last_folder"]
  2017. def get_last_save_folder(self):
  2018. """
  2019. Get the folder path from where the last file was saved.
  2020. :return: String, last saved folder path
  2021. """
  2022. loc = self.defaults["global_last_save_folder"]
  2023. if loc is None:
  2024. loc = self.defaults["global_last_folder"]
  2025. if loc is None:
  2026. loc = os.path.dirname(__file__)
  2027. return loc
  2028. @QtCore.pyqtSlot(str)
  2029. @QtCore.pyqtSlot(str, bool)
  2030. def info(self, msg, shell_echo=True):
  2031. """
  2032. Informs the user. Normally on the status bar, optionally
  2033. also on the shell.
  2034. :param msg: Text to write.
  2035. :type msg: str
  2036. :param shell_echo: Control if to display the message msg in the Shell
  2037. :type shell_echo: bool
  2038. :return: None
  2039. """
  2040. # Type of message in brackets at the beginning of the message.
  2041. match = re.search(r"\[(.*)\](.*)", msg)
  2042. if match:
  2043. level = match.group(1)
  2044. msg_ = match.group(2)
  2045. self.ui.fcinfo.set_status(str(msg_), level=level)
  2046. if shell_echo is True:
  2047. if level.lower() == "error":
  2048. self.shell_message(msg, error=True, show=True)
  2049. elif level.lower() == "warning":
  2050. self.shell_message(msg, warning=True, show=True)
  2051. elif level.lower() == "error_notcl":
  2052. self.shell_message(msg, error=True, show=False)
  2053. elif level.lower() == "warning_notcl":
  2054. self.shell_message(msg, warning=True, show=False)
  2055. elif level.lower() == "success":
  2056. self.shell_message(msg, success=True, show=False)
  2057. elif level.lower() == "selected":
  2058. self.shell_message(msg, selected=True, show=False)
  2059. else:
  2060. self.shell_message(msg, show=False)
  2061. else:
  2062. self.ui.fcinfo.set_status(str(msg), level="info")
  2063. # make sure that if the message is to clear the infobar with a space
  2064. # is not printed over and over on the shell
  2065. if msg != '' and shell_echo is True:
  2066. self.shell_message(msg)
  2067. def info_shell(self, msg):
  2068. self.shell_message(msg=msg)
  2069. def on_import_preferences(self):
  2070. """
  2071. Loads the application default settings from a saved file into
  2072. ``self.defaults`` dictionary.
  2073. :return: None
  2074. """
  2075. self.defaults.report_usage("on_import_preferences")
  2076. App.log.debug("App.on_import_preferences()")
  2077. # Show file chooser
  2078. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2079. try:
  2080. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2081. directory=self.data_path,
  2082. filter=filter_)
  2083. except TypeError:
  2084. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2085. filter=filter_)
  2086. filename = str(filename)
  2087. if filename == "":
  2088. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2089. return
  2090. # Load in the defaults from the chosen file
  2091. self.defaults.load(filename=filename)
  2092. self.preferencesUiManager.on_preferences_edited()
  2093. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2094. def on_export_preferences(self):
  2095. """
  2096. Save the defaults dictionary to a file.
  2097. :return: None
  2098. """
  2099. self.defaults.report_usage("on_export_preferences")
  2100. App.log.debug("on_export_preferences()")
  2101. # defaults_file_content = None
  2102. # Show file chooser
  2103. date = str(datetime.today()).rpartition('.')[0]
  2104. date = ''.join(c for c in date if c not in ':-')
  2105. date = date.replace(' ', '_')
  2106. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2107. try:
  2108. filename, _f = FCFileSaveDialog.get_saved_filename(
  2109. caption=_("Export FlatCAM Preferences"),
  2110. directory=self.data_path + '/preferences_' + date,
  2111. ext_filter=filter__
  2112. )
  2113. except TypeError:
  2114. filename, _f = FCFileSaveDialog.get_saved_filename(
  2115. caption=_("Export FlatCAM Preferences"), ext_filter=filter__)
  2116. filename = str(filename)
  2117. if filename == "":
  2118. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2119. return
  2120. # Update options
  2121. self.preferencesUiManager.defaults_read_form()
  2122. self.defaults.propagate_defaults()
  2123. # Save update options
  2124. try:
  2125. self.defaults.write(filename=filename)
  2126. except Exception:
  2127. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2128. return
  2129. if self.defaults["global_open_style"] is False:
  2130. self.file_opened.emit("preferences", filename)
  2131. self.file_saved.emit("preferences", filename)
  2132. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2133. def save_to_file(self, content_to_save, txt_content):
  2134. """
  2135. Save something to a file.
  2136. :return: None
  2137. """
  2138. self.defaults.report_usage("save_to_file")
  2139. App.log.debug("save_to_file()")
  2140. self.date = str(datetime.today()).rpartition('.')[0]
  2141. self.date = ''.join(c for c in self.date if c not in ':-')
  2142. self.date = self.date.replace(' ', '_')
  2143. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2144. path_to_save = self.defaults["global_last_save_folder"] if \
  2145. self.defaults["global_last_save_folder"] is not None else self.data_path
  2146. try:
  2147. filename, _f = FCFileSaveDialog.get_saved_filename(
  2148. caption=_("Save to file"),
  2149. directory=path_to_save + '/file_' + self.date,
  2150. ext_filter=filter__
  2151. )
  2152. except TypeError:
  2153. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), ext_filter=filter__)
  2154. filename = str(filename)
  2155. if filename == "":
  2156. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2157. return
  2158. else:
  2159. try:
  2160. with open(filename, 'w') as f:
  2161. ___ = f.read()
  2162. except PermissionError:
  2163. self.inform.emit('[WARNING] %s' %
  2164. _("Permission denied, saving not possible.\n"
  2165. "Most likely another app is holding the file open and not accessible."))
  2166. return
  2167. except IOError:
  2168. App.log.debug('Creating a new file ...')
  2169. f = open(filename, 'w')
  2170. f.close()
  2171. except Exception:
  2172. e = sys.exc_info()[0]
  2173. App.log.error("Could not load the file.")
  2174. App.log.error(str(e))
  2175. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2176. return
  2177. # Save content
  2178. if filename.rpartition('.')[2].lower() == 'html':
  2179. file_content = content_to_save
  2180. else:
  2181. file_content = txt_content
  2182. try:
  2183. with open(filename, "w") as f:
  2184. f.write(file_content)
  2185. except Exception:
  2186. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2187. return
  2188. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2189. def register_recent(self, kind, filename):
  2190. """
  2191. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2192. dictionary.
  2193. :param kind: type of file that was opened
  2194. :param filename: the path and file name for the file that was opened
  2195. :return:
  2196. """
  2197. self.log.debug("register_recent()")
  2198. self.log.debug(" %s" % kind)
  2199. self.log.debug(" %s" % filename)
  2200. record = {'kind': str(kind), 'filename': str(filename)}
  2201. if record in self.recent:
  2202. return
  2203. if record in self.recent_projects:
  2204. return
  2205. if record['kind'] == 'project':
  2206. self.recent_projects.insert(0, record)
  2207. else:
  2208. self.recent.insert(0, record)
  2209. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2210. self.recent.pop()
  2211. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2212. self.recent_projects.pop()
  2213. try:
  2214. f = open(self.data_path + '/recent.json', 'w')
  2215. except IOError:
  2216. App.log.error("Failed to open recent items file for writing.")
  2217. self.inform.emit('[ERROR_NOTCL] %s' %
  2218. _('Failed to open recent files file for writing.'))
  2219. return
  2220. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2221. f.close()
  2222. try:
  2223. fp = open(self.data_path + '/recent_projects.json', 'w')
  2224. except IOError:
  2225. App.log.error("Failed to open recent items file for writing.")
  2226. self.inform.emit('[ERROR_NOTCL] %s' %
  2227. _('Failed to open recent projects file for writing.'))
  2228. return
  2229. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2230. fp.close()
  2231. # Re-build the recent items menu
  2232. self.setup_recent_items()
  2233. def on_about(self):
  2234. """
  2235. Displays the "about" dialog found in the Menu --> Help.
  2236. :return: None
  2237. """
  2238. self.defaults.report_usage("on_about")
  2239. version = self.version
  2240. version_date = self.version_date
  2241. beta = self.beta
  2242. class AboutDialog(QtWidgets.QDialog):
  2243. def __init__(self, app, parent=None):
  2244. QtWidgets.QDialog.__init__(self, parent)
  2245. self.app = app
  2246. # Icon and title
  2247. self.setWindowIcon(parent.app_icon)
  2248. self.setWindowTitle(_("About FlatCAM"))
  2249. self.resize(600, 200)
  2250. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2251. # self.setStyleSheet(
  2252. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2253. # "background-attachment: fixed"
  2254. # )
  2255. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2256. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2257. # palette = QtGui.QPalette()
  2258. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2259. # self.setPalette(palette)
  2260. logo = QtWidgets.QLabel()
  2261. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2262. title = QtWidgets.QLabel(
  2263. "<font size=8><B>FlatCAM</B></font><BR>"
  2264. "{title}<BR>"
  2265. "<BR>"
  2266. "<BR>"
  2267. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2268. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2269. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2270. "<B>{issue}</B></a><BR>".format(
  2271. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2272. devel=_("Development"),
  2273. down=_("DOWNLOAD"),
  2274. issue=_("Issue tracker"))
  2275. )
  2276. title.setOpenExternalLinks(True)
  2277. closebtn = QtWidgets.QPushButton(_("Close"))
  2278. tab_widget = QtWidgets.QTabWidget()
  2279. description_label = QtWidgets.QLabel(
  2280. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2281. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2282. version=version,
  2283. beta=('BETA' if beta else ''),
  2284. date=version_date,
  2285. arch=platform.architecture()[0])
  2286. )
  2287. description_label.setOpenExternalLinks(True)
  2288. lic_lbl_header = QtWidgets.QLabel(
  2289. '%s:<br>%s<br>' % (
  2290. _('Licensed under the MIT license'),
  2291. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2292. "http://www.opensource.org/licenses/mit-license.php</a>"
  2293. )
  2294. )
  2295. lic_lbl_header.setOpenExternalLinks(True)
  2296. lic_lbl_body = QtWidgets.QLabel(
  2297. _(
  2298. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2299. 'of this software and associated documentation files (the "Software"), to deal\n'
  2300. 'in the Software without restriction, including without limitation the rights\n'
  2301. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2302. 'copies of the Software, and to permit persons to whom the Software is\n'
  2303. 'furnished to do so, subject to the following conditions:\n\n'
  2304. 'The above copyright notice and this permission notice shall be included in\n'
  2305. 'all copies or substantial portions of the Software.\n\n'
  2306. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2307. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2308. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2309. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2310. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2311. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2312. 'THE SOFTWARE.'
  2313. )
  2314. )
  2315. attributions_label = QtWidgets.QLabel(
  2316. _(
  2317. 'Some of the icons used are from the following sources:<br>'
  2318. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2319. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2320. 'title="Flaticon">www.flaticon.com</a></div>'
  2321. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2322. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2323. '<div>Icons by <a href="https://www.flaticon.com/authors/pixel-perfect" '
  2324. 'title="Pixel perfect">Pixel perfect</a> from <a href="https://www.flaticon.com/" '
  2325. 'title="Flaticon">www.flaticon.com</a></div>'
  2326. )
  2327. )
  2328. attributions_label.setOpenExternalLinks(True)
  2329. # layouts
  2330. layout1 = QtWidgets.QVBoxLayout()
  2331. layout1_1 = QtWidgets.QHBoxLayout()
  2332. layout1_2 = QtWidgets.QHBoxLayout()
  2333. layout2 = QtWidgets.QHBoxLayout()
  2334. layout3 = QtWidgets.QHBoxLayout()
  2335. self.setLayout(layout1)
  2336. layout1.addLayout(layout1_1)
  2337. layout1.addLayout(layout1_2)
  2338. layout1.addLayout(layout2)
  2339. layout1.addLayout(layout3)
  2340. layout1_1.addStretch()
  2341. layout1_1.addWidget(description_label)
  2342. layout1_2.addWidget(tab_widget)
  2343. self.splash_tab = QtWidgets.QWidget()
  2344. self.splash_tab.setObjectName("splash_about")
  2345. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2346. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2347. tab_widget.addTab(self.splash_tab, _("Splash"))
  2348. self.programmmers_tab = QtWidgets.QWidget()
  2349. self.programmmers_tab.setObjectName("programmers_about")
  2350. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2351. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2352. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2353. self.translators_tab = QtWidgets.QWidget()
  2354. self.translators_tab.setObjectName("translators_about")
  2355. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2356. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2357. tab_widget.addTab(self.translators_tab, _("Translators"))
  2358. self.license_tab = QtWidgets.QWidget()
  2359. self.license_tab.setObjectName("license_about")
  2360. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2361. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2362. tab_widget.addTab(self.license_tab, _("License"))
  2363. self.attributions_tab = QtWidgets.QWidget()
  2364. self.attributions_tab.setObjectName("attributions_about")
  2365. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2366. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2367. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2368. self.splash_tab_layout.addWidget(logo, stretch=0)
  2369. self.splash_tab_layout.addWidget(title, stretch=1)
  2370. pal = QtGui.QPalette()
  2371. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2372. self.prog_grid_lay = QtWidgets.QGridLayout()
  2373. self.prog_grid_lay.setHorizontalSpacing(20)
  2374. self.prog_grid_lay.setColumnStretch(0, 0)
  2375. self.prog_grid_lay.setColumnStretch(2, 1)
  2376. prog_widget = QtWidgets.QWidget()
  2377. prog_widget.setLayout(self.prog_grid_lay)
  2378. prog_scroll = QtWidgets.QScrollArea()
  2379. prog_scroll.setWidget(prog_widget)
  2380. prog_scroll.setWidgetResizable(True)
  2381. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2382. prog_scroll.setPalette(pal)
  2383. self.programmmers_tab_layout.addWidget(prog_scroll)
  2384. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2385. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2386. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2387. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2388. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2389. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2390. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2391. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2392. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2393. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2394. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2395. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2396. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2397. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2398. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2399. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2400. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2401. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2402. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2403. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2404. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2405. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2406. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2407. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2408. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2409. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2410. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2411. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2412. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2413. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2414. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2415. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2416. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2417. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2418. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2419. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2420. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2421. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2422. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2423. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2424. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2425. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2426. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2427. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2428. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2429. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2430. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2431. self.translator_grid_lay = QtWidgets.QGridLayout()
  2432. self.translator_grid_lay.setColumnStretch(0, 0)
  2433. self.translator_grid_lay.setColumnStretch(1, 0)
  2434. self.translator_grid_lay.setColumnStretch(2, 1)
  2435. self.translator_grid_lay.setColumnStretch(3, 0)
  2436. # trans_widget = QtWidgets.QWidget()
  2437. # trans_widget.setLayout(self.translator_grid_lay)
  2438. # self.translators_tab_layout.addWidget(trans_widget)
  2439. # self.translators_tab_layout.addStretch()
  2440. trans_widget = QtWidgets.QWidget()
  2441. trans_widget.setLayout(self.translator_grid_lay)
  2442. trans_scroll = QtWidgets.QScrollArea()
  2443. trans_scroll.setWidget(trans_widget)
  2444. trans_scroll.setWidgetResizable(True)
  2445. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2446. trans_scroll.setPalette(pal)
  2447. self.translators_tab_layout.addWidget(trans_scroll)
  2448. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2449. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2450. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2451. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2452. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2453. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2454. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2455. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2456. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Michel Maciejewski"), 2, 1)
  2457. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2458. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<micmac589@gmail.com>"), 2, 3)
  2459. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2460. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2461. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2462. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2463. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2464. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Massimiliano Golfetto"), 4, 1)
  2465. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2466. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2467. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2468. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2469. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2470. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2471. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2472. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2473. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2474. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2475. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2476. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2477. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2478. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2479. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2480. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2481. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Turkish"), 9, 0)
  2482. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mehmet Kaya"), 9, 1)
  2483. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<malatyakaya480@gmail.com>"), 9, 3)
  2484. self.translator_grid_lay.setColumnStretch(0, 0)
  2485. self.translators_tab_layout.addStretch()
  2486. self.license_tab_layout.addWidget(lic_lbl_header)
  2487. self.license_tab_layout.addWidget(lic_lbl_body)
  2488. self.license_tab_layout.addStretch()
  2489. self.attributions_tab_layout.addWidget(attributions_label)
  2490. self.attributions_tab_layout.addStretch()
  2491. layout3.addStretch()
  2492. layout3.addWidget(closebtn)
  2493. closebtn.clicked.connect(self.accept)
  2494. AboutDialog(app=self, parent=self.ui).exec_()
  2495. def on_readme(self):
  2496. """
  2497. Displays the "about" dialog found in the Menu --> Help.
  2498. :return: None
  2499. """
  2500. class ReadmeDialog(QtWidgets.QDialog):
  2501. def __init__(self, app, parent=None):
  2502. QtWidgets.QDialog.__init__(self, parent)
  2503. self.app = app
  2504. open_source_link = "<a href = 'https://opensource.org/'<b>Open Source</b></a>"
  2505. new_features_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/pull-requests/'" \
  2506. "<b>click</b></a>"
  2507. bugs_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/issues/new'<b>click</b></a>"
  2508. # donation_link = "<a href = 'https://www.paypal.com/cgi-bin/webscr?cmd=_" \
  2509. # "donations&business=WLTJJ3Q77D98L&currency_code=USD&source=url'<b>click</b></a>"
  2510. # Icon and title
  2511. self.setWindowIcon(parent.app_icon)
  2512. self.setWindowTitle(_("Important Information's"))
  2513. self.resize(750, 375)
  2514. logo = QtWidgets.QLabel()
  2515. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/contribute256.png'))
  2516. # content = QtWidgets.QLabel(
  2517. # "%s<br>"
  2518. # "%s<br><br>"
  2519. # "%s,<br>"
  2520. # "%s<br>"
  2521. # "<ul>"
  2522. # "<li> &nbsp;%s %s</li>"
  2523. # "<li> &nbsp;%s %s</li>"
  2524. # "</ul>"
  2525. # "%s %s.<br>"
  2526. # "%s"
  2527. # "<ul>"
  2528. # "<li> &nbsp;%s &#128077;</li>"
  2529. # "<li> &nbsp;%s &#128513;</li>"
  2530. # "</ul>" %
  2531. # (
  2532. # _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2533. # _("Yet it cannot evolve without <b>contributions</b>."),
  2534. # _("If you want to see this application grow and become better and better"),
  2535. # _("you can <b>contribute</b> to the development yourself by:"),
  2536. # _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2537. # new_features_link,
  2538. # _("Bug Reports by providing the steps required to reproduce the bug"),
  2539. # bugs_link,
  2540. # _("If you like or use this program you can make a donation"),
  2541. # donation_link,
  2542. # _("You don't have to make a donation %s, and it is totally optional but:") % donation_link,
  2543. # _("it will be welcomed with joy"),
  2544. # _("it will give me a reason to continue")
  2545. # )
  2546. # )
  2547. content = QtWidgets.QLabel(
  2548. "%s<br>"
  2549. "%s<br><br>"
  2550. "%s,<br>"
  2551. "%s<br>"
  2552. "<ul>"
  2553. "<li> &nbsp;%s %s</li>"
  2554. "<li> &nbsp;%s %s</li>"
  2555. "</ul>" %
  2556. (
  2557. _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2558. _("Yet it cannot evolve without <b>contributions</b>."),
  2559. _("If you want to see this application grow and become better and better"),
  2560. _("you can <b>contribute</b> to the development yourself by:"),
  2561. _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2562. new_features_link,
  2563. _("Bug Reports by providing the steps required to reproduce the bug"),
  2564. bugs_link
  2565. )
  2566. )
  2567. content.setOpenExternalLinks(True)
  2568. # palette
  2569. pal = QtGui.QPalette()
  2570. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2571. # layouts
  2572. main_layout = QtWidgets.QVBoxLayout()
  2573. self.setLayout(main_layout)
  2574. tab_layout = QtWidgets.QHBoxLayout()
  2575. buttons_hlay = QtWidgets.QHBoxLayout()
  2576. main_layout.addLayout(tab_layout)
  2577. main_layout.addLayout(buttons_hlay)
  2578. tab_widget = QtWidgets.QTabWidget()
  2579. tab_layout.addWidget(tab_widget)
  2580. closebtn = QtWidgets.QPushButton(_("Close"))
  2581. buttons_hlay.addStretch()
  2582. buttons_hlay.addWidget(closebtn)
  2583. # CONTRIBUTE section
  2584. self.intro_tab = QtWidgets.QWidget()
  2585. self.intro_tab_layout = QtWidgets.QHBoxLayout(self.intro_tab)
  2586. self.intro_tab_layout.setContentsMargins(2, 2, 2, 2)
  2587. tab_widget.addTab(self.intro_tab, _("Contribute"))
  2588. self.grid_lay = QtWidgets.QGridLayout()
  2589. self.grid_lay.setHorizontalSpacing(20)
  2590. self.grid_lay.setColumnStretch(0, 0)
  2591. self.grid_lay.setColumnStretch(1, 1)
  2592. intro_wdg = QtWidgets.QWidget()
  2593. intro_wdg.setLayout(self.grid_lay)
  2594. intro_scroll_area = QtWidgets.QScrollArea()
  2595. intro_scroll_area.setWidget(intro_wdg)
  2596. intro_scroll_area.setWidgetResizable(True)
  2597. intro_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2598. intro_scroll_area.setPalette(pal)
  2599. self.grid_lay.addWidget(logo, 0, 0)
  2600. self.grid_lay.addWidget(content, 0, 1)
  2601. self.intro_tab_layout.addWidget(intro_scroll_area)
  2602. # LINKS EXCHANGE section
  2603. self.links_tab = QtWidgets.QWidget()
  2604. self.links_tab_layout = QtWidgets.QVBoxLayout(self.links_tab)
  2605. self.links_tab_layout.setContentsMargins(2, 2, 2, 2)
  2606. tab_widget.addTab(self.links_tab, _("Links Exchange"))
  2607. self.links_lay = QtWidgets.QHBoxLayout()
  2608. links_wdg = QtWidgets.QWidget()
  2609. links_wdg.setLayout(self.links_lay)
  2610. links_scroll_area = QtWidgets.QScrollArea()
  2611. links_scroll_area.setWidget(links_wdg)
  2612. links_scroll_area.setWidgetResizable(True)
  2613. links_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2614. links_scroll_area.setPalette(pal)
  2615. self.links_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2616. self.links_tab_layout.addWidget(links_scroll_area)
  2617. # HOW TO section
  2618. self.howto_tab = QtWidgets.QWidget()
  2619. self.howto_tab_layout = QtWidgets.QVBoxLayout(self.howto_tab)
  2620. self.howto_tab_layout.setContentsMargins(2, 2, 2, 2)
  2621. tab_widget.addTab(self.howto_tab, _("How To's"))
  2622. self.howto_lay = QtWidgets.QHBoxLayout()
  2623. howto_wdg = QtWidgets.QWidget()
  2624. howto_wdg.setLayout(self.howto_lay)
  2625. howto_scroll_area = QtWidgets.QScrollArea()
  2626. howto_scroll_area.setWidget(howto_wdg)
  2627. howto_scroll_area.setWidgetResizable(True)
  2628. howto_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2629. howto_scroll_area.setPalette(pal)
  2630. self.howto_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2631. self.howto_tab_layout.addWidget(howto_scroll_area)
  2632. # BUTTONS section
  2633. closebtn.clicked.connect(self.accept)
  2634. ReadmeDialog(app=self, parent=self.ui).exec_()
  2635. def install_bookmarks(self, book_dict=None):
  2636. """
  2637. Install the bookmarks actions in the Help menu -> Bookmarks
  2638. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2639. :return: None
  2640. """
  2641. if book_dict is None:
  2642. self.defaults["global_bookmarks"].update(
  2643. {
  2644. '1': ['FlatCAM', "http://flatcam.org"],
  2645. '2': ['Backup Site', ""]
  2646. }
  2647. )
  2648. else:
  2649. self.defaults["global_bookmarks"].clear()
  2650. self.defaults["global_bookmarks"].update(book_dict)
  2651. # first try to disconnect if somehow they get connected from elsewhere
  2652. for act in self.ui.menuhelp_bookmarks.actions():
  2653. try:
  2654. act.triggered.disconnect()
  2655. except TypeError:
  2656. pass
  2657. # clear all actions except the last one who is the Bookmark manager
  2658. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2659. pass
  2660. else:
  2661. self.ui.menuhelp_bookmarks.removeAction(act)
  2662. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2663. if self.defaults["global_bookmarks"]:
  2664. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2665. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2666. # the JSON is first making the keys as strings (therefore I have to use strings too
  2667. # or do the conversion :(
  2668. # )
  2669. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2670. # the '10' entry jsut after '1' therefore ordering as strings
  2671. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2672. key=lambda x: int(x[0]))
  2673. for entry, bookmark in sorted_bookmarks:
  2674. title = bookmark[0]
  2675. weblink = bookmark[1]
  2676. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2677. act.setText(title)
  2678. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2679. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2680. if title == 'Backup Site' and weblink == "":
  2681. act.triggered.connect(self.on_backup_site)
  2682. else:
  2683. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2684. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2685. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2686. def on_bookmarks_manager(self):
  2687. """
  2688. Adds the bookmark manager in a Tab in Plot Area
  2689. :return:
  2690. """
  2691. for idx in range(self.ui.plot_tab_area.count()):
  2692. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2693. # there can be only one instance of Bookmark Manager at one time
  2694. return
  2695. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2696. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2697. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2698. # add the tab if it was closed
  2699. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2700. # delete the absolute and relative position and messages in the infobar
  2701. # self.ui.position_label.setText("")
  2702. # self.ui.rel_position_label.setText("")
  2703. # hide coordinates toolbars in the infobar while in DB
  2704. self.ui.coords_toolbar.hide()
  2705. self.ui.delta_coords_toolbar.hide()
  2706. # Switch plot_area to preferences page
  2707. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2708. def on_backup_site(self):
  2709. msgbox = QtWidgets.QMessageBox()
  2710. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2711. "1. FlatCAM.org website is down\n"
  2712. "2. Someone forked FlatCAM project and wants to point\n"
  2713. "to his own website\n\n"
  2714. "If you can't get any informations about FlatCAM beta\n"
  2715. "use the YouTube channel link from the Help menu."))
  2716. msgbox.setWindowTitle(_("Alternative website"))
  2717. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2718. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2719. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2720. msgbox.setDefaultButton(bt_yes)
  2721. msgbox.exec_()
  2722. # response = msgbox.clickedButton()
  2723. def on_file_savedefaults(self):
  2724. """
  2725. Callback for menu item File->Save Defaults. Saves application default options
  2726. ``self.defaults`` to current_defaults.FlatConfig.
  2727. :return: None
  2728. """
  2729. self.preferencesUiManager.save_defaults()
  2730. def final_save(self):
  2731. """
  2732. Callback for doing a preferences save to file whenever the application is about to quit.
  2733. If the project has changes, it will ask the user to save the project.
  2734. :return: None
  2735. """
  2736. if self.save_in_progress:
  2737. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2738. return
  2739. if self.should_we_save and self.collection.get_list():
  2740. msgbox = QtWidgets.QMessageBox()
  2741. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2742. "\n"
  2743. "Do you want to Save the project?"))
  2744. msgbox.setWindowTitle(_("Save changes"))
  2745. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2746. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2747. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2748. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2749. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2750. msgbox.setDefaultButton(bt_yes)
  2751. msgbox.exec_()
  2752. response = msgbox.clickedButton()
  2753. if response == bt_yes:
  2754. try:
  2755. self.trayIcon.hide()
  2756. except Exception:
  2757. pass
  2758. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2759. elif response == bt_no:
  2760. try:
  2761. self.trayIcon.hide()
  2762. except Exception:
  2763. pass
  2764. self.quit_application()
  2765. elif response == bt_cancel:
  2766. return
  2767. else:
  2768. try:
  2769. self.trayIcon.hide()
  2770. except Exception:
  2771. pass
  2772. self.quit_application()
  2773. def quit_application(self):
  2774. """
  2775. Called (as a pyslot or not) when the application is quit.
  2776. :return: None
  2777. """
  2778. # close editors before quiting the app, if they are open
  2779. if self.geo_editor.editor_active is True:
  2780. self.geo_editor.deactivate()
  2781. try:
  2782. self.geo_editor.disconnect()
  2783. except TypeError:
  2784. pass
  2785. log.debug("App.quit_application() --> Geo Editor deactivated.")
  2786. if self.exc_editor.editor_active is True:
  2787. self.exc_editor.deactivate()
  2788. try:
  2789. self.grb_editor.disconnect()
  2790. except TypeError:
  2791. pass
  2792. log.debug("App.quit_application() --> Excellon Editor deactivated.")
  2793. if self.grb_editor.editor_active is True:
  2794. self.grb_editor.deactivate_grb_editor()
  2795. try:
  2796. self.exc_editor.disconnect()
  2797. except TypeError:
  2798. pass
  2799. log.debug("App.quit_application() --> Gerber Editor deactivated.")
  2800. # disconnect the mouse events
  2801. if self.is_legacy:
  2802. self.plotcanvas.graph_event_disconnect(self.mm)
  2803. self.plotcanvas.graph_event_disconnect(self.mp)
  2804. self.plotcanvas.graph_event_disconnect(self.mr)
  2805. self.plotcanvas.graph_event_disconnect(self.mdc)
  2806. self.plotcanvas.graph_event_disconnect(self.kp)
  2807. else:
  2808. self.mm = self.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move_over_plot)
  2809. self.mp = self.plotcanvas.graph_event_disconnect('mouse_press', self.on_mouse_click_over_plot)
  2810. self.mr = self.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release_over_plot)
  2811. self.mdc = self.plotcanvas.graph_event_disconnect('mouse_double_click',
  2812. self.on_mouse_double_click_over_plot)
  2813. self.kp = self.plotcanvas.graph_event_disconnect('key_press', self.ui.keyPressEvent)
  2814. self.preferencesUiManager.save_defaults(silent=True)
  2815. log.debug("App.quit_application() --> App Defaults saved.")
  2816. if self.cmd_line_headless != 1:
  2817. # save app state to file
  2818. stgs = QSettings("Open Source", "FlatCAM")
  2819. stgs.setValue('saved_gui_state', self.ui.saveState())
  2820. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2821. stgs.setValue(
  2822. 'language',
  2823. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2824. )
  2825. stgs.setValue(
  2826. 'notebook_font_size',
  2827. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2828. )
  2829. stgs.setValue(
  2830. 'axis_font_size',
  2831. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2832. )
  2833. stgs.setValue(
  2834. 'textbox_font_size',
  2835. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2836. )
  2837. stgs.setValue(
  2838. 'hud_font_size',
  2839. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2840. )
  2841. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2842. stgs.setValue(
  2843. 'machinist',
  2844. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2845. )
  2846. # This will write the setting to the platform specific storage.
  2847. del stgs
  2848. log.debug("App.quit_application() --> App UI state saved.")
  2849. # try to quit the Socket opened by ArgsThread class
  2850. try:
  2851. # self.new_launch.thread_exit = True
  2852. # self.new_launch.listener.close()
  2853. self.new_launch.stop.emit()
  2854. except Exception as err:
  2855. log.debug("App.quit_application() --> %s" % str(err))
  2856. # try to quit the QThread that run ArgsThread class
  2857. try:
  2858. # del self.new_launch
  2859. self.listen_th.quit()
  2860. except Exception as e:
  2861. log.debug("App.quit_application() --> %s" % str(e))
  2862. # terminate workers
  2863. # self.workers.__del__()
  2864. self.clear_pool()
  2865. # quit app by signalling for self.kill_app() method
  2866. # self.close_app_signal.emit()
  2867. QtWidgets.qApp.quit()
  2868. sys.exit(0)
  2869. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2870. # we use the following command
  2871. # minor_v = sys.version_info.minor
  2872. # if minor_v < 8:
  2873. # # make sure that the app closes
  2874. # sys.exit(0)
  2875. # else:
  2876. # os._exit(0) # fix to work with Python 3.8
  2877. @staticmethod
  2878. def kill_app():
  2879. QtWidgets.qApp.quit()
  2880. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2881. # we use the following command
  2882. sys.exit(0)
  2883. def on_portable_checked(self, state):
  2884. """
  2885. Callback called when the checkbox in Preferences GUI is checked.
  2886. It will set the application as portable by creating the preferences and recent files in the
  2887. 'config' folder found in the FlatCAM installation folder.
  2888. :param state: boolean, the state of the checkbox when clicked/checked
  2889. :return:
  2890. """
  2891. line_no = 0
  2892. data = None
  2893. if sys.platform != 'win32':
  2894. # this won't work in Linux or MacOS
  2895. return
  2896. # test if the app was frozen and choose the path for the configuration file
  2897. if getattr(sys, "frozen", False) is True:
  2898. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2899. else:
  2900. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2901. config_file = current_data_path + '\\configuration.txt'
  2902. try:
  2903. with open(config_file, 'r') as f:
  2904. try:
  2905. data = f.readlines()
  2906. except Exception as e:
  2907. log.debug('App.__init__() -->%s' % str(e))
  2908. return
  2909. except FileNotFoundError:
  2910. pass
  2911. for line in data:
  2912. line = line.strip('\n')
  2913. param = str(line).rpartition('=')
  2914. if param[0] == 'portable':
  2915. break
  2916. line_no += 1
  2917. if state:
  2918. data[line_no] = 'portable=True\n'
  2919. # create the new defauults files
  2920. # create current_defaults.FlatConfig file if there is none
  2921. try:
  2922. f = open(current_data_path + '/current_defaults.FlatConfig')
  2923. f.close()
  2924. except IOError:
  2925. App.log.debug('Creating empty current_defaults.FlatConfig')
  2926. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2927. json.dump({}, f)
  2928. f.close()
  2929. # create factory_defaults.FlatConfig file if there is none
  2930. try:
  2931. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2932. f.close()
  2933. except IOError:
  2934. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2935. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2936. json.dump({}, f)
  2937. f.close()
  2938. try:
  2939. f = open(current_data_path + '/recent.json')
  2940. f.close()
  2941. except IOError:
  2942. App.log.debug('Creating empty recent.json')
  2943. f = open(current_data_path + '/recent.json', 'w')
  2944. json.dump([], f)
  2945. f.close()
  2946. try:
  2947. fp = open(current_data_path + '/recent_projects.json')
  2948. fp.close()
  2949. except IOError:
  2950. App.log.debug('Creating empty recent_projects.json')
  2951. fp = open(current_data_path + '/recent_projects.json', 'w')
  2952. json.dump([], fp)
  2953. fp.close()
  2954. # save the current defaults to the new defaults file
  2955. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2956. else:
  2957. data[line_no] = 'portable=False\n'
  2958. with open(config_file, 'w') as f:
  2959. f.writelines(data)
  2960. def on_register_files(self, obj_type=None):
  2961. """
  2962. Called whenever there is a need to register file extensions with FlatCAM.
  2963. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2964. :param obj_type: the type of object to be register for.
  2965. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2966. :return: None
  2967. """
  2968. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2969. new_reg_path = 'Software\\Classes\\'
  2970. # find if the current user is admin
  2971. try:
  2972. is_admin = os.getuid() == 0
  2973. except AttributeError:
  2974. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2975. if is_admin is True:
  2976. root_path = winreg.HKEY_LOCAL_MACHINE
  2977. else:
  2978. root_path = winreg.HKEY_CURRENT_USER
  2979. # create the keys
  2980. def set_reg(name, root_pth, new_reg_path, value):
  2981. try:
  2982. winreg.CreateKey(root_pth, new_reg_path)
  2983. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  2984. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2985. return True
  2986. except WindowsError:
  2987. return False
  2988. # delete key in registry
  2989. def delete_reg(root_pth, reg_path, key_to_del):
  2990. key_to_del_path = reg_path + key_to_del
  2991. try:
  2992. winreg.DeleteKey(root_pth, key_to_del_path)
  2993. return True
  2994. except WindowsError:
  2995. return False
  2996. if obj_type is None or obj_type == 'excellon':
  2997. exc_list = \
  2998. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2999. exc_list = [x for x in exc_list if x != '']
  3000. # register all keys in the Preferences window
  3001. for ext in exc_list:
  3002. new_k = new_reg_path + '.%s' % ext
  3003. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3004. # and unregister those that are no longer in the Preferences windows but are in the file
  3005. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3006. if ext not in exc_list:
  3007. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3008. # now write the updated extensions to the self.defaults
  3009. # new_ext = ''
  3010. # for ext in exc_list:
  3011. # new_ext = new_ext + ext + ', '
  3012. # self.defaults["fa_excellon"] = new_ext
  3013. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3014. if obj_type is None or obj_type == 'gcode':
  3015. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3016. gco_list = [x for x in gco_list if x != '']
  3017. # register all keys in the Preferences window
  3018. for ext in gco_list:
  3019. new_k = new_reg_path + '.%s' % ext
  3020. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3021. # and unregister those that are no longer in the Preferences windows but are in the file
  3022. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3023. if ext not in gco_list:
  3024. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3025. # now write the updated extensions to the self.defaults
  3026. # new_ext = ''
  3027. # for ext in gco_list:
  3028. # new_ext = new_ext + ext + ', '
  3029. # self.defaults["fa_gcode"] = new_ext
  3030. self.inform.emit('[success] %s' %
  3031. _("Selected GCode file extensions registered with FlatCAM."))
  3032. if obj_type is None or obj_type == 'gerber':
  3033. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3034. grb_list = [x for x in grb_list if x != '']
  3035. # register all keys in the Preferences window
  3036. for ext in grb_list:
  3037. new_k = new_reg_path + '.%s' % ext
  3038. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3039. # and unregister those that are no longer in the Preferences windows but are in the file
  3040. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3041. if ext not in grb_list:
  3042. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3043. # now write the updated extensions to the self.defaults
  3044. # new_ext = ''
  3045. # for ext in grb_list:
  3046. # new_ext = new_ext + ext + ', '
  3047. # self.defaults["fa_gerber"] = new_ext
  3048. self.inform.emit('[success] %s' %
  3049. _("Selected Gerber file extensions registered with FlatCAM."))
  3050. def add_extension(self, ext_type):
  3051. """
  3052. Add a file extension to the list for a specific object
  3053. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3054. :return:
  3055. """
  3056. if ext_type == 'excellon':
  3057. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3058. if new_ext == '':
  3059. return
  3060. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3061. if new_ext in old_val:
  3062. return
  3063. old_val.append(new_ext)
  3064. old_val.sort()
  3065. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3066. if ext_type == 'gcode':
  3067. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3068. if new_ext == '':
  3069. return
  3070. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3071. if new_ext in old_val:
  3072. return
  3073. old_val.append(new_ext)
  3074. old_val.sort()
  3075. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3076. if ext_type == 'gerber':
  3077. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3078. if new_ext == '':
  3079. return
  3080. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3081. if new_ext in old_val:
  3082. return
  3083. old_val.append(new_ext)
  3084. old_val.sort()
  3085. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3086. if ext_type == 'keyword':
  3087. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3088. if new_kw == '':
  3089. return
  3090. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3091. if new_kw in old_val:
  3092. return
  3093. old_val.append(new_kw)
  3094. old_val.sort()
  3095. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3096. # update the self.myKeywords so the model is updated
  3097. self.autocomplete_kw_list = \
  3098. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3099. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3100. self.shell._edit.set_model_data(self.myKeywords)
  3101. def del_extension(self, ext_type):
  3102. """
  3103. Remove a file extension from the list for a specific object
  3104. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3105. :return:
  3106. """
  3107. if ext_type == 'excellon':
  3108. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3109. if new_ext == '':
  3110. return
  3111. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3112. if new_ext not in old_val:
  3113. return
  3114. old_val.remove(new_ext)
  3115. old_val.sort()
  3116. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3117. if ext_type == 'gcode':
  3118. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3119. if new_ext == '':
  3120. return
  3121. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3122. if new_ext not in old_val:
  3123. return
  3124. old_val.remove(new_ext)
  3125. old_val.sort()
  3126. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3127. if ext_type == 'gerber':
  3128. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3129. if new_ext == '':
  3130. return
  3131. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3132. if new_ext not in old_val:
  3133. return
  3134. old_val.remove(new_ext)
  3135. old_val.sort()
  3136. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3137. if ext_type == 'keyword':
  3138. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3139. if new_kw == '':
  3140. return
  3141. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3142. if new_kw not in old_val:
  3143. return
  3144. old_val.remove(new_kw)
  3145. old_val.sort()
  3146. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3147. # update the self.myKeywords so the model is updated
  3148. self.autocomplete_kw_list = \
  3149. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3150. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3151. self.shell._edit.set_model_data(self.myKeywords)
  3152. def restore_extensions(self, ext_type):
  3153. """
  3154. Restore all file extensions associations with FlatCAM, for a specific object
  3155. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3156. :return:
  3157. """
  3158. if ext_type == 'excellon':
  3159. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3160. # for the ability to open Excellon files with .txt extension
  3161. new_exc_list = deepcopy(self.exc_list)
  3162. try:
  3163. new_exc_list.remove('txt')
  3164. except ValueError:
  3165. pass
  3166. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3167. if ext_type == 'gcode':
  3168. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3169. if ext_type == 'gerber':
  3170. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3171. if ext_type == 'keyword':
  3172. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3173. # update the self.myKeywords so the model is updated
  3174. self.autocomplete_kw_list = self.default_keywords
  3175. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3176. self.shell._edit.set_model_data(self.myKeywords)
  3177. def delete_all_extensions(self, ext_type):
  3178. """
  3179. Delete all file extensions associations with FlatCAM, for a specific object
  3180. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3181. :return:
  3182. """
  3183. if ext_type == 'excellon':
  3184. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3185. if ext_type == 'gcode':
  3186. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3187. if ext_type == 'gerber':
  3188. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3189. if ext_type == 'keyword':
  3190. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3191. # update the self.myKeywords so the model is updated
  3192. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3193. self.shell._edit.set_model_data(self.myKeywords)
  3194. def on_edit_join(self, name=None):
  3195. """
  3196. Callback for Edit->Join. Joins the selected geometry objects into
  3197. a new one.
  3198. :return: None
  3199. """
  3200. self.defaults.report_usage("on_edit_join()")
  3201. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3202. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3203. geo_type_set = set()
  3204. objs = self.collection.get_selected()
  3205. if len(objs) < 2:
  3206. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3207. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3208. return 'fail'
  3209. for obj in objs:
  3210. geo_type_set.add(obj.multigeo)
  3211. # if len(geo_type_list) == 1 means that all list elements are the same
  3212. if len(geo_type_set) != 1:
  3213. self.inform.emit('[ERROR] %s' %
  3214. _("Failed join. The Geometry objects are of different types.\n"
  3215. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3216. "convert from one to another and retry joining \n"
  3217. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3218. "the result may not be what was expected. \n"
  3219. "Check the generated GCODE."))
  3220. return
  3221. fuse_tools = self.defaults["geometry_merge_fuse_tools"]
  3222. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3223. if True in geo_type_set:
  3224. def initialize(geo_obj, app):
  3225. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True, fuse_tools=fuse_tools)
  3226. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3227. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3228. for v in geo_obj.tools.values():
  3229. v['data']['name'] = obj_name_multi
  3230. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  3231. else:
  3232. def initialize(geo_obj, app):
  3233. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False, fuse_tools=fuse_tools)
  3234. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3235. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3236. for v in geo_obj.tools.values():
  3237. v['data']['name'] = obj_name_single
  3238. self.app_obj.new_object("geometry", obj_name_single, initialize)
  3239. self.should_we_save = True
  3240. def on_edit_join_exc(self):
  3241. """
  3242. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3243. a new Excellon.
  3244. :return: None
  3245. """
  3246. self.defaults.report_usage("on_edit_join_exc()")
  3247. objs = self.collection.get_selected()
  3248. for obj in objs:
  3249. if not isinstance(obj, ExcellonObject):
  3250. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3251. return
  3252. if len(objs) < 2:
  3253. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3254. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3255. return 'fail'
  3256. fuse_tools = self.defaults["excellon_merge_fuse_tools"]
  3257. def initialize(exc_obj, app):
  3258. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals, fuse_tools=fuse_tools)
  3259. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3260. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  3261. self.should_we_save = True
  3262. def on_edit_join_grb(self):
  3263. """
  3264. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3265. a new Gerber object.
  3266. :return: None
  3267. """
  3268. self.defaults.report_usage("on_edit_join_grb()")
  3269. objs = self.collection.get_selected()
  3270. for obj in objs:
  3271. if not isinstance(obj, GerberObject):
  3272. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3273. return
  3274. if len(objs) < 2:
  3275. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3276. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3277. return 'fail'
  3278. def initialize(grb_obj, app):
  3279. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3280. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3281. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3282. self.should_we_save = True
  3283. def on_convert_singlegeo_to_multigeo(self):
  3284. """
  3285. Called for converting a Geometry object from single-geo to multi-geo.
  3286. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3287. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3288. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3289. the solid-geometry of that tool.
  3290. :return: None
  3291. """
  3292. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3293. obj = self.collection.get_active()
  3294. if obj is None:
  3295. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3296. return
  3297. if not isinstance(obj, GeometryObject):
  3298. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3299. return
  3300. obj.multigeo = True
  3301. for tooluid, dict_value in obj.tools.items():
  3302. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3303. if not isinstance(obj.solid_geometry, list):
  3304. obj.solid_geometry = [obj.solid_geometry]
  3305. # obj.solid_geometry[:] = []
  3306. obj.plot()
  3307. self.should_we_save = True
  3308. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3309. def on_convert_multigeo_to_singlegeo(self):
  3310. """
  3311. Called for converting a Geometry object from multi-geo to single-geo.
  3312. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3313. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3314. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3315. the solid-geometry of that tool.
  3316. :return: None
  3317. """
  3318. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3319. obj = self.collection.get_active()
  3320. if obj is None:
  3321. self.inform.emit('[ERROR_NOTCL] %s' %
  3322. _("Failed. Select a Geometry Object and try again."))
  3323. return
  3324. if not isinstance(obj, GeometryObject):
  3325. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3326. (_("Expected a GeometryObject, got"), type(obj)))
  3327. return
  3328. obj.multigeo = False
  3329. total_solid_geometry = []
  3330. for tooluid, dict_value in obj.tools.items():
  3331. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3332. # clear the original geometry
  3333. dict_value['solid_geometry'][:] = []
  3334. obj.solid_geometry = deepcopy(total_solid_geometry)
  3335. obj.plot()
  3336. self.should_we_save = True
  3337. self.inform.emit('[success] %s' %
  3338. _("A Geometry object was converted to SingleGeo type."))
  3339. def on_defaults_dict_change(self, field):
  3340. """
  3341. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3342. Edit -> Preferences tab window.
  3343. :param field: the key of the self.defaults dictionary that was changed.
  3344. :return: None
  3345. """
  3346. self.preferencesUiManager.defaults_write_form_field(field=field)
  3347. if field == "units":
  3348. self.set_screen_units(self.defaults['units'])
  3349. def set_screen_units(self, units):
  3350. """
  3351. Set the FlatCAM units on the status bar.
  3352. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3353. :return: None
  3354. """
  3355. self.ui.units_label.setText("[" + units.lower() + "]")
  3356. def on_toggle_units_click(self):
  3357. try:
  3358. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3359. except (TypeError, AttributeError):
  3360. pass
  3361. if self.defaults["units"] == 'MM':
  3362. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3363. else:
  3364. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3365. self.on_toggle_units(no_pref=True)
  3366. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3367. lambda: self.on_toggle_units(no_pref=False))
  3368. def on_toggle_units(self, no_pref=False):
  3369. """
  3370. Callback for the Units radio-button change in the Preferences tab.
  3371. Changes the application's default units adn for the project too.
  3372. If changing the project's units, the change propagates to all of
  3373. the objects in the project.
  3374. :return: None
  3375. """
  3376. self.defaults.report_usage("on_toggle_units")
  3377. if self.toggle_units_ignore:
  3378. return
  3379. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3380. # If option is the same, then ignore
  3381. if new_units == self.defaults["units"].upper():
  3382. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3383. return
  3384. # Keys in self.defaults for which to scale their values
  3385. dimensions = ['tools_iso_tooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3386. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3387. "tools_iso_tool_vtipdia",
  3388. "tools_iso_tool_cutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3389. "gerber_editor_ma_high",
  3390. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3391. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3392. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3393. "excellon_feedrate_probe", "excellon_milling_dia",
  3394. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3395. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3396. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3397. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3398. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3399. "geometry_extracut_length", "geometry_z_pdepth",
  3400. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3401. 'cncjob_tooldia',
  3402. 'tools_paintoffset', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3403. "tools_paintnewdia",
  3404. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3405. "tools_nccnewdia", "tools_ncc_offset_value",
  3406. "tools_2sided_drilldia",
  3407. "tools_film_boundary", "tools_film_scale_stroke",
  3408. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3409. "tools_cutout_depthperpass",
  3410. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3411. "tools_panelize_spacing_rows",
  3412. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3413. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3414. "tools_transform_buffer_dis",
  3415. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3416. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3417. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3418. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3419. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3420. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3421. "tools_cr_h2h_val", "tools_cr_dh_val",
  3422. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3423. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3424. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3425. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3426. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3427. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3428. "tools_copper_thieving_mask_clearance",
  3429. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3430. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3431. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3432. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3433. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3434. "tools_invert_margin",
  3435. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3436. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3437. def scale_defaults(sfactor):
  3438. for dim in dimensions:
  3439. if dim in [
  3440. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3441. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3442. 'tools_transform_mirror_point'
  3443. ]:
  3444. if self.defaults[dim] is None or self.defaults[dim] == '':
  3445. continue
  3446. try:
  3447. coordinates = self.defaults[dim].split(",")
  3448. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3449. coords_xy[0] *= sfactor
  3450. coords_xy[1] *= sfactor
  3451. self.defaults[dim] = "%.*f, %.*f" % (
  3452. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3453. except Exception as e:
  3454. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3455. elif dim in [
  3456. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3457. ]:
  3458. if self.defaults[dim] is None or self.defaults[dim] == '':
  3459. continue
  3460. try:
  3461. self.defaults[dim] = float(self.defaults[dim])
  3462. tools_diameters = [self.defaults[dim]]
  3463. except ValueError:
  3464. try:
  3465. tools_string = self.defaults[dim].split(",")
  3466. tools_diameters = [eval(a) for a in tools_string if a != '']
  3467. except Exception as e:
  3468. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3469. continue
  3470. self.defaults[dim] = ''
  3471. td_len = len(tools_diameters)
  3472. if td_len > 1:
  3473. for t in range(td_len):
  3474. tools_diameters[t] *= sfactor
  3475. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3476. else:
  3477. tools_diameters[0] *= sfactor
  3478. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3479. elif dim in ['global_gridx', 'global_gridy']:
  3480. # format the number of decimals to the one specified in self.decimals
  3481. try:
  3482. val = float(self.defaults[dim]) * sfactor
  3483. except Exception as e:
  3484. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3485. continue
  3486. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3487. else:
  3488. # the number of decimals for the rest is kept unchanged
  3489. if self.defaults[dim]:
  3490. try:
  3491. val = float(self.defaults[dim]) * sfactor
  3492. except Exception as e:
  3493. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3494. continue
  3495. self.defaults[dim] = val
  3496. # The scaling factor depending on choice of units.
  3497. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3498. # Changing project units. Warn user.
  3499. msgbox = QtWidgets.QMessageBox()
  3500. msgbox.setWindowTitle(_("Toggle Units"))
  3501. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3502. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3503. msgbox.setText(_("Changing the units of the project\n"
  3504. "will scale all objects.\n\n"
  3505. "Do you want to continue?"))
  3506. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3507. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3508. msgbox.setDefaultButton(bt_ok)
  3509. msgbox.exec_()
  3510. response = msgbox.clickedButton()
  3511. if response == bt_ok:
  3512. if no_pref is False:
  3513. self.preferencesUiManager.defaults_read_form()
  3514. scale_defaults(factor)
  3515. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3516. self.defaults["units"] = new_units
  3517. # update the defaults from form, some may assume that the conversion is enough and it's not
  3518. self.on_options_app2project()
  3519. # update the objects
  3520. for obj in self.collection.get_list():
  3521. obj.convert_units(new_units)
  3522. # make that the properties stored in the object are also updated
  3523. self.app_obj.object_changed.emit(obj)
  3524. # rebuild the object UI
  3525. obj.build_ui()
  3526. # change this only if the workspace is active
  3527. if self.defaults['global_workspace'] is True:
  3528. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3529. # adjust the grid values on the main toolbar
  3530. val_x = float(self.defaults['global_gridx']) * factor
  3531. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3532. current = self.collection.get_active()
  3533. if current is not None:
  3534. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3535. if not isinstance(current, GeometryObject):
  3536. current.to_form()
  3537. # replot all objects
  3538. self.plot_all()
  3539. # set the status labels to reflect the current FlatCAM units
  3540. self.set_screen_units(new_units)
  3541. # signal to the app that we changed the object properties and it should save the project
  3542. self.should_we_save = True
  3543. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3544. else:
  3545. # Undo toggling
  3546. self.toggle_units_ignore = True
  3547. if self.defaults['units'].upper() == 'MM':
  3548. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3549. else:
  3550. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3551. self.toggle_units_ignore = False
  3552. # store the grid values so they are not changed in the next step
  3553. val_x = float(self.defaults['global_gridx'])
  3554. val_y = float(self.defaults['global_gridy'])
  3555. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  3556. self.preferencesUiManager.defaults_read_form()
  3557. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3558. # in self.defaults from the GUI elements but
  3559. # I don't want it for the grid values, so I update them here
  3560. self.defaults['global_gridx'] = val_x
  3561. self.defaults['global_gridy'] = val_y
  3562. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3563. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3564. def on_deselect_all(self):
  3565. self.collection.set_all_inactive()
  3566. self.delete_selection_shape()
  3567. def on_workspace_modified(self):
  3568. # self.save_defaults(silent=True)
  3569. self.plotcanvas.delete_workspace()
  3570. self.preferencesUiManager.defaults_read_form()
  3571. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3572. def on_workspace(self):
  3573. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3574. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3575. self.inform[str, bool].emit(_("Workspace enabled."), False)
  3576. else:
  3577. self.plotcanvas.delete_workspace()
  3578. self.inform[str, bool].emit(_("Workspace disabled."), False)
  3579. self.preferencesUiManager.defaults_read_form()
  3580. # self.save_defaults(silent=True)
  3581. def on_workspace_toggle(self):
  3582. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3583. try:
  3584. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3585. except TypeError:
  3586. pass
  3587. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3588. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3589. self.on_workspace()
  3590. def on_cursor_type(self, val):
  3591. """
  3592. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3593. :return: None
  3594. """
  3595. self.app_cursor.enabled = False
  3596. if val == 'small':
  3597. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3598. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3599. self.app_cursor = self.plotcanvas.new_cursor()
  3600. else:
  3601. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3602. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3603. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3604. if self.ui.grid_snap_btn.isChecked():
  3605. self.app_cursor.enabled = True
  3606. else:
  3607. self.app_cursor.enabled = False
  3608. def on_tool_add_keypress(self):
  3609. # ## Current application units in Upper Case
  3610. self.units = self.defaults['units'].upper()
  3611. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3612. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3613. if notebook_widget_name == 'selected_tab':
  3614. if self.collection.get_active().kind == 'geometry':
  3615. # Tool add works for Geometry only if Advanced is True in Preferences
  3616. if self.defaults["global_app_level"] == 'a':
  3617. tool_add_popup = FCInputDialog(title="New Tool ...",
  3618. text='Enter a Tool Diameter:',
  3619. min=0.0000, max=99.9999, decimals=4)
  3620. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3621. val, ok = tool_add_popup.get_value()
  3622. if ok:
  3623. if float(val) == 0:
  3624. self.inform.emit('[WARNING_NOTCL] %s' %
  3625. _("Please enter a tool diameter with non-zero value, in Float format."))
  3626. return
  3627. self.collection.get_active().on_tool_add(dia=float(val))
  3628. else:
  3629. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3630. else:
  3631. msgbox = QtWidgets.QMessageBox()
  3632. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3633. "Go to Preferences -> General - Show Advanced Options."))
  3634. msgbox.setWindowTitle("Tool adding ...")
  3635. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3636. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  3637. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3638. msgbox.setDefaultButton(bt_ok)
  3639. msgbox.exec_()
  3640. # work only if the notebook tab on focus is the Tools_Tab
  3641. if notebook_widget_name == 'tool_tab':
  3642. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3643. # and only if the tool is NCC Tool
  3644. if tool_widget == self.ncclear_tool.toolName:
  3645. self.ncclear_tool.on_add_tool_by_key()
  3646. # and only if the tool is Paint Area Tool
  3647. elif tool_widget == self.paint_tool.toolName:
  3648. self.paint_tool.on_add_tool_by_key()
  3649. # and only if the tool is Solder Paste Dispensing Tool
  3650. elif tool_widget == self.paste_tool.toolName:
  3651. self.paste_tool.on_add_tool_by_key()
  3652. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3653. # See description below.
  3654. def on_delete_keypress(self):
  3655. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3656. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3657. if notebook_widget_name == 'selected_tab':
  3658. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3659. self.collection.get_active().on_tool_delete()
  3660. # work only if the notebook tab on focus is the Tools_Tab
  3661. elif notebook_widget_name == 'tool_tab':
  3662. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3663. # and only if the tool is NCC Tool
  3664. if tool_widget == self.ncclear_tool.toolName:
  3665. self.ncclear_tool.on_tool_delete()
  3666. # and only if the tool is Paint Tool
  3667. elif tool_widget == self.paint_tool.toolName:
  3668. self.paint_tool.on_tool_delete()
  3669. # and only if the tool is Solder Paste Dispensing Tool
  3670. elif tool_widget == self.paste_tool.toolName:
  3671. self.paste_tool.on_tool_delete()
  3672. # and only if the tool is Isolation Tool
  3673. elif tool_widget == self.isolation_tool.toolName:
  3674. self.isolation_tool.on_tool_delete()
  3675. else:
  3676. self.on_delete()
  3677. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3678. # some screens you have to be careful where you hover with your mouse.
  3679. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3680. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3681. # Complicated, I know :)
  3682. def on_delete(self, force_deletion=False):
  3683. """
  3684. Delete the currently selected FlatCAMObjs.
  3685. :param force_deletion: used by Tcl command
  3686. :return: None
  3687. """
  3688. self.defaults.report_usage("on_delete()")
  3689. response = None
  3690. bt_ok = None
  3691. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3692. # a geometry object before we update it.
  3693. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3694. and self.grb_editor.editor_active is False and self.gcode_editor.editor_active is False:
  3695. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3696. msgbox = QtWidgets.QMessageBox()
  3697. msgbox.setWindowTitle(_("Delete objects"))
  3698. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3699. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3700. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3701. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3702. "the selected objects?"))
  3703. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3704. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3705. msgbox.setDefaultButton(bt_ok)
  3706. msgbox.exec_()
  3707. response = msgbox.clickedButton()
  3708. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3709. response = bt_ok
  3710. if response == bt_ok:
  3711. if self.collection.get_active():
  3712. self.log.debug("App.on_delete()")
  3713. for obj_active in self.collection.get_selected():
  3714. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3715. if obj_active.kind == 'gerber':
  3716. obj_active.mark_shapes_storage.clear()
  3717. obj_active.mark_shapes.clear(update=True)
  3718. obj_active.mark_shapes.enabled = False
  3719. elif obj_active.kind == 'cncjob':
  3720. try:
  3721. obj_active.text_col.enabled = False
  3722. del obj_active.text_col
  3723. obj_active.annotation.clear(update=True)
  3724. del obj_active.annotation
  3725. except AttributeError as e:
  3726. log.debug(
  3727. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3728. )
  3729. while self.collection.get_selected():
  3730. self.delete_first_selected()
  3731. # make sure that the selection shape is deleted, too
  3732. self.delete_selection_shape()
  3733. # if there are no longer objects delete also the exclusion areas shapes
  3734. if not self.collection.get_list():
  3735. self.exc_areas.clear_shapes()
  3736. self.inform.emit('%s...' % _("Object(s) deleted"))
  3737. else:
  3738. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3739. else:
  3740. self.inform.emit(_("Save the work in Editor and try again ..."))
  3741. def delete_first_selected(self):
  3742. # Keep this for later
  3743. try:
  3744. sel_obj = self.collection.get_active()
  3745. name = sel_obj.options["name"]
  3746. isPlotted = sel_obj.options["plot"]
  3747. except AttributeError:
  3748. self.log.debug("Nothing selected for deletion")
  3749. return
  3750. if self.is_legacy is True:
  3751. # Remove plot only if the object was plotted otherwise delaxes will fail
  3752. if isPlotted:
  3753. try:
  3754. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3755. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3756. except Exception as e:
  3757. log.debug("App.delete_first_selected() --> %s" % str(e))
  3758. self.plotcanvas.auto_adjust_axes()
  3759. # Remove from dictionary
  3760. self.collection.delete_active()
  3761. # Clear form
  3762. self.setup_component_editor()
  3763. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3764. def on_set_origin(self):
  3765. """
  3766. Set the origin to the left mouse click position
  3767. :return: None
  3768. """
  3769. # display the message for the user
  3770. # and ask him to click on the desired position
  3771. self.defaults.report_usage("on_set_origin()")
  3772. def origin_replot():
  3773. def worker_task():
  3774. with self.proc_container.new('%s...' % _("Plotting")):
  3775. for obj in self.collection.get_list():
  3776. obj.plot()
  3777. self.plotcanvas.fit_view()
  3778. if self.is_legacy:
  3779. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3780. else:
  3781. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3782. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3783. self.inform.emit(_('Click to set the origin ...'))
  3784. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3785. # first disconnect it as it may have been used by something else
  3786. try:
  3787. self.replot_signal.disconnect()
  3788. except TypeError:
  3789. pass
  3790. self.replot_signal[list].connect(origin_replot)
  3791. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3792. """
  3793. :param event:
  3794. :param location:
  3795. :param noplot:
  3796. :param use_thread:
  3797. :return:
  3798. """
  3799. noplot_sig = noplot
  3800. def worker_task():
  3801. with self.proc_container.new(_("Setting Origin...")):
  3802. obj_list = self.collection.get_list()
  3803. for obj in obj_list:
  3804. obj.offset((x, y))
  3805. self.app_obj.object_changed.emit(obj)
  3806. # Update the object bounding box options
  3807. a, b, c, d = obj.bounds()
  3808. obj.options['xmin'] = a
  3809. obj.options['ymin'] = b
  3810. obj.options['xmax'] = c
  3811. obj.options['ymax'] = d
  3812. self.inform.emit('[success] %s...' % _('Origin set'))
  3813. for obj in obj_list:
  3814. out_name = obj.options["name"]
  3815. if obj.kind == 'gerber':
  3816. obj.source_file = self.export_gerber(
  3817. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3818. elif obj.kind == 'excellon':
  3819. obj.source_file = self.export_excellon(
  3820. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3821. if noplot_sig is False:
  3822. self.replot_signal.emit([])
  3823. if location is not None:
  3824. if len(location) != 2:
  3825. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3826. return 'fail'
  3827. x, y = location
  3828. if use_thread is True:
  3829. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3830. else:
  3831. worker_task()
  3832. self.should_we_save = True
  3833. return
  3834. if event is not None and event.button == 1:
  3835. if self.is_legacy is False:
  3836. event_pos = event.pos
  3837. else:
  3838. event_pos = (event.xdata, event.ydata)
  3839. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3840. if self.grid_status():
  3841. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3842. else:
  3843. pos = pos_canvas
  3844. x = 0 - pos[0]
  3845. y = 0 - pos[1]
  3846. if use_thread is True:
  3847. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3848. else:
  3849. worker_task()
  3850. self.should_we_save = True
  3851. def on_move2origin(self, use_thread=True):
  3852. """
  3853. Move selected objects to origin.
  3854. :param use_thread: Control if to use threaded operation. Boolean.
  3855. :return:
  3856. """
  3857. def worker_task():
  3858. with self.proc_container.new(_("Moving to Origin...")):
  3859. obj_list = self.collection.get_selected()
  3860. if not obj_list:
  3861. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3862. return
  3863. xminlist = []
  3864. yminlist = []
  3865. # first get a bounding box to fit all
  3866. for obj in obj_list:
  3867. xmin, ymin, xmax, ymax = obj.bounds()
  3868. xminlist.append(xmin)
  3869. yminlist.append(ymin)
  3870. # get the minimum x,y for all objects selected
  3871. x = min(xminlist)
  3872. y = min(yminlist)
  3873. for obj in obj_list:
  3874. obj.offset((-x, -y))
  3875. self.app_obj.object_changed.emit(obj)
  3876. # Update the object bounding box options
  3877. a, b, c, d = obj.bounds()
  3878. obj.options['xmin'] = a
  3879. obj.options['ymin'] = b
  3880. obj.options['xmax'] = c
  3881. obj.options['ymax'] = d
  3882. for obj in obj_list:
  3883. obj.plot()
  3884. for obj in obj_list:
  3885. out_name = obj.options["name"]
  3886. if obj.kind == 'gerber':
  3887. obj.source_file = self.export_gerber(
  3888. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3889. elif obj.kind == 'excellon':
  3890. obj.source_file = self.export_excellon(
  3891. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3892. self.inform.emit('[success] %s...' % _('Origin set'))
  3893. if use_thread is True:
  3894. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3895. else:
  3896. worker_task()
  3897. self.should_we_save = True
  3898. def on_jump_to(self, custom_location=None, fit_center=True):
  3899. """
  3900. Jump to a location by setting the mouse cursor location.
  3901. :param custom_location: Jump to a specified point. (x, y) tuple.
  3902. :param fit_center: If to fit view. Boolean.
  3903. :return:
  3904. """
  3905. self.defaults.report_usage("on_jump_to()")
  3906. if not custom_location:
  3907. dia_box_location = None
  3908. try:
  3909. dia_box_location = eval(self.clipboard.text())
  3910. except Exception:
  3911. pass
  3912. if type(dia_box_location) == tuple:
  3913. dia_box_location = str(dia_box_location)
  3914. else:
  3915. dia_box_location = None
  3916. # dia_box = Dialog_box(title=_("Jump to ..."),
  3917. # label=_("Enter the coordinates in format X,Y:"),
  3918. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3919. # initial_text=dia_box_location)
  3920. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3921. label=_("Enter the coordinates in format X,Y:"),
  3922. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3923. initial_text=dia_box_location,
  3924. reference=self.defaults['global_jump_ref'])
  3925. if dia_box.ok is True:
  3926. try:
  3927. location = eval(dia_box.location)
  3928. if not isinstance(location, tuple):
  3929. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3930. return
  3931. if dia_box.reference == 'rel':
  3932. rel_x = self.mouse[0] + location[0]
  3933. rel_y = self.mouse[1] + location[1]
  3934. location = (rel_x, rel_y)
  3935. self.defaults['global_jump_ref'] = dia_box.reference
  3936. except Exception:
  3937. return
  3938. else:
  3939. return
  3940. else:
  3941. location = custom_location
  3942. self.jump_signal.emit(location)
  3943. if fit_center:
  3944. self.plotcanvas.fit_center(loc=location)
  3945. cursor = QtGui.QCursor()
  3946. if self.is_legacy is False:
  3947. # I don't know where those differences come from but they are constant for the current
  3948. # execution of the application and they are multiples of a value around 0.0263mm.
  3949. # In a random way sometimes they are more sometimes they are less
  3950. # if units == 'MM':
  3951. # cal_factor = 0.0263
  3952. # else:
  3953. # cal_factor = 0.0263 / 25.4
  3954. cal_location = (location[0], location[1])
  3955. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3956. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3957. j_pos = (
  3958. int(canvas_origin.x() + round(jump_loc[0])),
  3959. int(canvas_origin.y() + round(jump_loc[1]))
  3960. )
  3961. cursor.setPos(j_pos[0], j_pos[1])
  3962. else:
  3963. # find the canvas origin which is in the top left corner
  3964. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3965. # determine the coordinates for the lowest left point of the canvas
  3966. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3967. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3968. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3969. # canvas) and the point (width, height) is in the top-right location
  3970. loc = self.plotcanvas.axes.transData.transform_point(location)
  3971. j_pos = (
  3972. int(x0 + loc[0]),
  3973. int(y0 - loc[1])
  3974. )
  3975. cursor.setPos(j_pos[0], j_pos[1])
  3976. self.plotcanvas.mouse = [location[0], location[1]]
  3977. if self.defaults["global_cursor_color_enabled"] is True:
  3978. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3979. else:
  3980. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3981. if self.grid_status():
  3982. # Update cursor
  3983. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3984. symbol='++', edge_color=self.cursor_color_3D,
  3985. edge_width=self.defaults["global_cursor_width"],
  3986. size=self.defaults["global_cursor_size"])
  3987. # Set the relative position label
  3988. dx = location[0] - float(self.rel_point1[0])
  3989. dy = location[1] - float(self.rel_point1[1])
  3990. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3991. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3992. # Set the position label
  3993. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3994. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3995. units = self.defaults["units"].lower()
  3996. self.plotcanvas.text_hud.text = \
  3997. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3998. dx, units, dy, units, location[0], units, location[1], units)
  3999. self.inform.emit('[success] %s' % _("Done."))
  4000. return location
  4001. def on_locate(self, obj, fit_center=True):
  4002. """
  4003. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4004. :param obj: The object on which to locate certain points
  4005. :param fit_center: If to fit view. Boolean.
  4006. :return: A point location. (x, y) tuple.
  4007. """
  4008. self.defaults.report_usage("on_locate()")
  4009. if obj is None:
  4010. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4011. return 'fail'
  4012. class DialogBoxChoice(QtWidgets.QDialog):
  4013. def __init__(self, title=None, icon=None, choice='bl'):
  4014. """
  4015. :param title: string with the window title
  4016. """
  4017. super(DialogBoxChoice, self).__init__()
  4018. self.ok = False
  4019. self.setWindowIcon(icon)
  4020. self.setWindowTitle(str(title))
  4021. self.form = QtWidgets.QFormLayout(self)
  4022. self.ref_radio = RadioSet([
  4023. {"label": _("Bottom-Left"), "value": "bl"},
  4024. {"label": _("Top-Left"), "value": "tl"},
  4025. {"label": _("Bottom-Right"), "value": "br"},
  4026. {"label": _("Top-Right"), "value": "tr"},
  4027. {"label": _("Center"), "value": "c"}
  4028. ], orientation='vertical', stretch=False)
  4029. self.ref_radio.set_value(choice)
  4030. self.form.addRow(self.ref_radio)
  4031. self.button_box = QtWidgets.QDialogButtonBox(
  4032. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4033. Qt.Horizontal, parent=self)
  4034. self.form.addRow(self.button_box)
  4035. self.button_box.accepted.connect(self.accept)
  4036. self.button_box.rejected.connect(self.reject)
  4037. if self.exec_() == QtWidgets.QDialog.Accepted:
  4038. self.ok = True
  4039. self.location_point = self.ref_radio.get_value()
  4040. else:
  4041. self.ok = False
  4042. self.location_point = None
  4043. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4044. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4045. choice=self.defaults['global_locate_pt'])
  4046. if dia_box.ok is True:
  4047. try:
  4048. location_point = dia_box.location_point
  4049. self.defaults['global_locate_pt'] = dia_box.location_point
  4050. except Exception:
  4051. return
  4052. else:
  4053. return
  4054. loc_b = obj.bounds()
  4055. if location_point == 'bl':
  4056. location = (loc_b[0], loc_b[1])
  4057. elif location_point == 'tl':
  4058. location = (loc_b[0], loc_b[3])
  4059. elif location_point == 'br':
  4060. location = (loc_b[2], loc_b[1])
  4061. elif location_point == 'tr':
  4062. location = (loc_b[2], loc_b[3])
  4063. else:
  4064. # center
  4065. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4066. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4067. location = (cx, cy)
  4068. self.locate_signal.emit(location, location_point)
  4069. if fit_center:
  4070. self.plotcanvas.fit_center(loc=location)
  4071. cursor = QtGui.QCursor()
  4072. if self.is_legacy is False:
  4073. # I don't know where those differences come from but they are constant for the current
  4074. # execution of the application and they are multiples of a value around 0.0263mm.
  4075. # In a random way sometimes they are more sometimes they are less
  4076. # if units == 'MM':
  4077. # cal_factor = 0.0263
  4078. # else:
  4079. # cal_factor = 0.0263 / 25.4
  4080. cal_location = (location[0], location[1])
  4081. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4082. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4083. j_pos = (
  4084. int(canvas_origin.x() + round(jump_loc[0])),
  4085. int(canvas_origin.y() + round(jump_loc[1]))
  4086. )
  4087. cursor.setPos(j_pos[0], j_pos[1])
  4088. else:
  4089. # find the canvas origin which is in the top left corner
  4090. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4091. # determine the coordinates for the lowest left point of the canvas
  4092. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4093. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4094. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4095. # canvas) and the point (width, height) is in the top-right location
  4096. loc = self.plotcanvas.axes.transData.transform_point(location)
  4097. j_pos = (
  4098. int(x0 + loc[0]),
  4099. int(y0 - loc[1])
  4100. )
  4101. cursor.setPos(j_pos[0], j_pos[1])
  4102. self.plotcanvas.mouse = [location[0], location[1]]
  4103. if self.defaults["global_cursor_color_enabled"] is True:
  4104. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4105. else:
  4106. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4107. if self.grid_status():
  4108. # Update cursor
  4109. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4110. symbol='++', edge_color=self.cursor_color_3D,
  4111. edge_width=self.defaults["global_cursor_width"],
  4112. size=self.defaults["global_cursor_size"])
  4113. # Set the relative position label
  4114. self.dx = location[0] - float(self.rel_point1[0])
  4115. self.dy = location[1] - float(self.rel_point1[1])
  4116. # Set the position label
  4117. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4118. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4119. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4120. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4121. units = self.defaults["units"].lower()
  4122. self.plotcanvas.text_hud.text = \
  4123. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4124. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4125. self.inform.emit('[success] %s' % _("Done."))
  4126. return location
  4127. def on_copy_command(self):
  4128. """
  4129. Will copy a selection of objects, creating new objects.
  4130. :return:
  4131. """
  4132. self.defaults.report_usage("on_copy_command()")
  4133. def initialize(obj_init, app):
  4134. """
  4135. :param obj_init: the new object
  4136. :type obj_init: class
  4137. :param app: An instance of the App class
  4138. :type app: App
  4139. :return: None
  4140. :rtype:
  4141. """
  4142. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4143. try:
  4144. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4145. except AttributeError:
  4146. pass
  4147. try:
  4148. obj_init.apertures = deepcopy(obj.apertures)
  4149. except AttributeError:
  4150. pass
  4151. try:
  4152. if obj.tools:
  4153. obj_init.tools = deepcopy(obj.tools)
  4154. except Exception as err:
  4155. log.debug("App.on_copy_command() --> %s" % str(err))
  4156. try:
  4157. obj_init.source_file = deepcopy(obj.source_file)
  4158. except (AttributeError, TypeError):
  4159. pass
  4160. def initialize_excellon(obj_init, app):
  4161. obj_init.source_file = deepcopy(obj.source_file)
  4162. obj_init.tools = deepcopy(obj.tools)
  4163. # drills are offset, so they need to be deep copied
  4164. obj_init.drills = deepcopy(obj.drills)
  4165. # slots are offset, so they need to be deep copied
  4166. obj_init.slots = deepcopy(obj.slots)
  4167. obj_init.create_geometry()
  4168. def initialize_script(obj_init, app_obj):
  4169. obj_init.source_file = deepcopy(obj.source_file)
  4170. def initialize_document(obj_init, app_obj):
  4171. obj_init.source_file = deepcopy(obj.source_file)
  4172. for obj in self.collection.get_selected():
  4173. obj_name = obj.options["name"]
  4174. try:
  4175. if isinstance(obj, ExcellonObject):
  4176. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4177. elif isinstance(obj, GerberObject):
  4178. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  4179. elif isinstance(obj, GeometryObject):
  4180. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  4181. elif isinstance(obj, ScriptObject):
  4182. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  4183. elif isinstance(obj, DocumentObject):
  4184. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  4185. except Exception as e:
  4186. return "Operation failed: %s" % str(e)
  4187. def on_copy_object2(self, custom_name):
  4188. def initialize_geometry(obj_init, app):
  4189. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4190. try:
  4191. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4192. except AttributeError:
  4193. pass
  4194. try:
  4195. obj_init.apertures = deepcopy(obj.apertures)
  4196. except AttributeError:
  4197. pass
  4198. try:
  4199. if obj.tools:
  4200. obj_init.tools = deepcopy(obj.tools)
  4201. except Exception as ee:
  4202. log.debug("on_copy_object2() --> %s" % str(ee))
  4203. def initialize_gerber(obj_init, app):
  4204. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4205. obj_init.apertures = deepcopy(obj.apertures)
  4206. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4207. def initialize_excellon(obj_init, app):
  4208. obj_init.tools = deepcopy(obj.tools)
  4209. # drills are offset, so they need to be deep copied
  4210. obj_init.drills = deepcopy(obj.drills)
  4211. # slots are offset, so they need to be deep copied
  4212. obj_init.slots = deepcopy(obj.slots)
  4213. obj_init.create_geometry()
  4214. for obj in self.collection.get_selected():
  4215. obj_name = obj.options["name"]
  4216. try:
  4217. if isinstance(obj, ExcellonObject):
  4218. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4219. elif isinstance(obj, GerberObject):
  4220. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4221. elif isinstance(obj, GeometryObject):
  4222. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4223. except Exception as er:
  4224. return "Operation failed: %s" % str(er)
  4225. def on_rename_object(self, text):
  4226. """
  4227. Will rename an object.
  4228. :param text: New name for the object.
  4229. :return:
  4230. """
  4231. self.defaults.report_usage("on_rename_object()")
  4232. named_obj = self.collection.get_active()
  4233. for obj in named_obj:
  4234. if obj is list:
  4235. self.on_rename_object(text)
  4236. else:
  4237. try:
  4238. obj.options['name'] = text
  4239. except Exception as e:
  4240. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4241. def convert_any2geo(self):
  4242. """
  4243. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4244. :return:
  4245. """
  4246. self.defaults.report_usage("convert_any2geo()")
  4247. def initialize(obj_init, app):
  4248. obj_init.solid_geometry = obj.solid_geometry
  4249. try:
  4250. obj_init.follow_geometry = obj.follow_geometry
  4251. except AttributeError:
  4252. pass
  4253. try:
  4254. obj_init.apertures = obj.apertures
  4255. except AttributeError:
  4256. pass
  4257. try:
  4258. if obj.tools:
  4259. obj_init.tools = obj.tools
  4260. except AttributeError:
  4261. pass
  4262. def initialize_excellon(obj_init, app):
  4263. # objs = self.collection.get_selected()
  4264. # GeometryObject.merge(objs, obj)
  4265. solid_geo = []
  4266. for tool in obj.tools:
  4267. for geo in obj.tools[tool]['solid_geometry']:
  4268. solid_geo.append(geo)
  4269. obj_init.solid_geometry = deepcopy(solid_geo)
  4270. if not self.collection.get_selected():
  4271. log.warning("App.convert_any2geo --> No object selected")
  4272. self.inform.emit('[WARNING_NOTCL] %s' %
  4273. _("No object is selected. Select an object and try again."))
  4274. return
  4275. for obj in self.collection.get_selected():
  4276. obj_name = obj.options["name"]
  4277. try:
  4278. if obj.kind == 'excellon':
  4279. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4280. else:
  4281. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4282. except Exception as e:
  4283. return "Operation failed: %s" % str(e)
  4284. def convert_any2gerber(self):
  4285. """
  4286. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4287. :return:
  4288. """
  4289. def initialize_geometry(obj_init, app):
  4290. apertures = {}
  4291. apid = 0
  4292. apertures[str(apid)] = {}
  4293. apertures[str(apid)]['geometry'] = []
  4294. for obj_orig in obj.solid_geometry:
  4295. new_elem = {}
  4296. new_elem['solid'] = obj_orig
  4297. try:
  4298. new_elem['follow'] = obj_orig.exterior
  4299. except AttributeError:
  4300. pass
  4301. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4302. apertures[str(apid)]['size'] = 0.0
  4303. apertures[str(apid)]['type'] = 'C'
  4304. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4305. obj_init.apertures = deepcopy(apertures)
  4306. def initialize_excellon(obj_init, app):
  4307. apertures = {}
  4308. apid = 10
  4309. for tool in obj.tools:
  4310. apertures[str(apid)] = {}
  4311. apertures[str(apid)]['geometry'] = []
  4312. for geo in obj.tools[tool]['solid_geometry']:
  4313. new_el = {}
  4314. new_el['solid'] = geo
  4315. new_el['follow'] = geo.exterior
  4316. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4317. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4318. apertures[str(apid)]['type'] = 'C'
  4319. apid += 1
  4320. # create solid_geometry
  4321. solid_geometry = []
  4322. for apid in apertures:
  4323. for geo_el in apertures[apid]['geometry']:
  4324. solid_geometry.append(geo_el['solid'])
  4325. solid_geometry = MultiPolygon(solid_geometry)
  4326. solid_geometry = solid_geometry.buffer(0.0000001)
  4327. obj_init.solid_geometry = deepcopy(solid_geometry)
  4328. obj_init.apertures = deepcopy(apertures)
  4329. # clear the working objects (perhaps not necessary due of Python GC)
  4330. apertures.clear()
  4331. if not self.collection.get_selected():
  4332. log.warning("App.convert_any2gerber --> No object selected")
  4333. self.inform.emit('[WARNING_NOTCL] %s' %
  4334. _("No object is selected. Select an object and try again."))
  4335. return
  4336. for obj in self.collection.get_selected():
  4337. obj_name = obj.options["name"]
  4338. try:
  4339. if obj.kind == 'excellon':
  4340. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4341. elif obj.kind == 'geometry':
  4342. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4343. else:
  4344. log.warning("App.convert_any2gerber --> This is no valid object for conversion.")
  4345. except Exception as e:
  4346. return "Operation failed: %s" % str(e)
  4347. def convert_any2excellon(self):
  4348. """
  4349. Will convert any object out of Gerber, Excellon, Geometry to an Excellon object.
  4350. :return:
  4351. """
  4352. def initialize_geometry(obj_init, app):
  4353. tools = {}
  4354. tooluid = 1
  4355. obj_init.solid_geometry = []
  4356. for geo in obj.solid_geometry:
  4357. if not isinstance(geo, (Polygon, MultiPolygon, LinearRing)):
  4358. continue
  4359. minx, miny, maxx, maxy = geo.bounds
  4360. new_dia = min([maxx-minx, maxy-miny])
  4361. new_drill = geo.centroid
  4362. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4363. current_tooldias = []
  4364. if tools:
  4365. for tool in tools:
  4366. if tools[tool] and 'tooldia' in tools[tool]:
  4367. current_tooldias.append(tools[tool]['tooldia'])
  4368. if new_dia in current_tooldias:
  4369. for tool in tools:
  4370. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float('%.*f' % (self.decimals,
  4371. new_dia)):
  4372. tools[tool]['drills'].append(new_drill)
  4373. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4374. else:
  4375. tools[tooluid] = {}
  4376. tools[tooluid]['tooldia'] = new_dia
  4377. tools[tooluid]['drills'] = [new_drill]
  4378. tools[tooluid]['slots'] = []
  4379. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4380. tooluid += 1
  4381. try:
  4382. obj_init.solid_geometry.append(new_drill_geo)
  4383. except (TypeError, AttributeError):
  4384. obj_init.solid_geometry = [new_drill_geo]
  4385. obj_init.tools = deepcopy(tools)
  4386. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4387. def initialize_gerber(obj_init, app):
  4388. tools = {}
  4389. tooluid = 1
  4390. obj_init.solid_geometry = []
  4391. for apid in obj.apertures:
  4392. if 'geometry' in obj.apertures[apid]:
  4393. for geo_dict in obj.apertures[apid]['geometry']:
  4394. if 'follow' in geo_dict:
  4395. if isinstance(geo_dict['follow'], Point):
  4396. geo = geo_dict['solid']
  4397. minx, miny, maxx, maxy = geo.bounds
  4398. new_dia = min([maxx - minx, maxy - miny])
  4399. new_drill = geo.centroid
  4400. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4401. current_tooldias = []
  4402. if tools:
  4403. for tool in tools:
  4404. if tools[tool] and 'tooldia' in tools[tool]:
  4405. current_tooldias.append(
  4406. float('%.*f' % (self.decimals, tools[tool]['tooldia']))
  4407. )
  4408. if float('%.*f' % (self.decimals, new_dia)) in current_tooldias:
  4409. for tool in tools:
  4410. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float(
  4411. '%.*f' % (self.decimals, new_dia)):
  4412. if new_drill not in tools[tool]['drills']:
  4413. tools[tool]['drills'].append(new_drill)
  4414. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4415. else:
  4416. tools[tooluid] = {}
  4417. tools[tooluid]['tooldia'] = new_dia
  4418. tools[tooluid]['drills'] = [new_drill]
  4419. tools[tooluid]['slots'] = []
  4420. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4421. tooluid += 1
  4422. try:
  4423. obj_init.solid_geometry.append(new_drill_geo)
  4424. except (TypeError, AttributeError):
  4425. obj_init.solid_geometry = [new_drill_geo]
  4426. elif isinstance(geo_dict['follow'], LineString):
  4427. geo_coords = list(geo_dict['follow'].coords)
  4428. # slots can have only a start and stop point and no intermediate points
  4429. if len(geo_coords) != 2:
  4430. continue
  4431. geo = geo_dict['solid']
  4432. try:
  4433. new_dia = obj.apertures[apid]['size']
  4434. except Exception:
  4435. continue
  4436. new_slot = (Point(geo_coords[0]), Point(geo_coords[1]))
  4437. new_slot_geo = geo
  4438. current_tooldias = []
  4439. if tools:
  4440. for tool in tools:
  4441. if tools[tool] and 'tooldia' in tools[tool]:
  4442. current_tooldias.append(
  4443. float('%.*f' % (self.decimals, tools[tool]['tooldia']))
  4444. )
  4445. if float('%.*f' % (self.decimals, new_dia)) in current_tooldias:
  4446. for tool in tools:
  4447. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float(
  4448. '%.*f' % (self.decimals, new_dia)):
  4449. if new_slot not in tools[tool]['slots']:
  4450. tools[tool]['slots'].append(new_slot)
  4451. tools[tool]['solid_geometry'].append(deepcopy(new_slot_geo))
  4452. else:
  4453. tools[tooluid] = {}
  4454. tools[tooluid]['tooldia'] = new_dia
  4455. tools[tooluid]['drills'] = []
  4456. tools[tooluid]['slots'] = [new_slot]
  4457. tools[tooluid]['solid_geometry'] = [new_slot_geo]
  4458. tooluid += 1
  4459. try:
  4460. obj_init.solid_geometry.append(new_slot_geo)
  4461. except (TypeError, AttributeError):
  4462. obj_init.solid_geometry = [new_slot_geo]
  4463. obj_init.tools = deepcopy(tools)
  4464. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4465. if not self.collection.get_selected():
  4466. log.warning("App.convert_any2excellon--> No object selected")
  4467. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected. Select an object and try again."))
  4468. return
  4469. for obj in self.collection.get_selected():
  4470. obj_name = obj.options["name"]
  4471. try:
  4472. if obj.kind == 'gerber':
  4473. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_gerber)
  4474. elif obj.kind == 'geometry':
  4475. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_geometry)
  4476. else:
  4477. log.warning("App.convert_any2excellon --> This is no valid object for conversion.")
  4478. except Exception as e:
  4479. return "Operation failed: %s" % str(e)
  4480. def abort_all_tasks(self):
  4481. """
  4482. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4483. on the first possible occasion.
  4484. :return:
  4485. """
  4486. if self.abort_flag is False:
  4487. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4488. self.abort_flag = True
  4489. self.cleanup.emit()
  4490. def app_is_idle(self):
  4491. if self.abort_flag:
  4492. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4493. self.abort_flag = False
  4494. def on_selectall(self):
  4495. """
  4496. Will draw a selection box shape around the selected objects.
  4497. :return:
  4498. """
  4499. self.defaults.report_usage("on_selectall()")
  4500. # delete the possible selection box around a possible selected object
  4501. self.delete_selection_shape()
  4502. for name in self.collection.get_names():
  4503. self.collection.set_active(name)
  4504. curr_sel_obj = self.collection.get_by_name(name)
  4505. # create the selection box around the selected object
  4506. if self.defaults['global_selection_shape'] is True:
  4507. self.draw_selection_shape(curr_sel_obj)
  4508. def on_toggle_preferences(self):
  4509. pref_open = False
  4510. for idx in range(self.ui.plot_tab_area.count()):
  4511. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4512. pref_open = True
  4513. if pref_open:
  4514. for idx in range(self.ui.plot_tab_area.count()):
  4515. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4516. self.ui.plot_tab_area.removeTab(idx)
  4517. break
  4518. self.ui.pref_status_label.setStyleSheet("")
  4519. else:
  4520. self.on_preferences()
  4521. def on_preferences(self):
  4522. """
  4523. Adds the Preferences in a Tab in Plot Area
  4524. :return:
  4525. """
  4526. # add the tab if it was closed
  4527. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4528. # delete the absolute and relative position and messages in the infobar
  4529. # self.ui.position_label.setText("")
  4530. # self.ui.rel_position_label.setText("")
  4531. # hide coordinates toolbars in the infobar while in DB
  4532. self.ui.coords_toolbar.hide()
  4533. self.ui.delta_coords_toolbar.hide()
  4534. # Switch plot_area to preferences page
  4535. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4536. # self.ui.show()
  4537. self.ui.pref_status_label.setStyleSheet("""
  4538. QLabel
  4539. {
  4540. color: black;
  4541. background-color: lightseagreen;
  4542. }
  4543. """
  4544. )
  4545. # detect changes in the preferences
  4546. for idx in range(self.ui.pref_tab_area.count()):
  4547. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4548. try:
  4549. try:
  4550. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4551. except (TypeError, AttributeError):
  4552. pass
  4553. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4554. except AttributeError:
  4555. pass
  4556. try:
  4557. try:
  4558. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4559. except (TypeError, AttributeError):
  4560. pass
  4561. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4562. except AttributeError:
  4563. pass
  4564. try:
  4565. try:
  4566. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4567. except (TypeError, AttributeError):
  4568. pass
  4569. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4570. except AttributeError:
  4571. pass
  4572. try:
  4573. try:
  4574. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4575. except (TypeError, AttributeError):
  4576. pass
  4577. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4578. except AttributeError:
  4579. pass
  4580. try:
  4581. try:
  4582. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4583. except (TypeError, AttributeError):
  4584. pass
  4585. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4586. except AttributeError:
  4587. pass
  4588. def on_tools_database(self, source='app'):
  4589. """
  4590. Adds the Tools Database in a Tab in Plot Area.
  4591. :return:
  4592. """
  4593. for idx in range(self.ui.plot_tab_area.count()):
  4594. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4595. # there can be only one instance of Tools Database at one time
  4596. return
  4597. if source == 'app':
  4598. self.tools_db_tab = ToolsDB2(
  4599. app=self,
  4600. parent=self.ui,
  4601. callback_on_edited=self.on_tools_db_edited,
  4602. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4603. )
  4604. elif source == 'ncc':
  4605. self.tools_db_tab = ToolsDB2(
  4606. app=self,
  4607. parent=self.ui,
  4608. callback_on_edited=self.on_tools_db_edited,
  4609. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4610. )
  4611. elif source == 'paint':
  4612. self.tools_db_tab = ToolsDB2(
  4613. app=self,
  4614. parent=self.ui,
  4615. callback_on_edited=self.on_tools_db_edited,
  4616. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4617. )
  4618. elif source == 'iso':
  4619. self.tools_db_tab = ToolsDB2(
  4620. app=self,
  4621. parent=self.ui,
  4622. callback_on_edited=self.on_tools_db_edited,
  4623. callback_on_tool_request=self.isolation_tool.on_iso_tool_add_from_db_executed
  4624. )
  4625. # add the tab if it was closed
  4626. try:
  4627. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4628. self.tools_db_tab.setObjectName("database_tab")
  4629. except Exception as e:
  4630. log.debug("App.on_tools_database() --> %s" % str(e))
  4631. return
  4632. # delete the absolute and relative position and messages in the infobar
  4633. # self.ui.position_label.setText("")
  4634. # self.ui.rel_position_label.setText("")
  4635. # hide coordinates toolbars in the infobar while in DB
  4636. self.ui.coords_toolbar.hide()
  4637. self.ui.delta_coords_toolbar.hide()
  4638. # Switch plot_area to preferences page
  4639. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4640. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4641. self.tools_db_tab.ui_connect()
  4642. def on_tools_db_edited(self):
  4643. """
  4644. Executed whenever a tool is edited in Tools Database.
  4645. Will color the text of the Tools Database tab to Red color.
  4646. :return:
  4647. """
  4648. self.inform[str, bool].emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."), False)
  4649. for idx in range(self.ui.plot_tab_area.count()):
  4650. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4651. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4652. self.tools_db_tab.ui.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4653. self.tools_db_changed_flag = True
  4654. def on_geometry_tool_add_from_db_executed(self, tool):
  4655. """
  4656. Here add the tool from DB in the selected geometry object.
  4657. :return:
  4658. """
  4659. tool_from_db = deepcopy(tool)
  4660. obj = self.collection.get_active()
  4661. if obj.kind == 'geometry':
  4662. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4663. # close the tab and delete it
  4664. for idx in range(self.ui.plot_tab_area.count()):
  4665. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4666. wdg = self.ui.plot_tab_area.widget(idx)
  4667. wdg.deleteLater()
  4668. self.ui.plot_tab_area.removeTab(idx)
  4669. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4670. elif obj.kind == 'gerber':
  4671. self.isolation_tool.on_tool_from_db_inserted(tool=tool_from_db)
  4672. # close the tab and delete it
  4673. for idx in range(self.ui.plot_tab_area.count()):
  4674. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4675. wdg = self.ui.plot_tab_area.widget(idx)
  4676. wdg.deleteLater()
  4677. self.ui.plot_tab_area.removeTab(idx)
  4678. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4679. else:
  4680. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4681. def on_plot_area_tab_closed(self, tab_obj_name):
  4682. """
  4683. Executed whenever a QTab is closed in the Plot Area.
  4684. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4685. :return:
  4686. """
  4687. if tab_obj_name == "preferences_tab":
  4688. self.preferencesUiManager.on_close_preferences_tab()
  4689. elif tab_obj_name == "database_tab":
  4690. # disconnect the signals from the table widget in tab
  4691. self.tools_db_tab.ui_disconnect()
  4692. if self.tools_db_changed_flag is True:
  4693. msgbox = QtWidgets.QMessageBox()
  4694. msgbox.setText(_("One or more Tools are edited.\n"
  4695. "Do you want to update the Tools Database?"))
  4696. msgbox.setWindowTitle(_("Save Tools Database"))
  4697. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4698. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  4699. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4700. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4701. msgbox.setDefaultButton(bt_yes)
  4702. msgbox.exec_()
  4703. response = msgbox.clickedButton()
  4704. if response == bt_yes:
  4705. self.tools_db_tab.on_save_tools_db()
  4706. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4707. else:
  4708. self.tools_db_changed_flag = False
  4709. self.inform.emit('')
  4710. return
  4711. self.tools_db_tab.deleteLater()
  4712. elif tab_obj_name == "text_editor_tab":
  4713. self.toggle_codeeditor = False
  4714. elif tab_obj_name == "bookmarks_tab":
  4715. self.book_dialog_tab.rebuild_actions()
  4716. self.book_dialog_tab.deleteLater()
  4717. else:
  4718. pass
  4719. # restore the coords toolbars
  4720. self.ui.toggle_coords(checked=self.defaults["global_coords_show"])
  4721. self.ui.toggle_delta_coords(checked=self.defaults["global_delta_coords_show"])
  4722. def on_flipy(self):
  4723. """
  4724. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4725. :return:
  4726. """
  4727. self.defaults.report_usage("on_flipy()")
  4728. obj_list = self.collection.get_selected()
  4729. xminlist = []
  4730. yminlist = []
  4731. xmaxlist = []
  4732. ymaxlist = []
  4733. if not obj_list:
  4734. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4735. else:
  4736. try:
  4737. # first get a bounding box to fit all
  4738. for obj in obj_list:
  4739. xmin, ymin, xmax, ymax = obj.bounds()
  4740. xminlist.append(xmin)
  4741. yminlist.append(ymin)
  4742. xmaxlist.append(xmax)
  4743. ymaxlist.append(ymax)
  4744. # get the minimum x,y and maximum x,y for all objects selected
  4745. xminimal = min(xminlist)
  4746. yminimal = min(yminlist)
  4747. xmaximal = max(xmaxlist)
  4748. ymaximal = max(ymaxlist)
  4749. px = 0.5 * (xminimal + xmaximal)
  4750. py = 0.5 * (yminimal + ymaximal)
  4751. # execute mirroring
  4752. for obj in obj_list:
  4753. obj.mirror('X', [px, py])
  4754. obj.plot()
  4755. self.app_obj.object_changed.emit(obj)
  4756. self.inform.emit('[success] %s' %
  4757. _("Flip on Y axis done."))
  4758. except Exception as e:
  4759. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4760. return
  4761. def on_flipx(self):
  4762. """
  4763. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4764. :return:
  4765. """
  4766. self.defaults.report_usage("on_flipx()")
  4767. obj_list = self.collection.get_selected()
  4768. xminlist = []
  4769. yminlist = []
  4770. xmaxlist = []
  4771. ymaxlist = []
  4772. if not obj_list:
  4773. self.inform.emit('[WARNING_NOTCL] %s' %
  4774. _("No object selected to Flip on X axis."))
  4775. else:
  4776. try:
  4777. # first get a bounding box to fit all
  4778. for obj in obj_list:
  4779. xmin, ymin, xmax, ymax = obj.bounds()
  4780. xminlist.append(xmin)
  4781. yminlist.append(ymin)
  4782. xmaxlist.append(xmax)
  4783. ymaxlist.append(ymax)
  4784. # get the minimum x,y and maximum x,y for all objects selected
  4785. xminimal = min(xminlist)
  4786. yminimal = min(yminlist)
  4787. xmaximal = max(xmaxlist)
  4788. ymaximal = max(ymaxlist)
  4789. px = 0.5 * (xminimal + xmaximal)
  4790. py = 0.5 * (yminimal + ymaximal)
  4791. # execute mirroring
  4792. for obj in obj_list:
  4793. obj.mirror('Y', [px, py])
  4794. obj.plot()
  4795. self.app_obj.object_changed.emit(obj)
  4796. self.inform.emit('[success] %s' %
  4797. _("Flip on X axis done."))
  4798. except Exception as e:
  4799. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4800. return
  4801. def on_rotate(self, silent=False, preset=None):
  4802. """
  4803. Executed when Options -> Rotate Selection menu entry is clicked.
  4804. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4805. :param preset: A value to be used as predefined angle for rotation.
  4806. :return:
  4807. """
  4808. self.defaults.report_usage("on_rotate()")
  4809. obj_list = self.collection.get_selected()
  4810. xminlist = []
  4811. yminlist = []
  4812. xmaxlist = []
  4813. ymaxlist = []
  4814. if not obj_list:
  4815. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4816. else:
  4817. if silent is False:
  4818. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4819. min=-360, max=360, decimals=4,
  4820. init_val=float(self.defaults['tools_transform_rotate']))
  4821. num, ok = rotatebox.get_value()
  4822. else:
  4823. num = preset
  4824. ok = True
  4825. if ok:
  4826. try:
  4827. # first get a bounding box to fit all
  4828. for obj in obj_list:
  4829. xmin, ymin, xmax, ymax = obj.bounds()
  4830. xminlist.append(xmin)
  4831. yminlist.append(ymin)
  4832. xmaxlist.append(xmax)
  4833. ymaxlist.append(ymax)
  4834. # get the minimum x,y and maximum x,y for all objects selected
  4835. xminimal = min(xminlist)
  4836. yminimal = min(yminlist)
  4837. xmaximal = max(xmaxlist)
  4838. ymaximal = max(ymaxlist)
  4839. px = 0.5 * (xminimal + xmaximal)
  4840. py = 0.5 * (yminimal + ymaximal)
  4841. for sel_obj in obj_list:
  4842. sel_obj.rotate(-float(num), point=(px, py))
  4843. sel_obj.plot()
  4844. self.app_obj.object_changed.emit(sel_obj)
  4845. self.inform.emit('[success] %s' % _("Rotation done."))
  4846. except Exception as e:
  4847. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4848. return
  4849. def on_skewx(self):
  4850. """
  4851. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4852. :return:
  4853. """
  4854. self.defaults.report_usage("on_skewx()")
  4855. obj_list = self.collection.get_selected()
  4856. xminlist = []
  4857. yminlist = []
  4858. if not obj_list:
  4859. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4860. else:
  4861. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4862. min=-360, max=360, decimals=4,
  4863. init_val=float(self.defaults['tools_transform_skew_x']))
  4864. num, ok = skewxbox.get_value()
  4865. if ok:
  4866. # first get a bounding box to fit all
  4867. for obj in obj_list:
  4868. xmin, ymin, xmax, ymax = obj.bounds()
  4869. xminlist.append(xmin)
  4870. yminlist.append(ymin)
  4871. # get the minimum x,y and maximum x,y for all objects selected
  4872. xminimal = min(xminlist)
  4873. yminimal = min(yminlist)
  4874. for obj in obj_list:
  4875. obj.skew(num, 0, point=(xminimal, yminimal))
  4876. obj.plot()
  4877. self.app_obj.object_changed.emit(obj)
  4878. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4879. def on_skewy(self):
  4880. """
  4881. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4882. :return:
  4883. """
  4884. self.defaults.report_usage("on_skewy()")
  4885. obj_list = self.collection.get_selected()
  4886. xminlist = []
  4887. yminlist = []
  4888. if not obj_list:
  4889. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4890. else:
  4891. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4892. min=-360, max=360, decimals=4,
  4893. init_val=float(self.defaults['tools_transform_skew_y']))
  4894. num, ok = skewybox.get_value()
  4895. if ok:
  4896. # first get a bounding box to fit all
  4897. for obj in obj_list:
  4898. xmin, ymin, xmax, ymax = obj.bounds()
  4899. xminlist.append(xmin)
  4900. yminlist.append(ymin)
  4901. # get the minimum x,y and maximum x,y for all objects selected
  4902. xminimal = min(xminlist)
  4903. yminimal = min(yminlist)
  4904. for obj in obj_list:
  4905. obj.skew(0, num, point=(xminimal, yminimal))
  4906. obj.plot()
  4907. self.app_obj.object_changed.emit(obj)
  4908. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4909. def on_plots_updated(self):
  4910. """
  4911. Callback used to report when the plots have changed.
  4912. Adjust axes and zooms to fit.
  4913. :return: None
  4914. """
  4915. if self.is_legacy is False:
  4916. self.plotcanvas.update()
  4917. else:
  4918. self.plotcanvas.auto_adjust_axes()
  4919. self.on_zoom_fit()
  4920. self.collection.update_view()
  4921. # self.inform.emit(_("Plots updated ..."))
  4922. def on_toolbar_replot(self):
  4923. """
  4924. Callback for toolbar button. Re-plots all objects.
  4925. :return: None
  4926. """
  4927. self.log.debug("on_toolbar_replot()")
  4928. try:
  4929. obj = self.collection.get_active()
  4930. if obj:
  4931. obj.read_form()
  4932. else:
  4933. self.on_zoom_fit()
  4934. except AttributeError as e:
  4935. log.debug("on_toolbar_replot() -> %s" % str(e))
  4936. pass
  4937. self.plot_all()
  4938. def grid_status(self):
  4939. return True if self.ui.grid_snap_btn.isChecked() else False
  4940. def populate_cmenu_grids(self):
  4941. units = self.defaults['units'].lower()
  4942. # for act in self.ui.cmenu_gridmenu.actions():
  4943. # act.triggered.disconnect()
  4944. self.ui.cmenu_gridmenu.clear()
  4945. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4946. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4947. _("Grid On/Off"))
  4948. grid_toggle.setCheckable(True)
  4949. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4950. self.ui.cmenu_gridmenu.addSeparator()
  4951. for grid in sorted_list:
  4952. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4953. "%s" % str(grid))
  4954. action.triggered.connect(self.set_grid)
  4955. self.ui.cmenu_gridmenu.addSeparator()
  4956. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4957. _("Add"))
  4958. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4959. _("Delete"))
  4960. grid_add.triggered.connect(self.on_grid_add)
  4961. grid_delete.triggered.connect(self.on_grid_delete)
  4962. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4963. def set_grid(self):
  4964. menu_action = self.sender()
  4965. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  4966. self.ui.grid_gap_x_entry.setText(menu_action.text())
  4967. self.ui.grid_gap_y_entry.setText(menu_action.text())
  4968. def on_grid_add(self):
  4969. # ## Current application units in lower Case
  4970. units = self.defaults['units'].lower()
  4971. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4972. text=_('Enter a Grid Value:'),
  4973. min=0.0000, max=99.9999, decimals=4)
  4974. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  4975. val, ok = grid_add_popup.get_value()
  4976. if ok:
  4977. if float(val) == 0:
  4978. self.inform.emit('[WARNING_NOTCL] %s' %
  4979. _("Please enter a grid value with non-zero value, in Float format."))
  4980. return
  4981. else:
  4982. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4983. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4984. self.inform.emit('[success] %s...' % _("New Grid added"))
  4985. else:
  4986. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  4987. else:
  4988. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  4989. def on_grid_delete(self):
  4990. # ## Current application units in lower Case
  4991. units = self.defaults['units'].lower()
  4992. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4993. text='Enter a Grid Value:',
  4994. min=0.0000, max=99.9999, decimals=4)
  4995. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  4996. val, ok = grid_del_popup.get_value()
  4997. if ok:
  4998. if float(val) == 0:
  4999. self.inform.emit('[WARNING_NOTCL] %s' %
  5000. _("Please enter a grid value with non-zero value, in Float format."))
  5001. return
  5002. else:
  5003. try:
  5004. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5005. except ValueError:
  5006. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  5007. return
  5008. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  5009. else:
  5010. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  5011. def on_shortcut_list(self):
  5012. self.defaults.report_usage("on_shortcut_list()")
  5013. # add the tab if it was closed
  5014. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5015. # delete the absolute and relative position and messages in the infobar
  5016. # self.ui.position_label.setText("")
  5017. # self.ui.rel_position_label.setText("")
  5018. # hide coordinates toolbars in the infobar while in DB
  5019. self.ui.coords_toolbar.hide()
  5020. self.ui.delta_coords_toolbar.hide()
  5021. # Switch plot_area to preferences page
  5022. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5023. # self.ui.show()
  5024. def on_select_tab(self, name):
  5025. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5026. if self.ui.splitter.sizes()[0] == 0:
  5027. self.ui.splitter.setSizes([1, 1])
  5028. else:
  5029. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5030. self.ui.splitter.setSizes([0, 1])
  5031. if name == 'project':
  5032. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5033. elif name == 'selected':
  5034. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5035. elif name == 'tool':
  5036. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5037. def on_copy_name(self):
  5038. self.defaults.report_usage("on_copy_name()")
  5039. obj = self.collection.get_active()
  5040. try:
  5041. name = obj.options["name"]
  5042. except AttributeError:
  5043. log.debug("on_copy_name() --> No object selected to copy it's name")
  5044. self.inform.emit('[WARNING_NOTCL] %s' %
  5045. _(" No object selected to copy it's name"))
  5046. return
  5047. self.clipboard.setText(name)
  5048. self.inform.emit(_("Name copied on clipboard ..."))
  5049. def on_mouse_click_over_plot(self, event):
  5050. """
  5051. Default actions are:
  5052. :param event: Contains information about the event, like which button
  5053. was clicked, the pixel coordinates and the axes coordinates.
  5054. :return: None
  5055. """
  5056. self.pos = []
  5057. if self.is_legacy is False:
  5058. event_pos = event.pos
  5059. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5060. # # Set the mouse button for panning
  5061. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5062. else:
  5063. event_pos = (event.xdata, event.ydata)
  5064. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5065. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5066. # So it can receive key presses
  5067. self.plotcanvas.native.setFocus()
  5068. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5069. if self.grid_status():
  5070. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5071. else:
  5072. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5073. try:
  5074. if event.button == 1:
  5075. # Reset here the relative coordinates so there is a new reference on the click position
  5076. if self.rel_point1 is None:
  5077. self.rel_point1 = self.pos
  5078. else:
  5079. self.rel_point2 = copy(self.rel_point1)
  5080. self.rel_point1 = self.pos
  5081. self.on_mouse_move_over_plot(event, origin_click=True)
  5082. except Exception as e:
  5083. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5084. def on_mouse_double_click_over_plot(self, event):
  5085. if event.button == 1:
  5086. self.doubleclick = True
  5087. def on_mouse_move_over_plot(self, event, origin_click=None):
  5088. """
  5089. Callback for the mouse motion event over the plot.
  5090. :param event: Contains information about the event.
  5091. :param origin_click
  5092. :return: None
  5093. """
  5094. if self.is_legacy is False:
  5095. event_pos = event.pos
  5096. if self.defaults["global_pan_button"] == '2':
  5097. pan_button = 2
  5098. else:
  5099. pan_button = 3
  5100. self.event_is_dragging = event.is_dragging
  5101. else:
  5102. event_pos = (event.xdata, event.ydata)
  5103. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5104. if self.defaults["global_pan_button"] == '2':
  5105. pan_button = 3
  5106. else:
  5107. pan_button = 2
  5108. self.event_is_dragging = self.plotcanvas.is_dragging
  5109. # So it can receive key presses but not when the Tcl Shell is active
  5110. if not self.ui.shell_dock.isVisible():
  5111. if not self.plotcanvas.native.hasFocus():
  5112. self.plotcanvas.native.setFocus()
  5113. self.pos_jump = event_pos
  5114. self.ui.popMenu.mouse_is_panning = False
  5115. if origin_click is None:
  5116. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5117. if event.button == pan_button and self.event_is_dragging == 1:
  5118. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5119. if self.ui.popMenu.popup_active:
  5120. self.ui.popMenu.popup_active = False
  5121. return
  5122. self.ui.popMenu.mouse_is_panning = True
  5123. return
  5124. if self.rel_point1 is not None:
  5125. try: # May fail in case mouse not within axes
  5126. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5127. if pos_canvas[0] is None or pos_canvas[1] is None:
  5128. return
  5129. if self.grid_status():
  5130. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5131. # Update cursor
  5132. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5133. symbol='++', edge_color=self.cursor_color_3D,
  5134. edge_width=self.defaults["global_cursor_width"],
  5135. size=self.defaults["global_cursor_size"])
  5136. else:
  5137. pos = (pos_canvas[0], pos_canvas[1])
  5138. self.dx = pos[0] - float(self.rel_point1[0])
  5139. self.dy = pos[1] - float(self.rel_point1[1])
  5140. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5141. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  5142. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5143. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5144. units = self.defaults["units"].lower()
  5145. self.plotcanvas.text_hud.text = \
  5146. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  5147. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  5148. self.mouse = [pos[0], pos[1]]
  5149. if self.defaults['global_selection_shape'] is False:
  5150. self.selection_type = None
  5151. return
  5152. # if the mouse is moved and the LMB is clicked then the action is a selection
  5153. if self.event_is_dragging == 1 and event.button == 1:
  5154. self.delete_selection_shape()
  5155. if self.dx < 0:
  5156. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5157. face_color=self.defaults['global_alt_sel_fill'])
  5158. self.selection_type = False
  5159. elif self.dx >= 0:
  5160. self.draw_moving_selection_shape(self.pos, pos)
  5161. self.selection_type = True
  5162. else:
  5163. self.selection_type = None
  5164. else:
  5165. self.selection_type = None
  5166. # hover effect - enabled in Preferences -> General -> appGUI Settings
  5167. if self.defaults['global_hover']:
  5168. for obj in self.collection.get_list():
  5169. try:
  5170. # select the object(s) only if it is enabled (plotted)
  5171. if obj.options['plot']:
  5172. if obj not in self.collection.get_selected():
  5173. poly_obj = Polygon(
  5174. [(obj.options['xmin'], obj.options['ymin']),
  5175. (obj.options['xmax'], obj.options['ymin']),
  5176. (obj.options['xmax'], obj.options['ymax']),
  5177. (obj.options['xmin'], obj.options['ymax'])]
  5178. )
  5179. if Point(pos).within(poly_obj):
  5180. if obj.isHovering is False:
  5181. obj.isHovering = True
  5182. obj.notHovering = True
  5183. # create the selection box around the selected object
  5184. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5185. else:
  5186. if obj.notHovering is True:
  5187. obj.notHovering = False
  5188. obj.isHovering = False
  5189. self.delete_hover_shape()
  5190. except Exception:
  5191. # the Exception here will happen if we try to select on screen and we have an
  5192. # newly (and empty) just created Geometry or Excellon object that do not have the
  5193. # xmin, xmax, ymin, ymax options.
  5194. # In this case poly_obj creation (see above) will fail
  5195. pass
  5196. except Exception as e:
  5197. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5198. self.ui.position_label.setText("")
  5199. self.ui.rel_position_label.setText("")
  5200. self.mouse = None
  5201. def on_mouse_click_release_over_plot(self, event):
  5202. """
  5203. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5204. and has been registered in ''self.__init__()''.
  5205. :param event: contains information about the event.
  5206. :return:
  5207. """
  5208. if self.is_legacy is False:
  5209. event_pos = event.pos
  5210. right_button = 2
  5211. else:
  5212. event_pos = (event.xdata, event.ydata)
  5213. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5214. right_button = 3
  5215. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5216. if self.grid_status():
  5217. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5218. else:
  5219. pos = (pos_canvas[0], pos_canvas[1])
  5220. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5221. # canvas menu
  5222. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5223. self.ui.popMenu.mouse_is_panning = False
  5224. self.cursor = QtGui.QCursor()
  5225. self.populate_cmenu_grids()
  5226. self.ui.popMenu.popup(self.cursor.pos())
  5227. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5228. # selection and then select a type of selection ("enclosing" or "touching")
  5229. if event.button == 1: # left click
  5230. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5231. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5232. if modifiers == QtCore.Qt.ShiftModifier:
  5233. # do not auto open the Project Tab
  5234. self.click_noproject = True
  5235. self.clipboard.setText(
  5236. self.defaults["global_point_clipboard_format"] %
  5237. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5238. )
  5239. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5240. return
  5241. if self.doubleclick is True:
  5242. self.doubleclick = False
  5243. if self.collection.get_selected():
  5244. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5245. if self.ui.splitter.sizes()[0] == 0:
  5246. self.ui.splitter.setSizes([1, 1])
  5247. try:
  5248. # delete the selection shape(S) as it may be in the way
  5249. self.delete_selection_shape()
  5250. self.delete_hover_shape()
  5251. except Exception as e:
  5252. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5253. return
  5254. else:
  5255. # WORKAROUND for LEGACY MODE
  5256. if self.is_legacy is True:
  5257. # if there is no move on canvas then we have no dragging selection
  5258. if self.dx == 0 or self.dy == 0:
  5259. self.selection_type = None
  5260. if self.selection_type is not None:
  5261. try:
  5262. self.selection_area_handler(self.pos, pos, self.selection_type)
  5263. self.selection_type = None
  5264. except Exception as e:
  5265. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5266. return
  5267. else:
  5268. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5269. if key_modifier == QtCore.Qt.ShiftModifier:
  5270. mod_key = 'Shift'
  5271. elif key_modifier == QtCore.Qt.ControlModifier:
  5272. mod_key = 'Control'
  5273. else:
  5274. mod_key = None
  5275. try:
  5276. if self.command_active is None:
  5277. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5278. # deselect, and if it's not selected then it will be selected
  5279. # If there is no active command (self.command_active is None) then we check if we clicked
  5280. # on a object by checking the bounding limits against mouse click position
  5281. if mod_key == self.defaults["global_mselect_key"]:
  5282. self.select_objects(key='multisel')
  5283. else:
  5284. # If there is no active command (self.command_active is None) then we check if
  5285. # we clicked on a object by checking the bounding limits against mouse click position
  5286. self.select_objects()
  5287. self.delete_hover_shape()
  5288. except Exception as e:
  5289. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5290. return
  5291. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5292. """
  5293. :param start_pos: mouse position when the selection LMB click was done
  5294. :param end_pos: mouse position when the left mouse button is released
  5295. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5296. :return:
  5297. """
  5298. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5299. # delete previous selection shape
  5300. self.delete_selection_shape()
  5301. # make all objects inactive
  5302. self.collection.set_all_inactive()
  5303. for obj in self.collection.get_list():
  5304. try:
  5305. # select the object(s) only if it is enabled (plotted)
  5306. if obj.options['plot']:
  5307. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5308. (obj.options['xmax'], obj.options['ymin']),
  5309. (obj.options['xmax'], obj.options['ymax']),
  5310. (obj.options['xmin'], obj.options['ymax'])])
  5311. if sel_type is True:
  5312. if poly_obj.within(poly_selection):
  5313. # create the selection box around the selected object
  5314. if self.defaults['global_selection_shape'] is True:
  5315. self.draw_selection_shape(obj)
  5316. self.collection.set_active(obj.options['name'])
  5317. else:
  5318. if poly_selection.intersects(poly_obj):
  5319. # create the selection box around the selected object
  5320. if self.defaults['global_selection_shape'] is True:
  5321. self.draw_selection_shape(obj)
  5322. self.collection.set_active(obj.options['name'])
  5323. obj.selection_shape_drawn = True
  5324. except Exception as e:
  5325. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5326. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5327. # In this case poly_obj creation (see above) will fail
  5328. log.debug("App.selection_area_handler() --> %s" % str(e))
  5329. def select_objects(self, key=None):
  5330. """
  5331. Will select objects clicked on canvas
  5332. :param key: for future use in cumulative selection
  5333. :return:
  5334. """
  5335. # list where we store the overlapped objects under our mouse left click position
  5336. if key is None:
  5337. self.objects_under_the_click_list = []
  5338. # Populate the list with the overlapped objects on the click position
  5339. curr_x, curr_y = self.pos
  5340. for obj in self.all_objects_list:
  5341. # ScriptObject and DocumentObject objects can't be selected
  5342. if obj.kind == 'script' or obj.kind == 'document':
  5343. continue
  5344. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5345. continue
  5346. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5347. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5348. if obj.options['name'] not in self.objects_under_the_click_list:
  5349. if obj.options['plot']:
  5350. # add objects to the objects_under_the_click list only if the object is plotted
  5351. # (active and not disabled)
  5352. self.objects_under_the_click_list.append(obj.options['name'])
  5353. try:
  5354. if self.objects_under_the_click_list:
  5355. curr_sel_obj = self.collection.get_active()
  5356. # case when there is only an object under the click and we toggle it
  5357. if len(self.objects_under_the_click_list) == 1:
  5358. if curr_sel_obj is None:
  5359. self.collection.set_active(self.objects_under_the_click_list[0])
  5360. curr_sel_obj = self.collection.get_active()
  5361. # create the selection box around the selected object
  5362. if self.defaults['global_selection_shape'] is True:
  5363. self.draw_selection_shape(curr_sel_obj)
  5364. curr_sel_obj.selection_shape_drawn = True
  5365. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5366. self.collection.on_objects_selection(False)
  5367. self.delete_selection_shape()
  5368. curr_sel_obj.selection_shape_drawn = False
  5369. self.collection.set_active(self.objects_under_the_click_list[0])
  5370. curr_sel_obj = self.collection.get_active()
  5371. # create the selection box around the selected object
  5372. if self.defaults['global_selection_shape'] is True:
  5373. self.draw_selection_shape(curr_sel_obj)
  5374. curr_sel_obj.selection_shape_drawn = True
  5375. self.selected_message(curr_sel_obj=curr_sel_obj)
  5376. elif curr_sel_obj.selection_shape_drawn is False:
  5377. if self.defaults['global_selection_shape'] is True:
  5378. self.draw_selection_shape(curr_sel_obj)
  5379. curr_sel_obj.selection_shape_drawn = True
  5380. else:
  5381. self.collection.on_objects_selection(False)
  5382. self.delete_selection_shape()
  5383. if self.call_source != 'app':
  5384. self.call_source = 'app'
  5385. self.selected_message(curr_sel_obj=curr_sel_obj)
  5386. else:
  5387. # If there is no selected object
  5388. # make active the first element of the overlapped objects list
  5389. if self.collection.get_active() is None:
  5390. self.collection.set_active(self.objects_under_the_click_list[0])
  5391. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5392. name_sel_obj = self.collection.get_active().options['name']
  5393. # In case that there is a selected object but it is not in the overlapped object list
  5394. # make that object inactive and activate the first element in the overlapped object list
  5395. if name_sel_obj not in self.objects_under_the_click_list:
  5396. self.collection.set_inactive(name_sel_obj)
  5397. name_sel_obj = self.objects_under_the_click_list[0]
  5398. self.collection.set_active(name_sel_obj)
  5399. else:
  5400. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5401. self.collection.set_all_inactive()
  5402. self.collection.set_active(
  5403. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5404. curr_sel_obj = self.collection.get_active()
  5405. # delete the possible selection box around a possible selected object
  5406. self.delete_selection_shape()
  5407. curr_sel_obj.selection_shape_drawn = False
  5408. # create the selection box around the selected object
  5409. if self.defaults['global_selection_shape'] is True:
  5410. self.draw_selection_shape(curr_sel_obj)
  5411. curr_sel_obj.selection_shape_drawn = True
  5412. self.selected_message(curr_sel_obj=curr_sel_obj)
  5413. else:
  5414. # deselect everything
  5415. self.collection.on_objects_selection(False)
  5416. # delete the possible selection box around a possible selected object
  5417. self.delete_selection_shape()
  5418. for o in self.collection.get_list():
  5419. o.selection_shape_drawn = False
  5420. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5421. # only when working on App
  5422. if self.call_source == 'app':
  5423. if self.click_noproject is False:
  5424. # if the Tool Tab is in focus don't change focus to Project Tab
  5425. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5426. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5427. else:
  5428. # restore auto open the Project Tab
  5429. self.click_noproject = False
  5430. # delete any text in the status bar, implicitly the last object name that was selected
  5431. # self.inform.emit("")
  5432. else:
  5433. self.call_source = 'app'
  5434. except Exception as e:
  5435. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5436. def selected_message(self, curr_sel_obj):
  5437. if curr_sel_obj:
  5438. if curr_sel_obj.kind == 'gerber':
  5439. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5440. color='green',
  5441. name=str(curr_sel_obj.options['name']),
  5442. tx=_("selected"))
  5443. )
  5444. elif curr_sel_obj.kind == 'excellon':
  5445. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5446. color='brown',
  5447. name=str(curr_sel_obj.options['name']),
  5448. tx=_("selected"))
  5449. )
  5450. elif curr_sel_obj.kind == 'cncjob':
  5451. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5452. color='blue',
  5453. name=str(curr_sel_obj.options['name']),
  5454. tx=_("selected"))
  5455. )
  5456. elif curr_sel_obj.kind == 'geometry':
  5457. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5458. color='red',
  5459. name=str(curr_sel_obj.options['name']),
  5460. tx=_("selected"))
  5461. )
  5462. def delete_hover_shape(self):
  5463. self.hover_shapes.clear()
  5464. self.hover_shapes.redraw()
  5465. def draw_hover_shape(self, sel_obj, color=None):
  5466. """
  5467. :param sel_obj: The object for which the hover shape must be drawn
  5468. :param color: The color of the hover shape
  5469. :return: None
  5470. """
  5471. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5472. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5473. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5474. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5475. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5476. if self.defaults['units'].upper() == 'MM':
  5477. hover_rect = hover_rect.buffer(-0.1)
  5478. hover_rect = hover_rect.buffer(0.2)
  5479. else:
  5480. hover_rect = hover_rect.buffer(-0.00393)
  5481. hover_rect = hover_rect.buffer(0.00787)
  5482. # if color:
  5483. # face = Color(color)
  5484. # face.alpha = 0.2
  5485. # outline = Color(color, alpha=0.8)
  5486. # else:
  5487. # face = Color(self.defaults['global_sel_fill'])
  5488. # face.alpha = 0.2
  5489. # outline = self.defaults['global_sel_line']
  5490. if color:
  5491. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5492. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5493. else:
  5494. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5495. outline = self.defaults['global_sel_line']
  5496. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5497. if self.is_legacy is True:
  5498. self.hover_shapes.redraw()
  5499. def delete_selection_shape(self):
  5500. self.move_tool.sel_shapes.clear()
  5501. self.move_tool.sel_shapes.redraw()
  5502. def draw_selection_shape(self, sel_obj, color=None):
  5503. """
  5504. Will draw a selection shape around the selected object.
  5505. :param sel_obj: The object for which the selection shape must be drawn
  5506. :param color: The color for the selection shape.
  5507. :return: None
  5508. """
  5509. if sel_obj is None:
  5510. return
  5511. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5512. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5513. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5514. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5515. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5516. if self.defaults['units'].upper() == 'MM':
  5517. sel_rect = sel_rect.buffer(-0.1)
  5518. sel_rect = sel_rect.buffer(0.2)
  5519. else:
  5520. sel_rect = sel_rect.buffer(-0.00393)
  5521. sel_rect = sel_rect.buffer(0.00787)
  5522. if color:
  5523. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5524. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5525. else:
  5526. if self.is_legacy is False:
  5527. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5528. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5529. else:
  5530. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5531. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5532. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5533. color=outline,
  5534. face_color=face,
  5535. update=True,
  5536. layer=0,
  5537. tolerance=None))
  5538. if self.is_legacy is True:
  5539. self.move_tool.sel_shapes.redraw()
  5540. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5541. """
  5542. Will draw a selection shape when dragging mouse on canvas.
  5543. :param old_coords: Old coordinates
  5544. :param coords: New coordinates
  5545. :param kwargs: Keyword arguments
  5546. :return:
  5547. """
  5548. if 'color' in kwargs:
  5549. color = kwargs['color']
  5550. else:
  5551. color = self.defaults['global_sel_line']
  5552. if 'face_color' in kwargs:
  5553. face_color = kwargs['face_color']
  5554. else:
  5555. face_color = self.defaults['global_sel_fill']
  5556. if 'face_alpha' in kwargs:
  5557. face_alpha = kwargs['face_alpha']
  5558. else:
  5559. face_alpha = 0.3
  5560. x0, y0 = old_coords
  5561. x1, y1 = coords
  5562. pt1 = (x0, y0)
  5563. pt2 = (x1, y0)
  5564. pt3 = (x1, y1)
  5565. pt4 = (x0, y1)
  5566. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5567. # color_t = Color(face_color)
  5568. # color_t.alpha = face_alpha
  5569. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5570. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5571. layer=0, tolerance=None)
  5572. if self.is_legacy is True:
  5573. self.move_tool.sel_shapes.redraw()
  5574. def on_file_new_click(self):
  5575. """
  5576. Callback for menu item File -> New.
  5577. Executed on clicking the Menu -> File -> New Project
  5578. :return:
  5579. """
  5580. if self.collection.get_list() and self.should_we_save:
  5581. msgbox = QtWidgets.QMessageBox()
  5582. # msgbox.setText("<B>Save changes ...</B>")
  5583. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5584. "Creating a New project will delete them.\n"
  5585. "Do you want to Save the project?"))
  5586. msgbox.setWindowTitle(_("Save changes"))
  5587. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5588. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  5589. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5590. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5591. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5592. msgbox.setDefaultButton(bt_yes)
  5593. msgbox.exec_()
  5594. response = msgbox.clickedButton()
  5595. if response == bt_yes:
  5596. self.on_file_saveprojectas()
  5597. elif response == bt_cancel:
  5598. return
  5599. elif response == bt_no:
  5600. self.on_file_new()
  5601. else:
  5602. self.on_file_new()
  5603. self.inform.emit('[success] %s...' % _("New Project created"))
  5604. def on_file_new(self, cli=None):
  5605. """
  5606. Returns the application to its startup state. This method is thread-safe.
  5607. :param cli: Boolean. If True this method was run from command line
  5608. :return: None
  5609. """
  5610. self.defaults.report_usage("on_file_new")
  5611. # Remove everything from memory
  5612. App.log.debug("on_file_new()")
  5613. # close any editor that might be open
  5614. if self.call_source != 'app':
  5615. self.editor2object(cleanup=True)
  5616. # ## EDITOR section
  5617. self.geo_editor = AppGeoEditor(self)
  5618. self.exc_editor = AppExcEditor(self)
  5619. self.grb_editor = AppGerberEditor(self)
  5620. # Clear pool
  5621. self.clear_pool()
  5622. for obj in self.collection.get_list():
  5623. # delete shapes left drawn from mark shape_collections, if any
  5624. if isinstance(obj, GerberObject):
  5625. try:
  5626. obj.mark_shapes_storage.clear()
  5627. obj.mark_shapes.clear(update=True)
  5628. obj.mark_shapes.enabled = False
  5629. except AttributeError:
  5630. pass
  5631. # also delete annotation shapes, if any
  5632. elif isinstance(obj, CNCJobObject):
  5633. try:
  5634. obj.text_col.enabled = False
  5635. del obj.text_col
  5636. obj.annotation.clear(update=True)
  5637. del obj.annotation
  5638. except AttributeError:
  5639. pass
  5640. # delete the exclusion areas
  5641. self.exc_areas.clear_shapes()
  5642. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5643. self.shell.init_tcl()
  5644. # delete any selection shape on canvas
  5645. self.delete_selection_shape()
  5646. # delete all FlatCAM objects
  5647. self.collection.delete_all()
  5648. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  5649. self.setup_component_editor()
  5650. # Clear project filename
  5651. self.project_filename = None
  5652. # Load the application defaults
  5653. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  5654. # Re-fresh project options
  5655. self.on_options_app2project()
  5656. # Init FlatCAMTools
  5657. self.init_tools()
  5658. # Try to close all tabs in the PlotArea but only if the appGUI is active (CLI is None)
  5659. if cli is None:
  5660. # we need to go in reverse because once we remove a tab then the index changes
  5661. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  5662. # and so on. Therefore the deletion should be done in reverse
  5663. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  5664. for index in range(wdg_count, -1, -1):
  5665. try:
  5666. self.ui.plot_tab_area.closeTab(index)
  5667. except Exception as e:
  5668. log.debug("App.on_file_new() --> %s" % str(e))
  5669. # # And then add again the Plot Area
  5670. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5671. self.ui.plot_tab_area.protectTab(0)
  5672. # take the focus of the Notebook on Project Tab.
  5673. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5674. self.set_ui_title(name=_("New Project - Not saved"))
  5675. def obj_properties(self):
  5676. """
  5677. Will launch the object Properties Tool
  5678. :return:
  5679. """
  5680. self.defaults.report_usage("obj_properties()")
  5681. self.properties_tool.run(toggle=False)
  5682. def on_project_context_save(self):
  5683. """
  5684. Wrapper, will save the object function of it's type
  5685. :return:
  5686. """
  5687. sel_objects = self.collection.get_selected()
  5688. len_objects = len(sel_objects)
  5689. cnt = 0
  5690. if len_objects > 1:
  5691. for o in sel_objects:
  5692. if o.kind == 'cncjob':
  5693. cnt += 1
  5694. if len_objects == cnt:
  5695. # all selected objects are of type CNCJOB therefore we issue a multiple save
  5696. _filter_ = self.defaults['cncjob_save_filters'] + \
  5697. ";;RML1 Files .rol (*.rol);;HPGL Files .plt (*.plt)"
  5698. dir_file_to_save = self.get_last_save_folder() + '/multi_save'
  5699. try:
  5700. filename, _f = FCFileSaveDialog.get_saved_filename(
  5701. caption=_("Export Code ..."),
  5702. directory=dir_file_to_save,
  5703. ext_filter=_filter_
  5704. )
  5705. except TypeError:
  5706. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Code ..."),
  5707. ext_filter=_filter_)
  5708. filename = filename.rpartition('/')[0]
  5709. for ob in sel_objects:
  5710. ob.read_form()
  5711. fname = '%s/%s' % (filename, ob.options['name'])
  5712. ob.export_gcode_handler(fname, is_gcode=True)
  5713. return
  5714. obj = self.collection.get_active()
  5715. if type(obj) == GeometryObject:
  5716. self.on_file_exportdxf()
  5717. elif type(obj) == ExcellonObject:
  5718. self.on_file_saveexcellon()
  5719. elif type(obj) == CNCJobObject:
  5720. obj.on_exportgcode_button_click()
  5721. elif type(obj) == GerberObject:
  5722. self.on_file_savegerber()
  5723. elif type(obj) == ScriptObject:
  5724. self.on_file_savescript()
  5725. elif type(obj) == DocumentObject:
  5726. self.on_file_savedocument()
  5727. def obj_move(self):
  5728. """
  5729. Callback for the Move menu entry in various Context Menu's.
  5730. :return:
  5731. """
  5732. self.defaults.report_usage("obj_move()")
  5733. self.move_tool.run(toggle=False)
  5734. def on_fileopengerber(self, signal, name=None):
  5735. """
  5736. File menu callback for opening a Gerber.
  5737. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5738. :param name:
  5739. :return: None
  5740. """
  5741. self.defaults.report_usage("on_fileopengerber")
  5742. App.log.debug("on_fileopengerber()")
  5743. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 " \
  5744. "*.gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb " \
  5745. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.outline);;" \
  5746. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko " \
  5747. "*.outline);;" \
  5748. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5749. "*.mil);;" \
  5750. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5751. "Allegro Files (*.art);;" \
  5752. "Mentor Files (*.pho *.gdo);;" \
  5753. "All Files (*.*)"
  5754. if name is None:
  5755. try:
  5756. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5757. directory=self.get_last_folder(),
  5758. filter=_filter_,
  5759. initialFilter=self.last_op_gerber_filter)
  5760. except TypeError:
  5761. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5762. filenames = [str(filename) for filename in filenames]
  5763. self.last_op_gerber_filter = _f
  5764. else:
  5765. filenames = [name]
  5766. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5767. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5768. _("Opening Gerber file.")),
  5769. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5770. color=QtGui.QColor("gray"))
  5771. if len(filenames) == 0:
  5772. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5773. else:
  5774. for filename in filenames:
  5775. if filename != '':
  5776. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  5777. def on_fileopenexcellon(self, signal, name=None):
  5778. """
  5779. File menu callback for opening an Excellon file.
  5780. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5781. :param name:
  5782. :return: None
  5783. """
  5784. self.defaults.report_usage("on_fileopenexcellon")
  5785. App.log.debug("on_fileopenexcellon()")
  5786. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5787. "All Files (*.*)"
  5788. if name is None:
  5789. try:
  5790. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5791. directory=self.get_last_folder(),
  5792. filter=_filter_,
  5793. initialFilter=self.last_op_excellon_filter)
  5794. except TypeError:
  5795. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5796. filenames = [str(filename) for filename in filenames]
  5797. self.last_op_excellon_filter = _f
  5798. else:
  5799. filenames = [str(name)]
  5800. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5801. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5802. _("Opening Excellon file.")),
  5803. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5804. color=QtGui.QColor("gray"))
  5805. if len(filenames) == 0:
  5806. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5807. else:
  5808. for filename in filenames:
  5809. if filename != '':
  5810. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  5811. def on_fileopengcode(self, signal, name=None):
  5812. """
  5813. File menu call back for opening gcode.
  5814. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5815. :param name:
  5816. :return:
  5817. """
  5818. self.defaults.report_usage("on_fileopengcode")
  5819. App.log.debug("on_fileopengcode()")
  5820. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5821. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5822. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  5823. "All Files (*.*)"
  5824. if name is None:
  5825. try:
  5826. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5827. directory=self.get_last_folder(),
  5828. filter=_filter_,
  5829. initialFilter=self.last_op_gcode_filter)
  5830. except TypeError:
  5831. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5832. filenames = [str(filename) for filename in filenames]
  5833. self.last_op_gcode_filter = _f
  5834. else:
  5835. filenames = [name]
  5836. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5837. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5838. _("Opening G-Code file.")),
  5839. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5840. color=QtGui.QColor("gray"))
  5841. if len(filenames) == 0:
  5842. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5843. else:
  5844. for filename in filenames:
  5845. if filename != '':
  5846. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  5847. def on_file_openproject(self, signal):
  5848. """
  5849. File menu callback for opening a project.
  5850. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5851. :return: None
  5852. """
  5853. self.defaults.report_usage("on_file_openproject")
  5854. App.log.debug("on_file_openproject()")
  5855. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5856. try:
  5857. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5858. directory=self.get_last_folder(), filter=_filter_)
  5859. except TypeError:
  5860. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  5861. # The Qt methods above will return a QString which can cause problems later.
  5862. # So far json.dump() will fail to serialize it.
  5863. # TODO: Improve the serialization methods and remove this fix.
  5864. filename = str(filename)
  5865. if filename == "":
  5866. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5867. else:
  5868. # self.worker_task.emit({'fcn': self.open_project,
  5869. # 'params': [filename]})
  5870. # The above was failing because open_project() is not
  5871. # thread safe. The new_project()
  5872. self.open_project(filename)
  5873. def on_fileopenhpgl2(self, signal, name=None):
  5874. """
  5875. File menu callback for opening a HPGL2.
  5876. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5877. :param name:
  5878. :return: None
  5879. """
  5880. self.defaults.report_usage("on_fileopenhpgl2")
  5881. App.log.debug("on_fileopenhpgl2()")
  5882. _filter_ = "HPGL2 Files (*.plt);;" \
  5883. "All Files (*.*)"
  5884. if name is None:
  5885. try:
  5886. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  5887. directory=self.get_last_folder(),
  5888. filter=_filter_)
  5889. except TypeError:
  5890. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  5891. filenames = [str(filename) for filename in filenames]
  5892. else:
  5893. filenames = [name]
  5894. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5895. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5896. _("Opening HPGL2 file.")),
  5897. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5898. color=QtGui.QColor("gray"))
  5899. if len(filenames) == 0:
  5900. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5901. else:
  5902. for filename in filenames:
  5903. if filename != '':
  5904. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  5905. def on_file_openconfig(self, signal):
  5906. """
  5907. File menu callback for opening a config file.
  5908. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5909. :return: None
  5910. """
  5911. self.defaults.report_usage("on_file_openconfig")
  5912. App.log.debug("on_file_openconfig()")
  5913. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5914. try:
  5915. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5916. directory=self.data_path, filter=_filter_)
  5917. except TypeError:
  5918. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5919. filter=_filter_)
  5920. if filename == "":
  5921. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5922. else:
  5923. self.open_config_file(filename)
  5924. def on_file_exportsvg(self):
  5925. """
  5926. Callback for menu item File->Export SVG.
  5927. :return: None
  5928. """
  5929. self.defaults.report_usage("on_file_exportsvg")
  5930. App.log.debug("on_file_exportsvg()")
  5931. obj = self.collection.get_active()
  5932. if obj is None:
  5933. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5934. msg = _("Please Select a Geometry object to export")
  5935. msgbox = QtWidgets.QMessageBox()
  5936. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5937. msgbox.setInformativeText(msg)
  5938. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5939. msgbox.setDefaultButton(bt_ok)
  5940. msgbox.exec_()
  5941. return
  5942. # Check for more compatible types and add as required
  5943. if (not isinstance(obj, GeometryObject)
  5944. and not isinstance(obj, GerberObject)
  5945. and not isinstance(obj, CNCJobObject)
  5946. and not isinstance(obj, ExcellonObject)):
  5947. msg = '[ERROR_NOTCL] %s' % \
  5948. _("Only Geometry, Gerber and CNCJob objects can be used.")
  5949. msgbox = QtWidgets.QMessageBox()
  5950. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5951. msgbox.setInformativeText(msg)
  5952. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5953. msgbox.setDefaultButton(bt_ok)
  5954. msgbox.exec_()
  5955. return
  5956. name = obj.options["name"]
  5957. _filter = "SVG File (*.svg);;All Files (*.*)"
  5958. try:
  5959. filename, _f = FCFileSaveDialog.get_saved_filename(
  5960. caption=_("Export SVG"),
  5961. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  5962. ext_filter=_filter)
  5963. except TypeError:
  5964. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), ext_filter=_filter)
  5965. filename = str(filename)
  5966. if filename == "":
  5967. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5968. return
  5969. else:
  5970. self.export_svg(name, filename)
  5971. if self.defaults["global_open_style"] is False:
  5972. self.file_opened.emit("SVG", filename)
  5973. self.file_saved.emit("SVG", filename)
  5974. def on_file_exportpng(self):
  5975. self.defaults.report_usage("on_file_exportpng")
  5976. App.log.debug("on_file_exportpng()")
  5977. self.date = str(datetime.today()).rpartition('.')[0]
  5978. self.date = ''.join(c for c in self.date if c not in ':-')
  5979. self.date = self.date.replace(' ', '_')
  5980. data = None
  5981. if self.is_legacy is False:
  5982. image = _screenshot(alpha=False)
  5983. data = np.asarray(image)
  5984. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5985. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  5986. return
  5987. filter_ = "PNG File (*.png);;All Files (*.*)"
  5988. try:
  5989. filename, _f = FCFileSaveDialog.get_saved_filename(
  5990. caption=_("Export PNG Image"),
  5991. directory=self.get_last_save_folder() + '/png_' + self.date,
  5992. ext_filter=filter_)
  5993. except TypeError:
  5994. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), ext_filter=filter_)
  5995. filename = str(filename)
  5996. if filename == "":
  5997. self.inform.emit(_("Cancelled."))
  5998. return
  5999. else:
  6000. if self.is_legacy is False:
  6001. write_png(filename, data)
  6002. else:
  6003. self.plotcanvas.figure.savefig(filename)
  6004. if self.defaults["global_open_style"] is False:
  6005. self.file_opened.emit("png", filename)
  6006. self.file_saved.emit("png", filename)
  6007. def on_file_savegerber(self):
  6008. """
  6009. Callback for menu item in Project context menu.
  6010. :return: None
  6011. """
  6012. self.defaults.report_usage("on_file_savegerber")
  6013. App.log.debug("on_file_savegerber()")
  6014. obj = self.collection.get_active()
  6015. if obj is None:
  6016. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6017. return
  6018. # Check for more compatible types and add as required
  6019. if not isinstance(obj, GerberObject):
  6020. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6021. return
  6022. name = self.collection.get_active().options["name"]
  6023. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6024. try:
  6025. filename, _f = FCFileSaveDialog.get_saved_filename(
  6026. caption="Save Gerber source file",
  6027. directory=self.get_last_save_folder() + '/' + name,
  6028. ext_filter=_filter)
  6029. except TypeError:
  6030. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), ext_filter=_filter)
  6031. filename = str(filename)
  6032. if filename == "":
  6033. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6034. return
  6035. else:
  6036. self.save_source_file(name, filename)
  6037. if self.defaults["global_open_style"] is False:
  6038. self.file_opened.emit("Gerber", filename)
  6039. self.file_saved.emit("Gerber", filename)
  6040. def on_file_savescript(self):
  6041. """
  6042. Callback for menu item in Project context menu.
  6043. :return: None
  6044. """
  6045. self.defaults.report_usage("on_file_savescript")
  6046. App.log.debug("on_file_savescript()")
  6047. obj = self.collection.get_active()
  6048. if obj is None:
  6049. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6050. return
  6051. # Check for more compatible types and add as required
  6052. if not isinstance(obj, ScriptObject):
  6053. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6054. return
  6055. name = self.collection.get_active().options["name"]
  6056. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6057. try:
  6058. filename, _f = FCFileSaveDialog.get_saved_filename(
  6059. caption="Save Script source file",
  6060. directory=self.get_last_save_folder() + '/' + name,
  6061. ext_filter=_filter)
  6062. except TypeError:
  6063. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), ext_filter=_filter)
  6064. filename = str(filename)
  6065. if filename == "":
  6066. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6067. return
  6068. else:
  6069. self.save_source_file(name, filename)
  6070. if self.defaults["global_open_style"] is False:
  6071. self.file_opened.emit("Script", filename)
  6072. self.file_saved.emit("Script", filename)
  6073. def on_file_savedocument(self):
  6074. """
  6075. Callback for menu item in Project context menu.
  6076. :return: None
  6077. """
  6078. self.defaults.report_usage("on_file_savedocument")
  6079. App.log.debug("on_file_savedocument()")
  6080. obj = self.collection.get_active()
  6081. if obj is None:
  6082. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6083. return
  6084. # Check for more compatible types and add as required
  6085. if not isinstance(obj, ScriptObject):
  6086. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6087. return
  6088. name = self.collection.get_active().options["name"]
  6089. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6090. try:
  6091. filename, _f = FCFileSaveDialog.get_saved_filename(
  6092. caption="Save Document source file",
  6093. directory=self.get_last_save_folder() + '/' + name,
  6094. ext_filter=_filter)
  6095. except TypeError:
  6096. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"),
  6097. ext_filter=_filter)
  6098. filename = str(filename)
  6099. if filename == "":
  6100. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6101. return
  6102. else:
  6103. self.save_source_file(name, filename)
  6104. if self.defaults["global_open_style"] is False:
  6105. self.file_opened.emit("Document", filename)
  6106. self.file_saved.emit("Document", filename)
  6107. def on_file_saveexcellon(self):
  6108. """
  6109. Callback for menu item in project context menu.
  6110. :return: None
  6111. """
  6112. self.defaults.report_usage("on_file_saveexcellon")
  6113. App.log.debug("on_file_saveexcellon()")
  6114. obj = self.collection.get_active()
  6115. if obj is None:
  6116. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6117. return
  6118. # Check for more compatible types and add as required
  6119. if not isinstance(obj, ExcellonObject):
  6120. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6121. return
  6122. name = self.collection.get_active().options["name"]
  6123. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6124. try:
  6125. filename, _f = FCFileSaveDialog.get_saved_filename(
  6126. caption=_("Save Excellon source file"),
  6127. directory=self.get_last_save_folder() + '/' + name,
  6128. ext_filter=_filter)
  6129. except TypeError:
  6130. filename, _f = FCFileSaveDialog.get_saved_filename(
  6131. caption=_("Save Excellon source file"), ext_filter=_filter)
  6132. filename = str(filename)
  6133. if filename == "":
  6134. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6135. return
  6136. else:
  6137. self.save_source_file(name, filename)
  6138. if self.defaults["global_open_style"] is False:
  6139. self.file_opened.emit("Excellon", filename)
  6140. self.file_saved.emit("Excellon", filename)
  6141. def on_file_exportexcellon(self):
  6142. """
  6143. Callback for menu item File->Export->Excellon.
  6144. :return: None
  6145. """
  6146. self.defaults.report_usage("on_file_exportexcellon")
  6147. App.log.debug("on_file_exportexcellon()")
  6148. obj = self.collection.get_active()
  6149. if obj is None:
  6150. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6151. return
  6152. # Check for more compatible types and add as required
  6153. if not isinstance(obj, ExcellonObject):
  6154. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6155. return
  6156. name = self.collection.get_active().options["name"]
  6157. _filter = self.defaults["excellon_save_filters"]
  6158. try:
  6159. filename, _f = FCFileSaveDialog.get_saved_filename(
  6160. caption=_("Export Excellon"),
  6161. directory=self.get_last_save_folder() + '/' + name,
  6162. ext_filter=_filter)
  6163. except TypeError:
  6164. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), ext_filter=_filter)
  6165. filename = str(filename)
  6166. if filename == "":
  6167. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6168. return
  6169. else:
  6170. used_extension = filename.rpartition('.')[2]
  6171. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  6172. self.export_excellon(name, filename)
  6173. if self.defaults["global_open_style"] is False:
  6174. self.file_opened.emit("Excellon", filename)
  6175. self.file_saved.emit("Excellon", filename)
  6176. def on_file_exportgerber(self):
  6177. """
  6178. Callback for menu item File->Export->Gerber.
  6179. :return: None
  6180. """
  6181. self.defaults.report_usage("on_file_exportgerber")
  6182. App.log.debug("on_file_exportgerber()")
  6183. obj = self.collection.get_active()
  6184. if obj is None:
  6185. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6186. return
  6187. # Check for more compatible types and add as required
  6188. if not isinstance(obj, GerberObject):
  6189. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6190. return
  6191. name = self.collection.get_active().options["name"]
  6192. _filter_ = self.defaults['gerber_save_filters']
  6193. try:
  6194. filename, _f = FCFileSaveDialog.get_saved_filename(
  6195. caption=_("Export Gerber"),
  6196. directory=self.get_last_save_folder() + '/' + name,
  6197. ext_filter=_filter_)
  6198. except TypeError:
  6199. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), ext_filter=_filter_)
  6200. filename = str(filename)
  6201. if filename == "":
  6202. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6203. return
  6204. else:
  6205. used_extension = filename.rpartition('.')[2]
  6206. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  6207. self.export_gerber(name, filename)
  6208. if self.defaults["global_open_style"] is False:
  6209. self.file_opened.emit("Gerber", filename)
  6210. self.file_saved.emit("Gerber", filename)
  6211. def on_file_exportdxf(self):
  6212. """
  6213. Callback for menu item File->Export DXF.
  6214. :return: None
  6215. """
  6216. self.defaults.report_usage("on_file_exportdxf")
  6217. App.log.debug("on_file_exportdxf()")
  6218. obj = self.collection.get_active()
  6219. if obj is None:
  6220. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6221. msg = _("Please Select a Geometry object to export")
  6222. msgbox = QtWidgets.QMessageBox()
  6223. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6224. msgbox.setInformativeText(msg)
  6225. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6226. msgbox.setDefaultButton(bt_ok)
  6227. msgbox.exec_()
  6228. return
  6229. # Check for more compatible types and add as required
  6230. if not isinstance(obj, GeometryObject):
  6231. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6232. msgbox = QtWidgets.QMessageBox()
  6233. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6234. msgbox.setInformativeText(msg)
  6235. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6236. msgbox.setDefaultButton(bt_ok)
  6237. msgbox.exec_()
  6238. return
  6239. name = self.collection.get_active().options["name"]
  6240. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6241. try:
  6242. filename, _f = FCFileSaveDialog.get_saved_filename(
  6243. caption=_("Export DXF"),
  6244. directory=self.get_last_save_folder() + '/' + name,
  6245. ext_filter=_filter_)
  6246. except TypeError:
  6247. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), ext_filter=_filter_)
  6248. filename = str(filename)
  6249. if filename == "":
  6250. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6251. return
  6252. else:
  6253. self.export_dxf(name, filename)
  6254. if self.defaults["global_open_style"] is False:
  6255. self.file_opened.emit("DXF", filename)
  6256. self.file_saved.emit("DXF", filename)
  6257. def on_file_importsvg(self, type_of_obj):
  6258. """
  6259. Callback for menu item File->Import SVG.
  6260. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6261. :type type_of_obj: str
  6262. :return: None
  6263. """
  6264. self.defaults.report_usage("on_file_importsvg")
  6265. App.log.debug("on_file_importsvg()")
  6266. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6267. try:
  6268. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6269. directory=self.get_last_folder(), filter=_filter_)
  6270. except TypeError:
  6271. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6272. filter=_filter_)
  6273. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6274. type_of_obj = "geometry"
  6275. filenames = [str(filename) for filename in filenames]
  6276. if len(filenames) == 0:
  6277. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6278. else:
  6279. for filename in filenames:
  6280. if filename != '':
  6281. self.worker_task.emit({'fcn': self.import_svg,
  6282. 'params': [filename, type_of_obj]})
  6283. def on_file_importdxf(self, type_of_obj):
  6284. """
  6285. Callback for menu item File->Import DXF.
  6286. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6287. :type type_of_obj: str
  6288. :return: None
  6289. """
  6290. self.defaults.report_usage("on_file_importdxf")
  6291. App.log.debug("on_file_importdxf()")
  6292. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6293. try:
  6294. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6295. directory=self.get_last_folder(),
  6296. filter=_filter_)
  6297. except TypeError:
  6298. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6299. filter=_filter_)
  6300. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6301. type_of_obj = "geometry"
  6302. filenames = [str(filename) for filename in filenames]
  6303. if len(filenames) == 0:
  6304. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6305. else:
  6306. for filename in filenames:
  6307. if filename != '':
  6308. self.worker_task.emit({'fcn': self.import_dxf,
  6309. 'params': [filename, type_of_obj]})
  6310. # ###############################################################################################################
  6311. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6312. # ###############################################################################################################
  6313. def init_code_editor(self, name):
  6314. self.text_editor_tab = AppTextEditor(app=self, plain_text=True)
  6315. # add the tab if it was closed
  6316. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6317. self.text_editor_tab.setObjectName('text_editor_tab')
  6318. # delete the absolute and relative position and messages in the infobar
  6319. # self.ui.position_label.setText("")
  6320. # self.ui.rel_position_label.setText("")
  6321. # hide coordinates toolbars in the infobar while in DB
  6322. self.ui.coords_toolbar.hide()
  6323. self.ui.delta_coords_toolbar.hide()
  6324. self.toggle_codeeditor = True
  6325. self.text_editor_tab.code_editor.completer_enable = False
  6326. self.text_editor_tab.buttonRun.hide()
  6327. # make sure to keep a reference to the code editor
  6328. self.reference_code_editor = self.text_editor_tab.code_editor
  6329. # Switch plot_area to CNCJob tab
  6330. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6331. def on_view_source(self):
  6332. """
  6333. Called when the user wants to see the source file of the selected object
  6334. :return:
  6335. """
  6336. try:
  6337. obj = self.collection.get_active()
  6338. except Exception as e:
  6339. log.debug("App.on_view_source() --> %s" % str(e))
  6340. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6341. return 'fail'
  6342. if obj is None:
  6343. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6344. return 'fail'
  6345. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6346. self.proc_container.view.set_busy(_("Loading..."))
  6347. flt = "All Files (*.*)"
  6348. if obj.kind == 'gerber':
  6349. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6350. elif obj.kind == 'excellon':
  6351. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6352. elif obj.kind == 'cncjob':
  6353. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6354. self.source_editor_tab = AppTextEditor(app=self, plain_text=True)
  6355. # add the tab if it was closed
  6356. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6357. self.source_editor_tab.setObjectName('source_editor_tab')
  6358. # delete the absolute and relative position and messages in the infobar
  6359. # self.ui.position_label.setText("")
  6360. # self.ui.rel_position_label.setText("")
  6361. # hide coordinates toolbars in the infobar while in DB
  6362. self.ui.coords_toolbar.hide()
  6363. self.ui.delta_coords_toolbar.hide()
  6364. self.source_editor_tab.code_editor.completer_enable = False
  6365. self.source_editor_tab.buttonRun.hide()
  6366. # Switch plot_area to CNCJob tab
  6367. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6368. try:
  6369. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6370. except TypeError:
  6371. pass
  6372. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6373. try:
  6374. self.source_editor_tab.buttonSave.clicked.disconnect()
  6375. except TypeError:
  6376. pass
  6377. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6378. # then append the text from GCode to the text editor
  6379. if obj.kind == 'cncjob':
  6380. try:
  6381. file = obj.export_gcode(to_file=True)
  6382. if file == 'fail':
  6383. return 'fail'
  6384. except AttributeError:
  6385. self.inform.emit('[WARNING_NOTCL] %s' %
  6386. _("There is no selected object for which to see it's source file code."))
  6387. return 'fail'
  6388. else:
  6389. try:
  6390. file = StringIO(obj.source_file)
  6391. except (AttributeError, TypeError):
  6392. self.inform.emit('[WARNING_NOTCL] %s' %
  6393. _("There is no selected object for which to see it's source file code."))
  6394. return 'fail'
  6395. self.source_editor_tab.t_frame.hide()
  6396. try:
  6397. self.source_editor_tab.load_text(file.getvalue(), clear_text=True, move_to_start=True)
  6398. except Exception as e:
  6399. log.debug('App.on_view_source() -->%s' % str(e))
  6400. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6401. return
  6402. self.source_editor_tab.t_frame.show()
  6403. self.proc_container.view.set_idle()
  6404. # self.ui.show()
  6405. def on_toggle_code_editor(self):
  6406. self.defaults.report_usage("on_toggle_code_editor()")
  6407. if self.toggle_codeeditor is False:
  6408. self.init_code_editor(name=_("Code Editor"))
  6409. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6410. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6411. self.text_editor_tab.buttonSave.clicked.disconnect()
  6412. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6413. else:
  6414. for idx in range(self.ui.plot_tab_area.count()):
  6415. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6416. self.ui.plot_tab_area.closeTab(idx)
  6417. break
  6418. self.toggle_codeeditor = False
  6419. def on_code_editor_close(self):
  6420. self.toggle_codeeditor = False
  6421. def goto_text_line(self):
  6422. """
  6423. Will scroll a text to the specified text line.
  6424. :return: None
  6425. """
  6426. dia_box = Dialog_box(title=_("Go to Line ..."),
  6427. label=_("Line:"),
  6428. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6429. initial_text='')
  6430. try:
  6431. line = int(dia_box.location) - 1
  6432. except (ValueError, TypeError):
  6433. line = 0
  6434. if dia_box.ok:
  6435. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6436. # at the top of the window
  6437. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6438. # get the document() of the AppTextEditor
  6439. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6440. # create a Text Cursor based on the searched line
  6441. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6442. # set cursor of the code editor with the cursor at the searcehd line
  6443. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6444. def on_filenewscript(self, silent=False):
  6445. """
  6446. Will create a new script file and open it in the Code Editor
  6447. :param silent: if True will not display status messages
  6448. :return: None
  6449. """
  6450. if silent is False:
  6451. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6452. # delete the absolute and relative position and messages in the infobar
  6453. # self.ui.position_label.setText("")
  6454. # self.ui.rel_position_label.setText("")
  6455. # hide coordinates toolbars in the infobar while in DB
  6456. self.ui.coords_toolbar.hide()
  6457. self.ui.delta_coords_toolbar.hide()
  6458. self.app_obj.new_script_object()
  6459. # script_text = script_obj.source_file
  6460. #
  6461. # self.proc_container.view.set_busy(_("Loading..."))
  6462. # script_obj.script_editor_tab.t_frame.hide()
  6463. #
  6464. # script_obj.script_editor_tab.t_frame.show()
  6465. # self.proc_container.view.set_idle()
  6466. def on_fileopenscript(self, name=None, silent=False):
  6467. """
  6468. Will open a Tcl script file into the Code Editor
  6469. :param silent: if True will not display status messages
  6470. :param name: name of a Tcl script file to open
  6471. :return: None
  6472. """
  6473. self.defaults.report_usage("on_fileopenscript")
  6474. App.log.debug("on_fileopenscript()")
  6475. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6476. "All Files (*.*)"
  6477. if name:
  6478. filenames = [name]
  6479. else:
  6480. try:
  6481. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6482. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6483. except TypeError:
  6484. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6485. if len(filenames) == 0:
  6486. if silent is False:
  6487. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6488. else:
  6489. for filename in filenames:
  6490. if filename != '':
  6491. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6492. def on_fileopenscript_example(self, name=None, silent=False):
  6493. """
  6494. Will open a Tcl script file into the Code Editor
  6495. :param silent: if True will not display status messages
  6496. :param name: name of a Tcl script file to open
  6497. :return:
  6498. """
  6499. self.defaults.report_usage("on_fileopenscript_example")
  6500. log.debug("on_fileopenscript_example()")
  6501. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6502. "All Files (*.*)"
  6503. # test if the app was frozen and choose the path for the configuration file
  6504. if getattr(sys, "frozen", False) is True:
  6505. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6506. else:
  6507. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6508. if name:
  6509. filenames = [name]
  6510. else:
  6511. try:
  6512. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6513. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6514. except TypeError:
  6515. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6516. if len(filenames) == 0:
  6517. if silent is False:
  6518. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6519. else:
  6520. for filename in filenames:
  6521. if filename != '':
  6522. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6523. def on_filerunscript(self, name=None, silent=False):
  6524. """
  6525. File menu callback for loading and running a TCL script.
  6526. :param silent: if True will not display status messages
  6527. :param name: name of a Tcl script file to be run by FlatCAM
  6528. :return: None
  6529. """
  6530. self.defaults.report_usage("on_filerunscript")
  6531. App.log.debug("on_file_runscript()")
  6532. if name:
  6533. filename = name
  6534. if self.cmd_line_headless != 1:
  6535. self.splash.showMessage('%s: %ssec\n%s' %
  6536. (_("Canvas initialization started.\n"
  6537. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6538. _("Executing ScriptObject file.")
  6539. ),
  6540. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6541. color=QtGui.QColor("gray"))
  6542. else:
  6543. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6544. "All Files (*.*)"
  6545. try:
  6546. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6547. directory=self.get_last_folder(), filter=_filter_)
  6548. except TypeError:
  6549. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6550. # The Qt methods above will return a QString which can cause problems later.
  6551. # So far json.dump() will fail to serialize it.
  6552. filename = str(filename)
  6553. if filename == "":
  6554. if silent is False:
  6555. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6556. else:
  6557. if self.cmd_line_headless != 1:
  6558. if self.ui.shell_dock.isHidden():
  6559. self.ui.shell_dock.show()
  6560. try:
  6561. with open(filename, "r") as tcl_script:
  6562. cmd_line_shellfile_content = tcl_script.read()
  6563. if self.cmd_line_headless != 1:
  6564. self.shell.exec_command(cmd_line_shellfile_content)
  6565. else:
  6566. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6567. if silent is False:
  6568. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6569. except Exception as e:
  6570. log.debug("App.on_filerunscript() -> %s" % str(e))
  6571. sys.exit(2)
  6572. def on_file_saveproject(self, silent=False):
  6573. """
  6574. Callback for menu item File->Save Project. Saves the project to
  6575. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6576. if set to None. The project is saved by calling ``self.save_project()``.
  6577. :param silent: if True will not display status messages
  6578. :return: None
  6579. """
  6580. self.defaults.report_usage("on_file_saveproject")
  6581. if self.project_filename is None:
  6582. self.on_file_saveprojectas()
  6583. else:
  6584. self.worker_task.emit({'fcn': self.save_project,
  6585. 'params': [self.project_filename, silent]})
  6586. if self.defaults["global_open_style"] is False:
  6587. self.file_opened.emit("project", self.project_filename)
  6588. self.file_saved.emit("project", self.project_filename)
  6589. self.set_ui_title(name=self.project_filename)
  6590. self.should_we_save = False
  6591. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6592. """
  6593. Callback for menu item File->Save Project As... Opens a file
  6594. chooser and saves the project to the given file via
  6595. ``self.save_project()``.
  6596. :param make_copy if to be create a copy of the project; boolean
  6597. :param use_thread: if to be run in a separate thread; boolean
  6598. :param quit_action: if to be followed by quiting the application; boolean
  6599. :return: None
  6600. """
  6601. self.defaults.report_usage("on_file_saveprojectas")
  6602. self.date = str(datetime.today()).rpartition('.')[0]
  6603. self.date = ''.join(c for c in self.date if c not in ':-')
  6604. self.date = self.date.replace(' ', '_')
  6605. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6606. try:
  6607. filename, _f = FCFileSaveDialog.get_saved_filename(
  6608. caption=_("Save Project As ..."),
  6609. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6610. proj=_("Project")),
  6611. ext_filter=filter_
  6612. )
  6613. except TypeError:
  6614. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), ext_filter=filter_)
  6615. filename = str(filename)
  6616. if filename == '':
  6617. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6618. return
  6619. if use_thread is True:
  6620. self.worker_task.emit({'fcn': self.save_project,
  6621. 'params': [filename, quit_action]})
  6622. else:
  6623. self.save_project(filename, quit_action)
  6624. # self.save_project(filename)
  6625. if self.defaults["global_open_style"] is False:
  6626. self.file_opened.emit("project", filename)
  6627. self.file_saved.emit("project", filename)
  6628. if not make_copy:
  6629. self.project_filename = filename
  6630. self.set_ui_title(name=self.project_filename)
  6631. self.should_we_save = False
  6632. def on_file_save_objects_pdf(self, use_thread=True):
  6633. self.date = str(datetime.today()).rpartition('.')[0]
  6634. self.date = ''.join(c for c in self.date if c not in ':-')
  6635. self.date = self.date.replace(' ', '_')
  6636. try:
  6637. obj_selection = self.collection.get_selected()
  6638. if len(obj_selection) == 1:
  6639. obj_name = str(obj_selection[0].options['name'])
  6640. else:
  6641. obj_name = _("FlatCAM objects print")
  6642. except AttributeError as err:
  6643. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  6644. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6645. return
  6646. if not obj_selection:
  6647. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6648. return
  6649. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  6650. try:
  6651. filename, _f = FCFileSaveDialog.get_saved_filename(
  6652. caption=_("Save Object as PDF ..."),
  6653. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  6654. obj_name=obj_name,
  6655. date=self.date),
  6656. ext_filter=filter_
  6657. )
  6658. except TypeError:
  6659. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), ext_filter=filter_)
  6660. filename = str(filename)
  6661. if filename == '':
  6662. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6663. return
  6664. if use_thread is True:
  6665. self.proc_container.new(_("Printing PDF ... Please wait."))
  6666. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  6667. else:
  6668. self.save_pdf(filename, obj_selection)
  6669. # self.save_project(filename)
  6670. if self.defaults["global_open_style"] is False:
  6671. self.file_opened.emit("pdf", filename)
  6672. self.file_saved.emit("pdf", filename)
  6673. def save_pdf(self, file_name, obj_selection):
  6674. p_size = self.defaults['global_workspaceT']
  6675. orientation = self.defaults['global_workspace_orientation']
  6676. color = 'black'
  6677. transparency_level = 1.0
  6678. self.pagesize = {}
  6679. self.pagesize.update(
  6680. {
  6681. 'Bounds': None,
  6682. 'A0': (841 * mm, 1189 * mm),
  6683. 'A1': (594 * mm, 841 * mm),
  6684. 'A2': (420 * mm, 594 * mm),
  6685. 'A3': (297 * mm, 420 * mm),
  6686. 'A4': (210 * mm, 297 * mm),
  6687. 'A5': (148 * mm, 210 * mm),
  6688. 'A6': (105 * mm, 148 * mm),
  6689. 'A7': (74 * mm, 105 * mm),
  6690. 'A8': (52 * mm, 74 * mm),
  6691. 'A9': (37 * mm, 52 * mm),
  6692. 'A10': (26 * mm, 37 * mm),
  6693. 'B0': (1000 * mm, 1414 * mm),
  6694. 'B1': (707 * mm, 1000 * mm),
  6695. 'B2': (500 * mm, 707 * mm),
  6696. 'B3': (353 * mm, 500 * mm),
  6697. 'B4': (250 * mm, 353 * mm),
  6698. 'B5': (176 * mm, 250 * mm),
  6699. 'B6': (125 * mm, 176 * mm),
  6700. 'B7': (88 * mm, 125 * mm),
  6701. 'B8': (62 * mm, 88 * mm),
  6702. 'B9': (44 * mm, 62 * mm),
  6703. 'B10': (31 * mm, 44 * mm),
  6704. 'C0': (917 * mm, 1297 * mm),
  6705. 'C1': (648 * mm, 917 * mm),
  6706. 'C2': (458 * mm, 648 * mm),
  6707. 'C3': (324 * mm, 458 * mm),
  6708. 'C4': (229 * mm, 324 * mm),
  6709. 'C5': (162 * mm, 229 * mm),
  6710. 'C6': (114 * mm, 162 * mm),
  6711. 'C7': (81 * mm, 114 * mm),
  6712. 'C8': (57 * mm, 81 * mm),
  6713. 'C9': (40 * mm, 57 * mm),
  6714. 'C10': (28 * mm, 40 * mm),
  6715. # American paper sizes
  6716. 'LETTER': (8.5 * inch, 11 * inch),
  6717. 'LEGAL': (8.5 * inch, 14 * inch),
  6718. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  6719. # From https://en.wikipedia.org/wiki/Paper_size
  6720. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  6721. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  6722. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  6723. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  6724. 'LEDGER': (17 * inch, 11 * inch),
  6725. }
  6726. )
  6727. exported_svg = []
  6728. for obj in obj_selection:
  6729. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  6730. scale_factor_x=None, scale_factor_y=None,
  6731. skew_factor_x=None, skew_factor_y=None,
  6732. mirror=None)
  6733. if obj.kind.lower() == 'gerber':
  6734. # color = self.defaults["gerber_plot_fill"][:-2]
  6735. color = obj.fill_color[:-2]
  6736. elif obj.kind.lower() == 'excellon':
  6737. color = '#C40000'
  6738. elif obj.kind.lower() == 'geometry':
  6739. color = self.defaults["global_draw_color"]
  6740. # Change the attributes of the exported SVG
  6741. # We don't need stroke-width
  6742. # We set opacity to maximum
  6743. # We set the colour to WHITE
  6744. root = ET.fromstring(svg_obj)
  6745. for child in root:
  6746. child.set('fill', str(color))
  6747. child.set('opacity', str(transparency_level))
  6748. child.set('stroke', str(color))
  6749. exported_svg.append(ET.tostring(root))
  6750. xmin = Inf
  6751. ymin = Inf
  6752. xmax = -Inf
  6753. ymax = -Inf
  6754. for obj in obj_selection:
  6755. try:
  6756. gxmin, gymin, gxmax, gymax = obj.bounds()
  6757. xmin = min([xmin, gxmin])
  6758. ymin = min([ymin, gymin])
  6759. xmax = max([xmax, gxmax])
  6760. ymax = max([ymax, gymax])
  6761. except Exception as e:
  6762. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  6763. # Determine bounding area for svg export
  6764. bounds = [xmin, ymin, xmax, ymax]
  6765. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  6766. # This contain the measure units
  6767. uom = obj_selection[0].units.lower()
  6768. # Define a boundary around SVG of about 1.0mm (~39mils)
  6769. if uom in "mm":
  6770. boundary = 1.0
  6771. else:
  6772. boundary = 0.0393701
  6773. # Convert everything to strings for use in the xml doc
  6774. svgwidth = str(size[0] + (2 * boundary))
  6775. svgheight = str(size[1] + (2 * boundary))
  6776. minx = str(bounds[0] - boundary)
  6777. miny = str(bounds[1] + boundary + size[1])
  6778. # Add a SVG Header and footer to the svg output from shapely
  6779. # The transform flips the Y Axis so that everything renders
  6780. # properly within svg apps such as inkscape
  6781. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6782. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6783. svg_header += 'width="' + svgwidth + uom + '" '
  6784. svg_header += 'height="' + svgheight + uom + '" '
  6785. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6786. svg_header += '>'
  6787. svg_header += '<g transform="scale(1,-1)">'
  6788. svg_footer = '</g> </svg>'
  6789. svg_elem = str(svg_header)
  6790. for svg_item in exported_svg:
  6791. svg_elem += str(svg_item)
  6792. svg_elem += str(svg_footer)
  6793. # Parse the xml through a xml parser just to add line feeds
  6794. # and to make it look more pretty for the output
  6795. doc = parse_xml_string(svg_elem)
  6796. doc_final = doc.toprettyxml()
  6797. try:
  6798. if self.defaults['units'].upper() == 'IN':
  6799. unit = inch
  6800. else:
  6801. unit = mm
  6802. doc_final = StringIO(doc_final)
  6803. drawing = svg2rlg(doc_final)
  6804. if p_size == 'Bounds':
  6805. renderPDF.drawToFile(drawing, file_name)
  6806. else:
  6807. if orientation == 'p':
  6808. page_size = portrait(self.pagesize[p_size])
  6809. else:
  6810. page_size = landscape(self.pagesize[p_size])
  6811. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  6812. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  6813. renderPDF.draw(drawing, my_canvas, 0, 0)
  6814. my_canvas.save()
  6815. except Exception as e:
  6816. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  6817. return 'fail'
  6818. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  6819. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  6820. """
  6821. Exports a Geometry Object to an SVG file.
  6822. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6823. :param filename: Path to the SVG file to save to.
  6824. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  6825. :return:
  6826. """
  6827. self.defaults.report_usage("export_svg()")
  6828. if filename is None:
  6829. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6830. is not None else self.defaults["global_last_folder"]
  6831. self.log.debug("export_svg()")
  6832. try:
  6833. obj = self.collection.get_by_name(str(obj_name))
  6834. except Exception:
  6835. # TODO: The return behavior has not been established... should raise exception?
  6836. return "Could not retrieve object: %s" % obj_name
  6837. with self.proc_container.new(_("Exporting SVG")) as proc:
  6838. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  6839. # Determine bounding area for svg export
  6840. bounds = obj.bounds()
  6841. size = obj.size()
  6842. # Convert everything to strings for use in the xml doc
  6843. svgwidth = str(size[0])
  6844. svgheight = str(size[1])
  6845. minx = str(bounds[0])
  6846. miny = str(bounds[1] - size[1])
  6847. uom = obj.units.lower()
  6848. # Add a SVG Header and footer to the svg output from shapely
  6849. # The transform flips the Y Axis so that everything renders
  6850. # properly within svg apps such as inkscape
  6851. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6852. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6853. svg_header += 'width="' + svgwidth + uom + '" '
  6854. svg_header += 'height="' + svgheight + uom + '" '
  6855. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6856. svg_header += '<g transform="scale(1,-1)">'
  6857. svg_footer = '</g> </svg>'
  6858. svg_elem = svg_header + exported_svg + svg_footer
  6859. # Parse the xml through a xml parser just to add line feeds
  6860. # and to make it look more pretty for the output
  6861. svgcode = parse_xml_string(svg_elem)
  6862. svgcode = svgcode.toprettyxml()
  6863. try:
  6864. with open(filename, 'w') as fp:
  6865. fp.write(svgcode)
  6866. except PermissionError:
  6867. self.inform.emit('[WARNING] %s' %
  6868. _("Permission denied, saving not possible.\n"
  6869. "Most likely another app is holding the file open and not accessible."))
  6870. return 'fail'
  6871. if self.defaults["global_open_style"] is False:
  6872. self.file_opened.emit("SVG", filename)
  6873. self.file_saved.emit("SVG", filename)
  6874. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  6875. def save_source_file(self, obj_name, filename, use_thread=True):
  6876. """
  6877. Exports a FlatCAM Object to an Gerber/Excellon file.
  6878. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6879. :param filename: Path to the Gerber file to save to.
  6880. :param use_thread: if to be run in a separate thread
  6881. :return:
  6882. """
  6883. self.defaults.report_usage("save source file()")
  6884. if filename is None:
  6885. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6886. is not None else self.defaults["global_last_folder"]
  6887. self.log.debug("save source file()")
  6888. obj = self.collection.get_by_name(obj_name)
  6889. file_string = StringIO(obj.source_file)
  6890. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6891. if file_string.getvalue() == '':
  6892. self.inform.emit('[ERROR_NOTCL] %s' %
  6893. _("Save cancelled because source file is empty. Try to export the file."))
  6894. return 'fail'
  6895. try:
  6896. with open(filename, 'w') as file:
  6897. file.writelines('G04*\n')
  6898. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6899. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6900. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6901. file.writelines('G04 Created on : %s*\n' % time_string)
  6902. for line in file_string:
  6903. file.writelines(line)
  6904. except PermissionError:
  6905. self.inform.emit('[WARNING] %s' %
  6906. _("Permission denied, saving not possible.\n"
  6907. "Most likely another app is holding the file open and not accessible."))
  6908. return 'fail'
  6909. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  6910. """
  6911. Exports a Excellon Object to an Excellon file.
  6912. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6913. :param filename: Path to the Excellon file to save to.
  6914. :param local_use:
  6915. :param use_thread: if to be run in a separate thread
  6916. :return:
  6917. """
  6918. self.defaults.report_usage("export_excellon()")
  6919. if filename is None:
  6920. if self.defaults["global_last_save_folder"]:
  6921. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  6922. else:
  6923. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  6924. self.log.debug("export_excellon()")
  6925. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  6926. self.defaults["excellon_exp_decimals"]
  6927. )
  6928. if local_use is None:
  6929. try:
  6930. obj = self.collection.get_by_name(str(obj_name))
  6931. except Exception:
  6932. return "Could not retrieve object: %s" % obj_name
  6933. else:
  6934. obj = local_use
  6935. if not isinstance(obj, ExcellonObject):
  6936. self.inform.emit('[ERROR_NOTCL] %s' %
  6937. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6938. return
  6939. # updated units
  6940. eunits = self.defaults["excellon_exp_units"]
  6941. ewhole = self.defaults["excellon_exp_integer"]
  6942. efract = self.defaults["excellon_exp_decimals"]
  6943. ezeros = self.defaults["excellon_exp_zeros"]
  6944. eformat = self.defaults["excellon_exp_format"]
  6945. slot_type = self.defaults["excellon_exp_slot_type"]
  6946. fc_units = self.defaults['units'].upper()
  6947. if fc_units == 'MM':
  6948. factor = 1 if eunits == 'METRIC' else 0.03937
  6949. else:
  6950. factor = 25.4 if eunits == 'METRIC' else 1
  6951. def make_excellon():
  6952. try:
  6953. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6954. header = 'M48\n'
  6955. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  6956. (str(self.version), str(self.version_date))
  6957. header += ';Filename: %s' % str(obj_name) + '\n'
  6958. header += ';Created on : %s' % time_str + '\n'
  6959. if eformat == 'dec':
  6960. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  6961. header += eunits + '\n'
  6962. for tool in obj.tools:
  6963. if eunits == 'METRIC':
  6964. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  6965. tool=str(tool),
  6966. dec=2)
  6967. else:
  6968. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  6969. tool=str(tool),
  6970. dec=4)
  6971. else:
  6972. if ezeros == 'LZ':
  6973. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6974. form='ndec', e_zeros='LZ', factor=factor,
  6975. slot_type=slot_type)
  6976. header += '%s,%s\n' % (eunits, 'LZ')
  6977. header += format_exc
  6978. for tool in obj.tools:
  6979. if eunits == 'METRIC':
  6980. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  6981. float(obj.tools[tool]['tooldia']) * factor,
  6982. tool=str(tool),
  6983. dec=2)
  6984. else:
  6985. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  6986. float(obj.tools[tool]['tooldia']) * factor,
  6987. tool=str(tool),
  6988. dec=4)
  6989. else:
  6990. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6991. form='ndec', e_zeros='TZ', factor=factor,
  6992. slot_type=slot_type)
  6993. header += '%s,%s\n' % (eunits, 'TZ')
  6994. header += format_exc
  6995. for tool in obj.tools:
  6996. if eunits == 'METRIC':
  6997. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  6998. float(obj.tools[tool]['tooldia']) * factor,
  6999. tool=str(tool),
  7000. dec=2)
  7001. else:
  7002. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7003. float(obj.tools[tool]['tooldia']) * factor,
  7004. tool=str(tool),
  7005. dec=4)
  7006. header += '%\n'
  7007. footer = 'M30\n'
  7008. exported_excellon = header
  7009. exported_excellon += excellon_code
  7010. exported_excellon += footer
  7011. if local_use is None:
  7012. try:
  7013. with open(filename, 'w') as fp:
  7014. fp.write(exported_excellon)
  7015. except PermissionError:
  7016. self.inform.emit('[WARNING] %s' %
  7017. _("Permission denied, saving not possible.\n"
  7018. "Most likely another app is holding the file open and not accessible."))
  7019. return 'fail'
  7020. if self.defaults["global_open_style"] is False:
  7021. self.file_opened.emit("Excellon", filename)
  7022. self.file_saved.emit("Excellon", filename)
  7023. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7024. else:
  7025. return exported_excellon
  7026. except Exception as e:
  7027. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7028. return 'fail'
  7029. if use_thread is True:
  7030. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7031. def job_thread_exc(app_obj):
  7032. ret = make_excellon()
  7033. if ret == 'fail':
  7034. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7035. return
  7036. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7037. else:
  7038. eret = make_excellon()
  7039. if eret == 'fail':
  7040. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7041. return 'fail'
  7042. if local_use is not None:
  7043. return eret
  7044. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7045. """
  7046. Exports a Gerber Object to an Gerber file.
  7047. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7048. :param filename: Path to the Gerber file to save to.
  7049. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7050. When not None, the value will be the actual Gerber object for which to create
  7051. the Gerber code
  7052. :param use_thread: if to be run in a separate thread
  7053. :return:
  7054. """
  7055. self.defaults.report_usage("export_gerber()")
  7056. if filename is None:
  7057. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7058. is not None else self.defaults["global_last_folder"]
  7059. self.log.debug("export_gerber()")
  7060. if local_use is None:
  7061. try:
  7062. obj = self.collection.get_by_name(str(obj_name))
  7063. except Exception:
  7064. return 'fail'
  7065. else:
  7066. obj = local_use
  7067. # updated units
  7068. gunits = self.defaults["gerber_exp_units"]
  7069. gwhole = self.defaults["gerber_exp_integer"]
  7070. gfract = self.defaults["gerber_exp_decimals"]
  7071. gzeros = self.defaults["gerber_exp_zeros"]
  7072. fc_units = self.defaults['units'].upper()
  7073. if fc_units == 'MM':
  7074. factor = 1 if gunits == 'MM' else 0.03937
  7075. else:
  7076. factor = 25.4 if gunits == 'MM' else 1
  7077. def make_gerber():
  7078. try:
  7079. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7080. header = 'G04*\n'
  7081. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7082. (str(self.version), str(self.version_date))
  7083. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7084. header += 'G04 Created on : %s*' % time_str + '\n'
  7085. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7086. header += "%MO{units}*%\n".format(units=gunits)
  7087. for apid in obj.apertures:
  7088. if obj.apertures[apid]['type'] == 'C':
  7089. header += "%ADD{apid}{type},{size}*%\n".format(
  7090. apid=str(apid),
  7091. type='C',
  7092. size=(factor * obj.apertures[apid]['size'])
  7093. )
  7094. elif obj.apertures[apid]['type'] == 'R':
  7095. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7096. apid=str(apid),
  7097. type='R',
  7098. width=(factor * obj.apertures[apid]['width']),
  7099. height=(factor * obj.apertures[apid]['height'])
  7100. )
  7101. elif obj.apertures[apid]['type'] == 'O':
  7102. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7103. apid=str(apid),
  7104. type='O',
  7105. width=(factor * obj.apertures[apid]['width']),
  7106. height=(factor * obj.apertures[apid]['height'])
  7107. )
  7108. header += '\n'
  7109. # obsolete units but some software may need it
  7110. if gunits == 'IN':
  7111. header += 'G70*\n'
  7112. else:
  7113. header += 'G71*\n'
  7114. # Absolute Mode
  7115. header += 'G90*\n'
  7116. header += 'G01*\n'
  7117. # positive polarity
  7118. header += '%LPD*%\n'
  7119. footer = 'M02*\n'
  7120. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7121. exported_gerber = header
  7122. exported_gerber += gerber_code
  7123. exported_gerber += footer
  7124. if local_use is None:
  7125. try:
  7126. with open(filename, 'w') as fp:
  7127. fp.write(exported_gerber)
  7128. except PermissionError:
  7129. self.inform.emit('[WARNING] %s' %
  7130. _("Permission denied, saving not possible.\n"
  7131. "Most likely another app is holding the file open and not accessible."))
  7132. return 'fail'
  7133. if self.defaults["global_open_style"] is False:
  7134. self.file_opened.emit("Gerber", filename)
  7135. self.file_saved.emit("Gerber", filename)
  7136. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7137. else:
  7138. return exported_gerber
  7139. except Exception as e:
  7140. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7141. return 'fail'
  7142. if use_thread is True:
  7143. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7144. def job_thread_grb(app_obj):
  7145. ret = make_gerber()
  7146. if ret == 'fail':
  7147. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export file.'))
  7148. return
  7149. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7150. else:
  7151. gret = make_gerber()
  7152. if gret == 'fail':
  7153. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export file.'))
  7154. return 'fail'
  7155. if local_use is not None:
  7156. return gret
  7157. def export_dxf(self, obj_name, filename, local_use=None, use_thread=True):
  7158. """
  7159. Exports a Geometry Object to an DXF file.
  7160. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7161. :param filename: Path to the DXF file to save to.
  7162. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7163. When not None, the value will be the actual Geometry object for which to create
  7164. the Geometry/DXF code
  7165. :param use_thread: if to be run in a separate thread
  7166. :return:
  7167. """
  7168. self.defaults.report_usage("export_dxf()")
  7169. if filename is None:
  7170. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7171. is not None else self.defaults["global_last_folder"]
  7172. self.log.debug("export_dxf()")
  7173. if local_use is None:
  7174. try:
  7175. obj = self.collection.get_by_name(str(obj_name))
  7176. except Exception:
  7177. return 'fail'
  7178. else:
  7179. obj = local_use
  7180. def make_dxf():
  7181. try:
  7182. dxf_code = obj.export_dxf()
  7183. if local_use is None:
  7184. try:
  7185. dxf_code.saveas(filename)
  7186. except PermissionError:
  7187. self.inform.emit('[WARNING] %s' %
  7188. _("Permission denied, saving not possible.\n"
  7189. "Most likely another app is holding the file open and not accessible."))
  7190. return 'fail'
  7191. if self.defaults["global_open_style"] is False:
  7192. self.file_opened.emit("DXF", filename)
  7193. self.file_saved.emit("DXF", filename)
  7194. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7195. else:
  7196. return dxf_code
  7197. except Exception as e:
  7198. log.debug("App.export_dxf.make_dxf() --> %s" % str(e))
  7199. return 'fail'
  7200. if use_thread is True:
  7201. with self.proc_container.new(_("Exporting DXF")) as proc:
  7202. def job_thread_exc(app_obj):
  7203. ret_dxf_val = make_dxf()
  7204. if ret_dxf_val == 'fail':
  7205. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7206. return
  7207. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7208. else:
  7209. ret = make_dxf()
  7210. if ret == 'fail':
  7211. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7212. return
  7213. if local_use is not None:
  7214. return ret
  7215. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  7216. """
  7217. Adds a new Geometry Object to the projects and populates
  7218. it with shapes extracted from the SVG file.
  7219. :param plot: If True then the resulting object will be plotted on canvas
  7220. :param filename: Path to the SVG file.
  7221. :param geo_type: Type of FlatCAM object that will be created from SVG
  7222. :param outname: The name given to the resulting FlatCAM object
  7223. :return:
  7224. """
  7225. self.defaults.report_usage("import_svg()")
  7226. log.debug("App.import_svg()")
  7227. obj_type = ""
  7228. if geo_type is None or geo_type == "geometry":
  7229. obj_type = "geometry"
  7230. elif geo_type == "gerber":
  7231. obj_type = "gerber"
  7232. else:
  7233. self.inform.emit('[ERROR_NOTCL] %s' %
  7234. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7235. return
  7236. units = self.defaults['units'].upper()
  7237. def obj_init(geo_obj, app_obj):
  7238. if obj_type == "geometry":
  7239. geo_obj.import_svg(filename, obj_type, units=units)
  7240. elif obj_type == "gerber":
  7241. geo_obj.import_svg(filename, obj_type, units=units)
  7242. geo_obj.multigeo = True
  7243. with open(filename) as f:
  7244. file_content = f.read()
  7245. geo_obj.source_file = file_content
  7246. with self.proc_container.new(_("Importing SVG")) as proc:
  7247. # Object name
  7248. name = outname or filename.split('/')[-1].split('\\')[-1]
  7249. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7250. if ret == 'fail':
  7251. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7252. return 'fail'
  7253. # Register recent file
  7254. self.file_opened.emit("svg", filename)
  7255. # appGUI feedback
  7256. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7257. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7258. """
  7259. Adds a new Geometry Object to the projects and populates
  7260. it with shapes extracted from the DXF file.
  7261. :param filename: Path to the DXF file.
  7262. :param geo_type: Type of FlatCAM object that will be created from DXF
  7263. :param outname: Name for the imported Geometry
  7264. :param plot: If True then the resulting object will be plotted on canvas
  7265. :return:
  7266. """
  7267. log.debug(" ********* Importing DXF as: %s ********* " % geo_type.capitalize())
  7268. obj_type = ""
  7269. if geo_type is None or geo_type == "geometry":
  7270. obj_type = "geometry"
  7271. elif geo_type == "gerber":
  7272. obj_type = geo_type
  7273. else:
  7274. self.inform.emit('[ERROR_NOTCL] %s' %
  7275. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7276. return
  7277. units = self.defaults['units'].upper()
  7278. def obj_init(geo_obj, app_obj):
  7279. if obj_type == "geometry":
  7280. geo_obj.import_dxf_as_geo(filename, units=units)
  7281. elif obj_type == "gerber":
  7282. geo_obj.import_dxf_as_gerber(filename, units=units)
  7283. else:
  7284. return "fail"
  7285. geo_obj.multigeo = True
  7286. with open(filename) as f:
  7287. file_content = f.read()
  7288. geo_obj.source_file = file_content
  7289. with self.proc_container.new(_("Importing DXF")):
  7290. # Object name
  7291. name = outname or filename.split('/')[-1].split('\\')[-1]
  7292. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7293. if ret == 'fail':
  7294. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7295. return 'fail'
  7296. # Register recent file
  7297. self.file_opened.emit("dxf", filename)
  7298. # appGUI feedback
  7299. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7300. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7301. """
  7302. Opens a Gerber file, parses it and creates a new object for
  7303. it in the program. Thread-safe.
  7304. :param outname: Name of the resulting object. None causes the
  7305. name to be that of the file. Str.
  7306. :param filename: Gerber file filename
  7307. :type filename: str
  7308. :param plot: boolean, to plot or not the resulting object
  7309. :param from_tcl: True if run from Tcl Shell
  7310. :return: None
  7311. """
  7312. # How the object should be initialized
  7313. def obj_init(gerber_obj, app_obj):
  7314. assert isinstance(gerber_obj, GerberObject), \
  7315. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7316. # Opening the file happens here
  7317. try:
  7318. gerber_obj.parse_file(filename)
  7319. except IOError:
  7320. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7321. return "fail"
  7322. except ParseError as err:
  7323. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7324. app_obj.log.error(str(err))
  7325. return "fail"
  7326. except Exception as e:
  7327. log.debug("App.open_gerber() --> %s" % str(e))
  7328. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7329. msg += traceback.format_exc()
  7330. app_obj.inform.emit(msg)
  7331. return "fail"
  7332. if gerber_obj.is_empty():
  7333. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7334. _("Object is not Gerber file or empty. Aborting object creation."))
  7335. return "fail"
  7336. App.log.debug("open_gerber()")
  7337. with self.proc_container.new(_("Opening Gerber")):
  7338. # Object name
  7339. name = outname or filename.split('/')[-1].split('\\')[-1]
  7340. # # ## Object creation # ##
  7341. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7342. if ret_val == 'fail':
  7343. if from_tcl:
  7344. filename = self.defaults['global_tcl_path'] + '/' + name
  7345. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7346. if ret_val == 'fail':
  7347. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7348. return 'fail'
  7349. # Register recent file
  7350. self.file_opened.emit("gerber", filename)
  7351. # appGUI feedback
  7352. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7353. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7354. """
  7355. Opens an Excellon file, parses it and creates a new object for
  7356. it in the program. Thread-safe.
  7357. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7358. :param filename: Excellon file filename
  7359. :type filename: str
  7360. :param plot: boolean, to plot or not the resulting object
  7361. :param from_tcl: True if run from Tcl Shell
  7362. :return: None
  7363. """
  7364. App.log.debug("open_excellon()")
  7365. # How the object should be initialized
  7366. def obj_init(excellon_obj, app_obj):
  7367. try:
  7368. ret = excellon_obj.parse_file(filename=filename)
  7369. if ret == "fail":
  7370. log.debug("Excellon parsing failed.")
  7371. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not Excellon file."))
  7372. return "fail"
  7373. except IOError:
  7374. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Cannot open file"), filename))
  7375. log.debug("Could not open Excellon object.")
  7376. return "fail"
  7377. except Exception:
  7378. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  7379. msg += traceback.format_exc()
  7380. app_obj.inform.emit(msg)
  7381. return "fail"
  7382. ret = excellon_obj.create_geometry()
  7383. if ret == 'fail':
  7384. log.debug("Could not create geometry for Excellon object.")
  7385. return "fail"
  7386. for tool in excellon_obj.tools:
  7387. if excellon_obj.tools[tool]['solid_geometry']:
  7388. return
  7389. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7390. return "fail"
  7391. with self.proc_container.new(_("Opening Excellon.")):
  7392. # Object name
  7393. name = outname or filename.split('/')[-1].split('\\')[-1]
  7394. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7395. if ret_val == 'fail':
  7396. if from_tcl:
  7397. filename = self.defaults['global_tcl_path'] + '/' + name
  7398. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7399. if ret_val == 'fail':
  7400. self.inform.emit('[ERROR_NOTCL] %s' %
  7401. _('Open Excellon file failed. Probable not an Excellon file.'))
  7402. return
  7403. # Register recent file
  7404. self.file_opened.emit("excellon", filename)
  7405. # appGUI feedback
  7406. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7407. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7408. """
  7409. Opens a G-gcode file, parses it and creates a new object for
  7410. it in the program. Thread-safe.
  7411. :param filename: G-code file filename
  7412. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7413. :param force_parsing:
  7414. :param plot: If True plot the object on canvas
  7415. :param from_tcl: True if run from Tcl Shell
  7416. :return: None
  7417. """
  7418. App.log.debug("open_gcode()")
  7419. # How the object should be initialized
  7420. def obj_init(job_obj, app_obj_):
  7421. """
  7422. :param job_obj: the resulting object
  7423. :type app_obj_: App
  7424. """
  7425. assert isinstance(app_obj_, App), \
  7426. "Initializer expected App, got %s" % type(app_obj_)
  7427. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7428. try:
  7429. f = open(filename)
  7430. gcode = f.read()
  7431. f.close()
  7432. except IOError:
  7433. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7434. return "fail"
  7435. job_obj.gcode = gcode
  7436. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7437. if gcode_ret == "fail":
  7438. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7439. return "fail"
  7440. job_obj.create_geometry()
  7441. with self.proc_container.new(_("Opening G-Code.")):
  7442. # Object name
  7443. name = outname or filename.split('/')[-1].split('\\')[-1]
  7444. # New object creation and file processing
  7445. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7446. if ret_val == 'fail':
  7447. if from_tcl:
  7448. filename = self.defaults['global_tcl_path'] + '/' + name
  7449. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7450. if ret_val == 'fail':
  7451. self.inform.emit('[ERROR_NOTCL] %s' %
  7452. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7453. "Try to load it from File menu.\n "
  7454. "Attempting to create a FlatCAM CNCJob Object from "
  7455. "G-Code file failed during processing"))
  7456. return "fail"
  7457. # Register recent file
  7458. self.file_opened.emit("cncjob", filename)
  7459. # appGUI feedback
  7460. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7461. def open_hpgl2(self, filename, outname=None):
  7462. """
  7463. Opens a HPGL2 file, parses it and creates a new object for
  7464. it in the program. Thread-safe.
  7465. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7466. :param filename: HPGL2 file filename
  7467. :return: None
  7468. """
  7469. filename = filename
  7470. # How the object should be initialized
  7471. def obj_init(geo_obj, app_obj):
  7472. assert isinstance(geo_obj, GeometryObject), \
  7473. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7474. # Opening the file happens here
  7475. obj = HPGL2(self)
  7476. try:
  7477. HPGL2.parse_file(obj, filename)
  7478. except IOError:
  7479. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7480. return "fail"
  7481. except ParseError as err:
  7482. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7483. app_obj.log.error(str(err))
  7484. return "fail"
  7485. except Exception as e:
  7486. log.debug("App.open_hpgl2() --> %s" % str(e))
  7487. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7488. msg += traceback.format_exc()
  7489. app_obj.inform.emit(msg)
  7490. return "fail"
  7491. geo_obj.multigeo = True
  7492. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7493. geo_obj.tools = deepcopy(obj.tools)
  7494. geo_obj.source_file = deepcopy(obj.source_file)
  7495. del obj
  7496. if not geo_obj.solid_geometry:
  7497. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7498. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7499. return "fail"
  7500. App.log.debug("open_hpgl2()")
  7501. with self.proc_container.new(_("Opening HPGL2")):
  7502. # Object name
  7503. name = outname or filename.split('/')[-1].split('\\')[-1]
  7504. # # ## Object creation # ##
  7505. ret = self.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  7506. if ret == 'fail':
  7507. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7508. return 'fail'
  7509. # Register recent file
  7510. self.file_opened.emit("geometry", filename)
  7511. # appGUI feedback
  7512. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7513. def open_script(self, filename, outname=None, silent=False):
  7514. """
  7515. Opens a Script file, parses it and creates a new object for
  7516. it in the program. Thread-safe.
  7517. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7518. :param filename: Script file filename
  7519. :param silent: If True there will be no messages printed to StatusBar
  7520. :return: None
  7521. """
  7522. def obj_init(script_obj, app_obj):
  7523. assert isinstance(script_obj, ScriptObject), \
  7524. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7525. if silent is False:
  7526. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7527. try:
  7528. script_obj.parse_file(filename)
  7529. except IOError:
  7530. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7531. return "fail"
  7532. except ParseError as err:
  7533. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7534. app_obj.log.error(str(err))
  7535. return "fail"
  7536. except Exception as e:
  7537. log.debug("App.open_script() -> %s" % str(e))
  7538. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7539. msg += traceback.format_exc()
  7540. app_obj.inform.emit(msg)
  7541. return "fail"
  7542. App.log.debug("open_script()")
  7543. with self.proc_container.new(_("Opening TCL Script...")):
  7544. # Object name
  7545. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7546. # Object creation
  7547. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7548. if ret_val == 'fail':
  7549. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7550. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7551. if ret_val == 'fail':
  7552. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7553. return 'fail'
  7554. # Register recent file
  7555. self.file_opened.emit("script", filename)
  7556. # appGUI feedback
  7557. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7558. def open_config_file(self, filename, run_from_arg=None):
  7559. """
  7560. Loads a config file from the specified file.
  7561. :param filename: Name of the file from which to load.
  7562. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7563. :return: None
  7564. """
  7565. App.log.debug("Opening config file: " + filename)
  7566. if run_from_arg:
  7567. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7568. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7569. _("Opening FlatCAM Config file.")),
  7570. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7571. color=QtGui.QColor("gray"))
  7572. # # add the tab if it was closed
  7573. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7574. # # first clear previous text in text editor (if any)
  7575. # self.ui.text_editor_tab.code_editor.clear()
  7576. #
  7577. # # Switch plot_area to CNCJob tab
  7578. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7579. # close the Code editor if already open
  7580. if self.toggle_codeeditor:
  7581. self.on_toggle_code_editor()
  7582. self.on_toggle_code_editor()
  7583. try:
  7584. if filename:
  7585. f = QtCore.QFile(filename)
  7586. if f.open(QtCore.QIODevice.ReadOnly):
  7587. stream = QtCore.QTextStream(f)
  7588. code_edited = stream.readAll()
  7589. self.text_editor_tab.load_text(code_edited, clear_text=True, move_to_start=True)
  7590. f.close()
  7591. except IOError:
  7592. App.log.error("Failed to open config file: %s" % filename)
  7593. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7594. (_("Failed to open config file"), filename))
  7595. return
  7596. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7597. """
  7598. Loads a project from the specified file.
  7599. 1) Loads and parses file
  7600. 2) Registers the file as recently opened.
  7601. 3) Calls on_file_new()
  7602. 4) Updates options
  7603. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  7604. 6) Calls plot_all() if plot=True
  7605. :param filename: Name of the file from which to load.
  7606. :param run_from_arg: True if run for arguments
  7607. :param plot: If True plot all objects in the project
  7608. :param cli: Run from command line
  7609. :param from_tcl: True if run from Tcl Sehll
  7610. :return: None
  7611. """
  7612. App.log.debug("Opening project: " + filename)
  7613. # block autosaving while a project is loaded
  7614. self.block_autosave = True
  7615. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7616. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7617. if cli is None:
  7618. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7619. if run_from_arg:
  7620. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7621. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7622. _("Opening FlatCAM Project file.")),
  7623. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7624. color=QtGui.QColor("gray"))
  7625. # Open and parse an uncompressed Project file
  7626. try:
  7627. f = open(filename, 'r')
  7628. except IOError:
  7629. if from_tcl:
  7630. name = filename.split('/')[-1].split('\\')[-1]
  7631. filename = self.defaults['global_tcl_path'] + '/' + name
  7632. try:
  7633. f = open(filename, 'r')
  7634. except IOError:
  7635. log.error("Failed to open project file: %s" % filename)
  7636. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7637. return
  7638. else:
  7639. log.error("Failed to open project file: %s" % filename)
  7640. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7641. return
  7642. try:
  7643. d = json.load(f, object_hook=dict2obj)
  7644. except Exception as e:
  7645. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7646. (filename, str(e)))
  7647. f.close()
  7648. # Open and parse a compressed Project file
  7649. try:
  7650. with lzma.open(filename) as f:
  7651. file_content = f.read().decode('utf-8')
  7652. d = json.loads(file_content, object_hook=dict2obj)
  7653. except Exception as e:
  7654. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7655. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7656. return
  7657. # Clear the current project
  7658. # # NOT THREAD SAFE # ##
  7659. if run_from_arg is True:
  7660. pass
  7661. elif cli is True:
  7662. self.delete_selection_shape()
  7663. else:
  7664. self.on_file_new()
  7665. # Project options
  7666. self.options.update(d['options'])
  7667. self.project_filename = filename
  7668. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7669. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7670. if cli is None:
  7671. self.set_screen_units(self.options["units"])
  7672. # Re create objects
  7673. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7674. for obj in d['objs']:
  7675. def obj_init(obj_inst, app_inst):
  7676. try:
  7677. obj_inst.from_dict(obj)
  7678. except Exception as e:
  7679. print('App.open_project() --> ' + str(e))
  7680. return 'fail'
  7681. App.log.debug("Recreating from opened project an %s object: %s" %
  7682. (obj['kind'].capitalize(), obj['options']['name']))
  7683. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7684. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7685. if cli is None:
  7686. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7687. obj['kind'].upper(),
  7688. obj['options']['name']
  7689. )
  7690. )
  7691. self.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  7692. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  7693. self.should_we_save = False
  7694. self.file_opened.emit("project", filename)
  7695. # restore autosaving after a project was loaded
  7696. self.block_autosave = False
  7697. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7698. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7699. if cli is None:
  7700. self.set_ui_title(name=self.project_filename)
  7701. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7702. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  7703. """
  7704. Re-generates all plots from all objects.
  7705. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  7706. :param muted: if True don't print messages
  7707. :param use_thread: if True will use threading for plotting the objects
  7708. :return: None
  7709. """
  7710. self.log.debug("Plot_all()")
  7711. if muted is not True:
  7712. self.inform[str, bool].emit('%s...' % _("Redrawing all objects"), False)
  7713. for plot_obj in self.collection.get_list():
  7714. def worker_task(obj):
  7715. with self.proc_container.new("Plotting"):
  7716. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7717. if fit_view is True:
  7718. self.app_obj.object_plotted.emit(obj)
  7719. if use_thread is True:
  7720. # Send to worker
  7721. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  7722. else:
  7723. worker_task(plot_obj)
  7724. def register_folder(self, filename):
  7725. """
  7726. Register the last folder used by the app to open something
  7727. :param filename: the last folder is extracted from the filename
  7728. :return: None
  7729. """
  7730. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7731. def register_save_folder(self, filename):
  7732. """
  7733. Register the last folder used by the app to save something
  7734. :param filename: the last folder is extracted from the filename
  7735. :return: None
  7736. """
  7737. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7738. # def set_progress_bar(self, percentage, text=""):
  7739. # """
  7740. # Set a progress bar to a value (percentage)
  7741. #
  7742. # :param percentage: Value set to the progressbar
  7743. # :param text: Not used
  7744. # :return: None
  7745. # """
  7746. # self.ui.progress_bar.setValue(int(percentage))
  7747. def setup_recent_items(self):
  7748. """
  7749. Setup a dictionary with the recent files accessed, organized by type
  7750. :return:
  7751. """
  7752. icons = {
  7753. "gerber": self.resource_location + "/flatcam_icon16.png",
  7754. "excellon": self.resource_location + "/drill16.png",
  7755. 'geometry': self.resource_location + "/geometry16.png",
  7756. "cncjob": self.resource_location + "/cnc16.png",
  7757. "script": self.resource_location + "/script_new24.png",
  7758. "document": self.resource_location + "/notes16_1.png",
  7759. "project": self.resource_location + "/project16.png",
  7760. "svg": self.resource_location + "/geometry16.png",
  7761. "dxf": self.resource_location + "/dxf16.png",
  7762. "pdf": self.resource_location + "/pdf32.png",
  7763. "image": self.resource_location + "/image16.png"
  7764. }
  7765. try:
  7766. image_opener = self.image_tool.import_image
  7767. except AttributeError:
  7768. image_opener = None
  7769. openers = {
  7770. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7771. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7772. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7773. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7774. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  7775. "document": None,
  7776. 'project': self.open_project,
  7777. 'svg': self.import_svg,
  7778. 'dxf': self.import_dxf,
  7779. 'image': image_opener,
  7780. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7781. }
  7782. # Open recent file for files
  7783. try:
  7784. f = open(self.data_path + '/recent.json')
  7785. except IOError:
  7786. App.log.error("Failed to load recent item list.")
  7787. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  7788. return
  7789. try:
  7790. self.recent = json.load(f)
  7791. except json.errors.JSONDecodeError:
  7792. App.log.error("Failed to parse recent item list.")
  7793. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  7794. f.close()
  7795. return
  7796. f.close()
  7797. # Open recent file for projects
  7798. try:
  7799. fp = open(self.data_path + '/recent_projects.json')
  7800. except IOError:
  7801. App.log.error("Failed to load recent project item list.")
  7802. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  7803. return
  7804. try:
  7805. self.recent_projects = json.load(fp)
  7806. except json.errors.JSONDecodeError:
  7807. App.log.error("Failed to parse recent project item list.")
  7808. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  7809. fp.close()
  7810. return
  7811. fp.close()
  7812. # Closure needed to create callbacks in a loop.
  7813. # Otherwise late binding occurs.
  7814. def make_callback(func, fname):
  7815. def opener():
  7816. func(fname)
  7817. return opener
  7818. def reset_recent_files():
  7819. # Reset menu
  7820. self.ui.recent.clear()
  7821. self.recent = []
  7822. try:
  7823. ff = open(self.data_path + '/recent.json', 'w')
  7824. except IOError:
  7825. App.log.error("Failed to open recent items file for writing.")
  7826. return
  7827. json.dump(self.recent, ff)
  7828. def reset_recent_projects():
  7829. # Reset menu
  7830. self.ui.recent_projects.clear()
  7831. self.recent_projects = []
  7832. try:
  7833. frp = open(self.data_path + '/recent_projects.json', 'w')
  7834. except IOError:
  7835. App.log.error("Failed to open recent projects items file for writing.")
  7836. return
  7837. json.dump(self.recent, frp)
  7838. # Reset menu
  7839. self.ui.recent.clear()
  7840. self.ui.recent_projects.clear()
  7841. # Create menu items for projects
  7842. for recent in self.recent_projects:
  7843. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7844. if recent['kind'] == 'project':
  7845. try:
  7846. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7847. # Attach callback
  7848. o = make_callback(openers[recent["kind"]], recent['filename'])
  7849. action.triggered.connect(o)
  7850. self.ui.recent_projects.addAction(action)
  7851. except KeyError:
  7852. App.log.error("Unsupported file type: %s" % recent["kind"])
  7853. # Last action in Recent Files menu is one that Clear the content
  7854. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7855. (_("Clear Recent projects")), self)
  7856. clear_action_proj.triggered.connect(reset_recent_projects)
  7857. self.ui.recent_projects.addSeparator()
  7858. self.ui.recent_projects.addAction(clear_action_proj)
  7859. # Create menu items for files
  7860. for recent in self.recent:
  7861. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7862. if recent['kind'] != 'project':
  7863. try:
  7864. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7865. # Attach callback
  7866. o = make_callback(openers[recent["kind"]], recent['filename'])
  7867. action.triggered.connect(o)
  7868. self.ui.recent.addAction(action)
  7869. except KeyError:
  7870. App.log.error("Unsupported file type: %s" % recent["kind"])
  7871. # Last action in Recent Files menu is one that Clear the content
  7872. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7873. (_("Clear Recent files")), self)
  7874. clear_action.triggered.connect(reset_recent_files)
  7875. self.ui.recent.addSeparator()
  7876. self.ui.recent.addAction(clear_action)
  7877. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7878. # self.ui.menufilerecent.set_submenu(recent_menu)
  7879. # recent_menu.show_all()
  7880. # self.ui.recent.show()
  7881. self.log.debug("Recent items list has been populated.")
  7882. def setup_component_editor(self):
  7883. """
  7884. Default text for the Selected tab when is not taken by the Object UI.
  7885. :return:
  7886. """
  7887. # label = QtWidgets.QLabel("Choose an item from Project")
  7888. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7889. sel_title = QtWidgets.QTextEdit(
  7890. _('<b>Shortcut Key List</b>'))
  7891. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7892. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7893. f_settings = QSettings("Open Source", "FlatCAM")
  7894. if f_settings.contains("notebook_font_size"):
  7895. fsize = f_settings.value('notebook_font_size', type=int)
  7896. else:
  7897. fsize = 12
  7898. tsize = fsize + int(fsize / 2)
  7899. # selected_text = (_('''
  7900. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  7901. # </p>
  7902. #
  7903. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  7904. # The normal flow when working in FlatCAM is the following:</span></p>
  7905. #
  7906. # <ol>
  7907. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  7908. # file into
  7909. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  7910. # even dragging and dropping the files on the appGUI.<br />
  7911. # <br />
  7912. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  7913. # drop of the
  7914. # file into the FLATCAM appGUI or through the menu/toolbar links offered within the app.</span><br />
  7915. # &nbsp;</li>
  7916. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  7917. # and then
  7918. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  7919. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  7920. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  7921. # <br />
  7922. # If the selection of the object is done on the canvas by single click instead, and the
  7923. # <strong>SELECTED TAB</strong>
  7924. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  7925. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  7926. # it even if it was out of focus.<br />
  7927. # <br />
  7928. # You can change the parameters in this screen and the flow direction is like this:<br />
  7929. # <br />
  7930. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  7931. # <strong> Geometry Object
  7932. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  7933. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  7934. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  7935. # </ol>
  7936. #
  7937. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  7938. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  7939. # <strong>F3</strong>.</span></p>
  7940. #
  7941. # ''').format(fsize=fsize, tsize=tsize))
  7942. selected_text = '''
  7943. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  7944. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  7945. {s1}</span></p>
  7946. <ol>
  7947. <li><span style="font-size:{fsize}px">{s2}<br />
  7948. <br />
  7949. {s3}</span><br />
  7950. &nbsp;</li>
  7951. <li><span style="font-size:{fsize}px">{s4}<br />
  7952. &nbsp;</li>
  7953. <br />
  7954. <li><span style="font-size:{fsize}px">{s5}<br />
  7955. &nbsp;</li>
  7956. <br />
  7957. <li><span style="font-size:{fsize}px">{s6}<br />
  7958. <br />
  7959. {s7}</span></li>
  7960. </ol>
  7961. <p><span style="font-size:{fsize}px">{s8}</span></p>
  7962. '''.format(
  7963. title=_("Selected Tab - Choose an Item from Project Tab"),
  7964. subtitle=_("Details"),
  7965. s1=_("The normal flow when working with the application is the following:"),
  7966. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into the application "
  7967. "using either the toolbars, key shortcuts or even dragging and dropping the "
  7968. "files on the GUI."),
  7969. s3=_("You can also load a project by double clicking on the project file, "
  7970. "drag and drop of the file into the GUI or through the menu (or toolbar) "
  7971. "actions offered within the app."),
  7972. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  7973. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  7974. "SELECTED TAB will be updated with the object properties according to its kind: "
  7975. "Gerber, Excellon, Geometry or CNCJob object."),
  7976. s5=_("If the selection of the object is done on the canvas by single click instead, "
  7977. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  7978. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  7979. "the SELECTED TAB and populate it even if it was out of focus."),
  7980. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  7981. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  7982. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  7983. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  7984. "(again, done in SELECTED TAB) --> Save GCode."),
  7985. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  7986. "or through its own key shortcut: <b>F3</b>."),
  7987. tsize=tsize,
  7988. fsize=fsize
  7989. )
  7990. sel_title.setText(selected_text)
  7991. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  7992. self.ui.selected_scroll_area.setWidget(sel_title)
  7993. def setup_obj_classes(self):
  7994. """
  7995. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  7996. class.
  7997. :return: None
  7998. """
  7999. FlatCAMObj.app = self
  8000. ObjectCollection.app = self
  8001. Gerber.app = self
  8002. Excellon.app = self
  8003. Geometry.app = self
  8004. CNCjob.app = self
  8005. FCProcess.app = self
  8006. FCProcessContainer.app = self
  8007. OptionsGroupUI.app = self
  8008. def version_check(self):
  8009. """
  8010. Checks for the latest version of the program. Alerts the
  8011. user if theirs is outdated. This method is meant to be run
  8012. in a separate thread.
  8013. :return: None
  8014. """
  8015. self.log.debug("version_check()")
  8016. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8017. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  8018. App.version_url,
  8019. str(self.defaults['global_serial']),
  8020. str(self.version),
  8021. str(self.os),
  8022. urllib.parse.urlencode(self.defaults["global_stats"])
  8023. )
  8024. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  8025. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  8026. # urllib.parse.urlencode(self.defaults["global_stats"])
  8027. else:
  8028. # no_stats dict; just so it won't break things on website
  8029. no_ststs_dict = {}
  8030. no_ststs_dict["global_ststs"] = {}
  8031. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  8032. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8033. App.log.debug("Checking for updates @ %s" % full_url)
  8034. # ## Get the data
  8035. try:
  8036. f = urllib.request.urlopen(full_url)
  8037. except Exception:
  8038. # App.log.warning("Failed checking for latest version. Could not connect.")
  8039. self.log.warning("Failed checking for latest version. Could not connect.")
  8040. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  8041. return
  8042. try:
  8043. data = json.load(f)
  8044. except Exception as e:
  8045. App.log.error("Could not parse information about latest version.")
  8046. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  8047. App.log.debug("json.load(): %s" % str(e))
  8048. f.close()
  8049. return
  8050. f.close()
  8051. # ## Latest version?
  8052. if self.version >= data["version"]:
  8053. App.log.debug("FlatCAM is up to date!")
  8054. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  8055. return
  8056. App.log.debug("Newer version available.")
  8057. self.message.emit(
  8058. _("Newer Version Available"),
  8059. '%s<br><br>><b>%s</b><br>%s' % (
  8060. _("There is a newer version of FlatCAM available for download:"),
  8061. str(data["name"]),
  8062. str(data["message"])
  8063. ),
  8064. _("info")
  8065. )
  8066. def on_plotcanvas_setup(self, container=None):
  8067. """
  8068. This is doing the setup for the plot area (canvas).
  8069. :param container: QT Widget where to install the canvas
  8070. :return: None
  8071. """
  8072. if container:
  8073. plot_container = container
  8074. else:
  8075. plot_container = self.ui.right_layout
  8076. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  8077. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  8078. self.is_legacy = True
  8079. self.defaults["global_graphic_engine"] = "2D"
  8080. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  8081. else:
  8082. try:
  8083. self.plotcanvas = PlotCanvas(plot_container, self)
  8084. except Exception as er:
  8085. msg_txt = traceback.format_exc()
  8086. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  8087. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  8088. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8089. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  8090. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  8091. msg += msg_txt
  8092. self.inform.emit(msg)
  8093. return 'fail'
  8094. # So it can receive key presses
  8095. self.plotcanvas.native.setFocus()
  8096. if self.is_legacy is False:
  8097. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  8098. # Set the mouse button for panning
  8099. self.plotcanvas.view.camera.pan_button_setting = pan_button
  8100. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  8101. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  8102. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8103. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  8104. # Keys over plot enabled
  8105. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  8106. if self.defaults['global_cursor_type'] == 'small':
  8107. self.app_cursor = self.plotcanvas.new_cursor()
  8108. else:
  8109. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  8110. if self.ui.grid_snap_btn.isChecked():
  8111. self.app_cursor.enabled = True
  8112. else:
  8113. self.app_cursor.enabled = False
  8114. if self.is_legacy is False:
  8115. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8116. else:
  8117. # will use the default Matplotlib axes
  8118. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  8119. def on_zoom_fit(self):
  8120. """
  8121. Callback for zoom-fit request. This can be either from the corresponding
  8122. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8123. with axes limits from the geometry bounds of all objects.
  8124. :return: None
  8125. """
  8126. if self.is_legacy is False:
  8127. self.plotcanvas.fit_view()
  8128. else:
  8129. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  8130. width = xmax - xmin
  8131. height = ymax - ymin
  8132. xmin -= 0.05 * width
  8133. xmax += 0.05 * width
  8134. ymin -= 0.05 * height
  8135. ymax += 0.05 * height
  8136. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  8137. def on_zoom_in(self):
  8138. """
  8139. Callback for zoom-in request.
  8140. :return:
  8141. """
  8142. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8143. def on_zoom_out(self):
  8144. """
  8145. Callback for zoom-out request.
  8146. :return:
  8147. """
  8148. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8149. def disable_all_plots(self):
  8150. self.defaults.report_usage("disable_all_plots()")
  8151. self.disable_plots(self.collection.get_list())
  8152. self.inform.emit('[success] %s' %
  8153. _("All plots disabled."))
  8154. def disable_other_plots(self):
  8155. self.defaults.report_usage("disable_other_plots()")
  8156. self.disable_plots(self.collection.get_non_selected())
  8157. self.inform.emit('[success] %s' %
  8158. _("All non selected plots disabled."))
  8159. def enable_all_plots(self):
  8160. self.defaults.report_usage("enable_all_plots()")
  8161. self.enable_plots(self.collection.get_list())
  8162. self.inform.emit('[success] %s' %
  8163. _("All plots enabled."))
  8164. def on_enable_sel_plots(self):
  8165. log.debug("App.on_enable_sel_plot()")
  8166. object_list = self.collection.get_selected()
  8167. self.enable_plots(objects=object_list)
  8168. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  8169. def on_disable_sel_plots(self):
  8170. log.debug("App.on_disable_sel_plot()")
  8171. # self.inform.emit(_("Disabling plots ..."))
  8172. object_list = self.collection.get_selected()
  8173. self.disable_plots(objects=object_list)
  8174. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  8175. def enable_plots(self, objects):
  8176. """
  8177. Enable plots
  8178. :param objects: list of Objects to be enabled
  8179. :return:
  8180. """
  8181. log.debug("Enabling plots ...")
  8182. # self.inform.emit(_("Working ..."))
  8183. for obj in objects:
  8184. if obj.options['plot'] is False:
  8185. obj.options.set_change_callback(lambda x: None)
  8186. obj.options['plot'] = True
  8187. try:
  8188. # only the Gerber obj has on_plot_cb_click() method
  8189. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8190. # disable this cb while disconnected,
  8191. # in case the operation takes time the user is not allowed to change it
  8192. obj.ui.plot_cb.setDisabled(True)
  8193. except AttributeError:
  8194. pass
  8195. obj.set_form_item("plot")
  8196. try:
  8197. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8198. obj.ui.plot_cb.setDisabled(False)
  8199. except AttributeError:
  8200. pass
  8201. obj.options.set_change_callback(obj.on_options_change)
  8202. def worker_task(objs):
  8203. with self.proc_container.new(_("Enabling plots ...")):
  8204. for plot_obj in objs:
  8205. # obj.options['plot'] = True
  8206. if isinstance(plot_obj, CNCJobObject):
  8207. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8208. else:
  8209. plot_obj.plot(visible=True)
  8210. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8211. def disable_plots(self, objects):
  8212. """
  8213. Disables plots
  8214. :param objects: list of Objects to be disabled
  8215. :return:
  8216. """
  8217. # if no objects selected then do nothing
  8218. if not self.collection.get_selected():
  8219. return
  8220. log.debug("Disabling plots ...")
  8221. # self.inform.emit(_("Working ..."))
  8222. for obj in objects:
  8223. if obj.options['plot'] is True:
  8224. obj.options.set_change_callback(lambda x: None)
  8225. obj.options['plot'] = False
  8226. try:
  8227. # only the Gerber obj has on_plot_cb_click() method
  8228. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8229. obj.ui.plot_cb.setDisabled(True)
  8230. except AttributeError:
  8231. pass
  8232. obj.set_form_item("plot")
  8233. try:
  8234. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8235. obj.ui.plot_cb.setDisabled(False)
  8236. except AttributeError:
  8237. pass
  8238. obj.options.set_change_callback(obj.on_options_change)
  8239. try:
  8240. self.delete_selection_shape()
  8241. except Exception as e:
  8242. log.debug("App.disable_plots() --> %s" % str(e))
  8243. def worker_task(objs):
  8244. with self.proc_container.new(_("Disabling plots ...")):
  8245. for plot_obj in objs:
  8246. # obj.options['plot'] = True
  8247. if isinstance(plot_obj, CNCJobObject):
  8248. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8249. else:
  8250. plot_obj.plot(visible=False)
  8251. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8252. def toggle_plots(self, objects):
  8253. """
  8254. Toggle plots visibility
  8255. :param objects: list of Objects for which to be toggled the visibility
  8256. :return: None
  8257. """
  8258. # if no objects selected then do nothing
  8259. if not self.collection.get_selected():
  8260. return
  8261. log.debug("Toggling plots ...")
  8262. self.inform.emit(_("Working ..."))
  8263. for obj in objects:
  8264. if obj.options['plot'] is False:
  8265. obj.options['plot'] = True
  8266. else:
  8267. obj.options['plot'] = False
  8268. self.app_obj.plots_updated.emit()
  8269. def clear_plots(self):
  8270. """
  8271. Clear the plots
  8272. :return: None
  8273. """
  8274. objects = self.collection.get_list()
  8275. for obj in objects:
  8276. obj.clear(obj == objects[-1])
  8277. # Clear pool to free memory
  8278. self.clear_pool()
  8279. def on_set_color_action_triggered(self):
  8280. """
  8281. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8282. :return:
  8283. """
  8284. new_color = self.defaults['gerber_plot_fill']
  8285. clicked_action = self.sender()
  8286. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8287. act_name = clicked_action.text()
  8288. sel_obj_list = self.collection.get_selected()
  8289. if not sel_obj_list:
  8290. return
  8291. # a default value, I just chose this one
  8292. alpha_level = 'BF'
  8293. for sel_obj in sel_obj_list:
  8294. if sel_obj.kind == 'excellon':
  8295. alpha_level = str(hex(
  8296. self.ui.excellon_defaults_form.excellon_gen_group.excellon_alpha_entry.get_value())[2:])
  8297. elif sel_obj.kind == 'gerber':
  8298. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.gerber_alpha_entry.get_value())[2:])
  8299. elif sel_obj.kind == 'geometry':
  8300. alpha_level = 'FF'
  8301. else:
  8302. log.debug(
  8303. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8304. continue
  8305. sel_obj.alpha_level = alpha_level
  8306. if act_name == _('Red'):
  8307. new_color = '#FF0000' + alpha_level
  8308. if act_name == _('Blue'):
  8309. new_color = '#0000FF' + alpha_level
  8310. if act_name == _('Yellow'):
  8311. new_color = '#FFDF00' + alpha_level
  8312. if act_name == _('Green'):
  8313. new_color = '#00FF00' + alpha_level
  8314. if act_name == _('Purple'):
  8315. new_color = '#FF00FF' + alpha_level
  8316. if act_name == _('Brown'):
  8317. new_color = '#A52A2A' + alpha_level
  8318. if act_name == _('White'):
  8319. new_color = '#FFFFFF' + alpha_level
  8320. if act_name == _('Black'):
  8321. new_color = '#000000' + alpha_level
  8322. if act_name == _('Custom'):
  8323. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8324. c_dialog = QtWidgets.QColorDialog()
  8325. plot_fill_color = c_dialog.getColor(initial=new_color)
  8326. if plot_fill_color.isValid() is False:
  8327. return
  8328. new_color = str(plot_fill_color.name()) + alpha_level
  8329. if act_name == _("Default"):
  8330. for sel_obj in sel_obj_list:
  8331. if sel_obj.kind == 'excellon':
  8332. new_color = self.defaults['excellon_plot_fill']
  8333. new_line_color = self.defaults['excellon_plot_line']
  8334. elif sel_obj.kind == 'gerber':
  8335. new_color = self.defaults['gerber_plot_fill']
  8336. new_line_color = self.defaults['gerber_plot_line']
  8337. elif sel_obj.kind == 'geometry':
  8338. new_color = self.defaults['geometry_plot_line']
  8339. new_line_color = self.defaults['geometry_plot_line']
  8340. else:
  8341. log.debug(
  8342. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8343. continue
  8344. sel_obj.fill_color = new_color
  8345. sel_obj.outline_color = new_line_color
  8346. sel_obj.shapes.redraw(
  8347. update_colors=(new_color, new_line_color)
  8348. )
  8349. return
  8350. if act_name == _("Opacity"):
  8351. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8352. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8353. if ok_button:
  8354. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8355. for sel_obj in sel_obj_list:
  8356. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8357. sel_obj.shapes.redraw(
  8358. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8359. )
  8360. return
  8361. new_line_color = color_variant(new_color[:7], 0.7)
  8362. if act_name == _("White"):
  8363. new_line_color = color_variant("#dedede", 0.7)
  8364. for sel_obj in sel_obj_list:
  8365. sel_obj.fill_color = new_color
  8366. sel_obj.outline_color = new_line_color
  8367. sel_obj.shapes.redraw(
  8368. update_colors=(new_color, new_line_color)
  8369. )
  8370. # make sure to set the color in the Gerber colors storage self.defaults["gerber_color_list"]
  8371. group = self.collection.group_items["gerber"]
  8372. group_index = self.collection.index(group.row(), 0, QtCore.QModelIndex())
  8373. new_c = (new_line_color, new_color)
  8374. for sel_obj in sel_obj_list:
  8375. if sel_obj.kind == 'gerber':
  8376. item = sel_obj.item
  8377. item_index = self.collection.index(item.row(), 0, group_index)
  8378. idx = item_index.row()
  8379. self.defaults["gerber_color_list"][idx] = new_c
  8380. def generate_cnc_job(self, objects):
  8381. """
  8382. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8383. :param objects: Selected objects in the Project Tab
  8384. :return:
  8385. """
  8386. self.defaults.report_usage("generate_cnc_job()")
  8387. # for obj in objects:
  8388. # obj.generatecncjob()
  8389. for obj in objects:
  8390. obj.on_generatecnc_button_click()
  8391. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8392. """
  8393. Saves the current project to the specified file.
  8394. :param filename: Name of the file in which to save.
  8395. :type filename: str
  8396. :param quit_action: if the project saving will be followed by an app quit; boolean
  8397. :param silent: if True will not display status messages
  8398. :param from_tcl True is run from Tcl Shell
  8399. :return: None
  8400. """
  8401. self.log.debug("save_project()")
  8402. self.save_in_progress = True
  8403. with self.proc_container.new(_("Saving FlatCAM Project")):
  8404. # Capture the latest changes
  8405. # Current object
  8406. try:
  8407. current_object = self.collection.get_active()
  8408. if current_object:
  8409. current_object.read_form()
  8410. except Exception as e:
  8411. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8412. pass
  8413. # Serialize the whole project
  8414. d = {
  8415. "objs": [obj.to_dict() for obj in self.collection.get_list()],
  8416. "options": self.options,
  8417. "version": self.version
  8418. }
  8419. if self.defaults["global_save_compressed"] is True:
  8420. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8421. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8422. # # Write
  8423. f.write(g)
  8424. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8425. else:
  8426. # Open file
  8427. try:
  8428. f = open(filename, 'w')
  8429. except IOError:
  8430. App.log.error("Failed to open file for saving: %s", filename)
  8431. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8432. return
  8433. # Write
  8434. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8435. f.close()
  8436. # verification of the saved project
  8437. # Open and parse
  8438. try:
  8439. saved_f = open(filename, 'r')
  8440. except IOError:
  8441. if silent is False:
  8442. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8443. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8444. return
  8445. try:
  8446. saved_d = json.load(saved_f, object_hook=dict2obj)
  8447. except Exception:
  8448. if silent is False:
  8449. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8450. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8451. f.close()
  8452. return
  8453. saved_f.close()
  8454. if silent is False:
  8455. if 'version' in saved_d:
  8456. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8457. else:
  8458. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8459. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8460. tb_settings = QSettings("Open Source", "FlatCAM")
  8461. lock_state = self.ui.lock_action.isChecked()
  8462. tb_settings.setValue('toolbar_lock', lock_state)
  8463. # This will write the setting to the platform specific storage.
  8464. del tb_settings
  8465. # if quit:
  8466. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8467. # t.start()
  8468. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8469. def start_delayed_quit(self, delay, filename, should_quit=None):
  8470. """
  8471. :param delay: period of checking if project file size is more than zero; in seconds
  8472. :param filename: the name of the project file to be checked periodically for size more than zero
  8473. :param should_quit: if the task finished will be followed by an app quit; boolean
  8474. :return:
  8475. """
  8476. to_quit = should_quit
  8477. self.save_timer = QtCore.QTimer()
  8478. self.save_timer.setInterval(delay)
  8479. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8480. self.save_timer.start()
  8481. def check_project_file_size(self, filename, should_quit=None):
  8482. """
  8483. :param filename: the name of the project file to be checked periodically for size more than zero
  8484. :param should_quit: will quit the app if True; boolean
  8485. :return:
  8486. """
  8487. try:
  8488. if os.stat(filename).st_size > 0:
  8489. self.save_in_progress = False
  8490. self.save_timer.stop()
  8491. if should_quit:
  8492. self.app_quit.emit()
  8493. except Exception:
  8494. traceback.print_exc()
  8495. def save_project_auto(self):
  8496. """
  8497. Called periodically to save the project.
  8498. It will save if there is no block on the save, if the project was saved at least once and if there is no save in
  8499. # progress.
  8500. :return:
  8501. """
  8502. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8503. self.on_file_saveproject()
  8504. def save_project_auto_update(self):
  8505. """
  8506. Update the auto save time interval value.
  8507. :return:
  8508. """
  8509. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8510. try:
  8511. if self.autosave_timer.isActive():
  8512. self.autosave_timer.stop()
  8513. except Exception:
  8514. pass
  8515. if self.defaults['global_autosave'] is True:
  8516. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8517. self.autosave_timer.start()
  8518. def on_options_app2project(self):
  8519. """
  8520. Callback for Options->Transfer Options->App=>Project. Copies options
  8521. from application defaults to project defaults.
  8522. :return: None
  8523. """
  8524. self.defaults.report_usage("on_options_app2project")
  8525. self.preferencesUiManager.defaults_read_form()
  8526. self.options.update(self.defaults)
  8527. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8528. """
  8529. Shows a message on the FlatCAM Shell
  8530. :param msg: Message to display.
  8531. :param show: Opens the shell.
  8532. :param error: Shows the message as an error.
  8533. :param warning: Shows the message as an warning.
  8534. :param success: Shows the message as an success.
  8535. :param selected: Indicate that something was selected on canvas
  8536. :return: None
  8537. """
  8538. if show:
  8539. self.ui.shell_dock.show()
  8540. try:
  8541. if error:
  8542. self.shell.append_error(msg + "\n")
  8543. elif warning:
  8544. self.shell.append_warning(msg + "\n")
  8545. elif success:
  8546. self.shell.append_success(msg + "\n")
  8547. elif selected:
  8548. self.shell.append_selected(msg + "\n")
  8549. else:
  8550. self.shell.append_output(msg + "\n")
  8551. except AttributeError:
  8552. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8553. def dec_format(self, val, dec=None):
  8554. """
  8555. Returns a formatted float value with a certain number of decimals
  8556. """
  8557. dec_nr = dec if dec is not None else self.decimals
  8558. return float('%.*f' % (dec_nr, val))
  8559. class ArgsThread(QtCore.QObject):
  8560. open_signal = pyqtSignal(list)
  8561. start = pyqtSignal()
  8562. stop = pyqtSignal()
  8563. if sys.platform == 'win32':
  8564. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8565. else:
  8566. address = ('/tmp/testipc', 'AF_UNIX')
  8567. def __init__(self):
  8568. super().__init__()
  8569. self.listener = None
  8570. self.thread_exit = False
  8571. self.start.connect(self.run)
  8572. self.stop.connect(self.close_listener)
  8573. def my_loop(self, address):
  8574. try:
  8575. self.listener = Listener(*address)
  8576. while self.thread_exit is False:
  8577. conn = self.listener.accept()
  8578. self.serve(conn)
  8579. except socket.error:
  8580. try:
  8581. conn = Client(*address)
  8582. conn.send(sys.argv)
  8583. conn.send('close')
  8584. # close the current instance only if there are args
  8585. if len(sys.argv) > 1:
  8586. try:
  8587. self.listener.close()
  8588. except Exception:
  8589. pass
  8590. sys.exit()
  8591. except ConnectionRefusedError:
  8592. if sys.platform == 'win32':
  8593. pass
  8594. else:
  8595. os.system('rm /tmp/testipc')
  8596. self.listener = Listener(*address)
  8597. while True:
  8598. conn = self.listener.accept()
  8599. self.serve(conn)
  8600. def serve(self, conn):
  8601. while self.thread_exit is False:
  8602. msg = conn.recv()
  8603. if msg == 'close':
  8604. break
  8605. self.open_signal.emit(msg)
  8606. conn.close()
  8607. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8608. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8609. @pyqtSlot()
  8610. def run(self):
  8611. self.my_loop(self.address)
  8612. @pyqtSlot()
  8613. def close_listener(self):
  8614. self.thread_exit = True
  8615. self.listener.close()
  8616. # end of file